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
/*
 * PROJECT:         ReactOS Win32 Base API
 * LICENSE:         GPL - See COPYING in the top level directory
 * FILE:            dll/win32/kernel32/client/path.c
 * PURPOSE:         Handles path APIs
 * PROGRAMMERS:     Alex Ionescu (alex.ionescu@reactos.org)
 */

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

#include <k32.h>

#define NDEBUG
#include <debug.h>

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

UNICODE_STRING NoDefaultCurrentDirectoryInExePath = RTL_CONSTANT_STRING(L"NoDefaultCurrentDirectoryInExePath");

UNICODE_STRING BaseWindowsSystemDirectory, BaseWindowsDirectory;
UNICODE_STRING BaseDefaultPathAppend, BaseDefaultPath, BaseDllDirectory;

PVOID gpTermsrvGetWindowsDirectoryA;
PVOID gpTermsrvGetWindowsDirectoryW;

/* This is bitmask for each illegal filename character */
/* If someone has time, please feel free to use 0b notation */
DWORD IllegalMask[4] =
{
    0xFFFFFFFF, // None allowed (00 to 1F)
    0xFC009C05, // 20, 22, 2A, 2B, 2C, 2F, 3A, 3B, 3C, 3D, 3E, 3F not allowed
    0x38000000, // 5B, 5C, 5D not allowed
    0x10000000  // 7C not allowed
};

BASE_SEARCH_PATH_TYPE BaseDllOrderCurrent[BaseCurrentDirPlacementMax][BaseSearchPathMax] =
{
    {
        BaseSearchPathApp,
        BaseSearchPathCurrent,
        BaseSearchPathDefault,
        BaseSearchPathEnv,
        BaseSearchPathInvalid
    },
    {
        BaseSearchPathApp,
        BaseSearchPathDefault,
        BaseSearchPathCurrent,
        BaseSearchPathEnv,
        BaseSearchPathInvalid
    }
};

BASE_SEARCH_PATH_TYPE BaseProcessOrderNoCurrent[BaseSearchPathMax] =
{
    BaseSearchPathApp,
    BaseSearchPathDefault,
    BaseSearchPathEnv,
    BaseSearchPathInvalid,
    BaseSearchPathInvalid
};

BASE_SEARCH_PATH_TYPE BaseDllOrderNoCurrent[BaseSearchPathMax] =
{
    BaseSearchPathApp,
    BaseSearchPathDll,
    BaseSearchPathDefault,
    BaseSearchPathEnv,
    BaseSearchPathInvalid
};

BASE_SEARCH_PATH_TYPE BaseProcessOrder[BaseSearchPathMax] =
{
    BaseSearchPathApp,
    BaseSearchPathCurrent,
    BaseSearchPathDefault,
    BaseSearchPathEnv,
    BaseSearchPathInvalid
};

BASE_CURRENT_DIR_PLACEMENT BasepDllCurrentDirPlacement = BaseCurrentDirPlacementInvalid;

extern UNICODE_STRING BasePathVariableName;

/* PRIVATE FUNCTIONS **********************************************************/

PWCHAR
WINAPI
BasepEndOfDirName(IN PWCHAR FileName)
{
    PWCHAR FileNameEnd, FileNameSeparator;

    /* Find the first slash */
    FileNameSeparator = wcschr(FileName, OBJ_NAME_PATH_SEPARATOR);
    if (FileNameSeparator)
    {
        /* Find the last one */
        FileNameEnd = wcsrchr(FileNameSeparator, OBJ_NAME_PATH_SEPARATOR);
        ASSERT(FileNameEnd);

        /* Handle the case where they are one and the same */
        if (FileNameEnd == FileNameSeparator) FileNameEnd++;
    }
    else
    {
        /* No directory was specified */
        FileNameEnd = NULL;
    }

    /* Return where the directory ends and the filename starts */
    return FileNameEnd;
}

LPWSTR
WINAPI
BasepComputeProcessPath(IN PBASE_SEARCH_PATH_TYPE PathOrder,
                        IN LPWSTR AppName,
                        IN LPVOID Environment)
{
    PWCHAR PathBuffer, Buffer, AppNameEnd, PathCurrent;
    SIZE_T PathLengthInBytes;
    NTSTATUS Status;
    UNICODE_STRING EnvPath;
    PBASE_SEARCH_PATH_TYPE Order;

    /* Initialize state */
    AppNameEnd = Buffer = PathBuffer = NULL;
    Status = STATUS_SUCCESS;
    PathLengthInBytes = 0;

    /* Loop the ordering array */
    for (Order = PathOrder; *Order != BaseSearchPathInvalid; Order++) {
    switch (*Order)
    {
        /* Compute the size of the DLL path */
        case BaseSearchPathDll:

            /* This path only gets called if SetDllDirectory was called */
            ASSERT(BaseDllDirectory.Buffer != NULL);

            /* Make sure there's a DLL directory size */
            if (BaseDllDirectory.Length)
            {
                /* Add it, plus the separator */
                PathLengthInBytes += BaseDllDirectory.Length + sizeof(L';');
            }
            break;

        /* Compute the size of the current path */
        case BaseSearchPathCurrent:

            /* Add ".;" */
            PathLengthInBytes += (2 * sizeof(WCHAR));
            break;

        /* Compute the size of the "PATH" environment variable */
        case BaseSearchPathEnv:

            /* Grab PEB lock if one wasn't passed in */
            if (!Environment) RtlAcquirePebLock();

            /* Query the size first */
            EnvPath.MaximumLength = 0;
            Status = RtlQueryEnvironmentVariable_U(Environment,
                                                   &BasePathVariableName,
                                                   &EnvPath);
            if (Status == STATUS_BUFFER_TOO_SMALL)
            {
                /* Compute the size we'll need for the environment */
                EnvPath.MaximumLength = EnvPath.Length + sizeof(WCHAR);
                if ((EnvPath.Length + sizeof(WCHAR)) > UNICODE_STRING_MAX_BYTES)
                {
                    /* Don't let it overflow */
                    EnvPath.MaximumLength = EnvPath.Length;
                }

                /* Allocate the environment buffer */
                Buffer = RtlAllocateHeap(RtlGetProcessHeap(),
                                         0,
                                         EnvPath.MaximumLength);
                if (Buffer)
                {
                    /* Now query the PATH environment variable */
                    EnvPath.Buffer = Buffer;
                    Status = RtlQueryEnvironmentVariable_U(Environment,
                                                           &BasePathVariableName,
                                                           &EnvPath);
                }
                else
                {
                    /* Failure case */
                    Status = STATUS_NO_MEMORY;
                }
            }

            /* Release the PEB lock from above */
            if (!Environment) RtlReleasePebLock();

            /* There might not be a PATH */
            if (Status == STATUS_VARIABLE_NOT_FOUND)
            {
                /* In this case, skip this PathOrder */
                EnvPath.Length = EnvPath.MaximumLength = 0;
                Status = STATUS_SUCCESS;
            }
            else if (!NT_SUCCESS(Status))
            {
                /* An early failure, go to exit code */
                goto Quickie;
            }
            else
            {
                /* Add the length of the PATH variable unless it's empty */
                ASSERT(!(EnvPath.Length & 1));
                if (EnvPath.Length)
                {
                    /* Reserve space for the variable and a semicolon */
                    PathLengthInBytes += (EnvPath.Length + sizeof(L';'));
                }
            }
            break;

        /* Compute the size of the default search path */
        case BaseSearchPathDefault:

            /* Just add it... it already has a ';' at the end */
            ASSERT(!(BaseDefaultPath.Length & 1));
            PathLengthInBytes += BaseDefaultPath.Length;
            break;

        /* Compute the size of the current app directory */
        case BaseSearchPathApp:
            /* Find out where the app name ends, to get only the directory */
            if (AppName) AppNameEnd = BasepEndOfDirName(AppName);

            /* Check if there was no application name passed in */
            if (!(AppName) || !(AppNameEnd))
            {
                /* Do we have a per-thread CURDIR to use? */
                if (NtCurrentTeb()->NtTib.SubSystemTib)
                {
                    /* This means someone added RTL_PERTHREAD_CURDIR */
                    UNIMPLEMENTED_DBGBREAK();
                }

                /* We do not. Do we have the LDR_ENTRY for the executable? */
                if (!BasepExeLdrEntry)
                {
                    /* We do not. Grab it */
                    LdrEnumerateLoadedModules(0,
                                              BasepLocateExeLdrEntry,
                                              NtCurrentPeb()->ImageBaseAddress);
                }

                /* Now do we have it? */
                if (BasepExeLdrEntry)
                {
                    /* Yes, so read the name out of it */
                    AppName = BasepExeLdrEntry->FullDllName.Buffer;
                }

                /* Find out where the app name ends, to get only the directory */
                if (AppName) AppNameEnd = BasepEndOfDirName(AppName);
            }

            /* So, do we have an application name and its directory? */
            if ((AppName) && (AppNameEnd))
            {
                /* Add the size of the app's directory, plus the separator */
                PathLengthInBytes += ((AppNameEnd - AppName) * sizeof(WCHAR)) + sizeof(L';');
            }
            break;

        default:
            break;
        }
    }

    /* Bam, all done, we now have the final path size */
    ASSERT(PathLengthInBytes > 0);
    ASSERT(!(PathLengthInBytes & 1));

    /* Allocate the buffer to hold it */
    PathBuffer = RtlAllocateHeap(RtlGetProcessHeap(), 0, PathLengthInBytes);
    if (!PathBuffer)
    {
        /* Failure path */
        Status = STATUS_NO_MEMORY;
        goto Quickie;
    }

    /* Now we loop again, this time to copy the data */
    PathCurrent = PathBuffer;
    for (Order = PathOrder; *Order != BaseSearchPathInvalid; Order++) {
    switch (*Order)
    {
        /* Add the DLL path */
        case BaseSearchPathDll:
            if (BaseDllDirectory.Length)
            {
                /* Copy it in the buffer, ASSERT there's enough space */
                ASSERT((((PathCurrent - PathBuffer + 1) * sizeof(WCHAR)) + BaseDllDirectory.Length) <= PathLengthInBytes);
                RtlCopyMemory(PathCurrent,
                              BaseDllDirectory.Buffer,
                              BaseDllDirectory.Length);

                /* Update the current pointer, add a separator */
                PathCurrent += (BaseDllDirectory.Length / sizeof(WCHAR));
                *PathCurrent++ = ';';
            }
            break;

        /* Add the current application path */
        case BaseSearchPathApp:
            if ((AppName) && (AppNameEnd))
            {
                /* Copy it in the buffer, ASSERT there's enough space */
                ASSERT(((PathCurrent - PathBuffer + 1 + (AppNameEnd - AppName)) * sizeof(WCHAR)) <= PathLengthInBytes);
                RtlCopyMemory(PathCurrent,
                              AppName,
                              (AppNameEnd - AppName) * sizeof(WCHAR));

                /* Update the current pointer, add a separator */
                PathCurrent += AppNameEnd - AppName;
                *PathCurrent++ = ';';
            }
            break;

        /* Add the default search path */
        case BaseSearchPathDefault:
            /* Copy it in the buffer, ASSERT there's enough space */
            ASSERT((((PathCurrent - PathBuffer) * sizeof(WCHAR)) + BaseDefaultPath.Length) <= PathLengthInBytes);
            RtlCopyMemory(PathCurrent, BaseDefaultPath.Buffer, BaseDefaultPath.Length);

            /* Update the current pointer. The default path already has a ";" */
            PathCurrent += (BaseDefaultPath.Length / sizeof(WCHAR));
            break;

        /* Add the path in the PATH environment variable */
        case BaseSearchPathEnv:
            if (EnvPath.Length)
            {
                /* Copy it in the buffer, ASSERT there's enough space */
                ASSERT((((PathCurrent - PathBuffer + 1) * sizeof(WCHAR)) + EnvPath.Length) <= PathLengthInBytes);
                RtlCopyMemory(PathCurrent, EnvPath.Buffer, EnvPath.Length);

                /* Update the current pointer, add a separator */
                PathCurrent += (EnvPath.Length / sizeof(WCHAR));
                *PathCurrent++ = ';';
            }
            break;

        /* Add the current directory */
        case BaseSearchPathCurrent:

            /* Copy it in the buffer, ASSERT there's enough space */
            ASSERT(((PathCurrent - PathBuffer + 2) * sizeof(WCHAR)) <= PathLengthInBytes);
            *PathCurrent++ = '.';

            /* Add the path separator */
            *PathCurrent++ = ';';
            break;

        default:
            break;
        }
    }

    /* Everything should've perfectly fit in there */
    ASSERT((PathCurrent - PathBuffer) * sizeof(WCHAR) == PathLengthInBytes);
    ASSERT(PathCurrent > PathBuffer);

    /* Terminate the whole thing */
    PathCurrent[-1] = UNICODE_NULL;

Quickie:
    /* Exit path: free our buffers */
    if (Buffer) RtlFreeHeap(RtlGetProcessHeap(), 0, Buffer);
    if (PathBuffer)
    {
        /* This only gets freed in the failure path, since caller wants it */
        if (!NT_SUCCESS(Status))
        {
            RtlFreeHeap(RtlGetProcessHeap(), 0, PathBuffer);
            PathBuffer = NULL;
        }
    }

    /* Return the path! */
    return PathBuffer;
}

LPWSTR
WINAPI
BaseComputeProcessSearchPath(VOID)
{
    DPRINT("Computing Process Search path\n");

    /* Compute the path using default process order */
    return BasepComputeProcessPath(BaseProcessOrder, NULL, NULL);
}

LPWSTR
WINAPI
BaseComputeProcessExePath(IN LPWSTR FullPath)
{
    PBASE_SEARCH_PATH_TYPE PathOrder;
    DPRINT("Computing EXE path: %S\n", FullPath);

    /* Check if we should use the current directory */
    PathOrder = NeedCurrentDirectoryForExePathW(FullPath) ?
                BaseProcessOrder : BaseProcessOrderNoCurrent;

    /* And now compute the path */
    return BasepComputeProcessPath(PathOrder, NULL, NULL);
}

LPWSTR
WINAPI
BaseComputeProcessDllPath(IN LPWSTR FullPath,
                          IN PVOID Environment)
{
    LPWSTR DllPath = NULL;
    UNICODE_STRING KeyName = RTL_CONSTANT_STRING(L"\\Registry\\MACHINE\\System\\CurrentControlSet\\Control\\Session Manager");
    UNICODE_STRING ValueName = RTL_CONSTANT_STRING(L"SafeDllSearchMode");
    OBJECT_ATTRIBUTES ObjectAttributes = RTL_CONSTANT_OBJECT_ATTRIBUTES(&KeyName, OBJ_CASE_INSENSITIVE);
    KEY_VALUE_PARTIAL_INFORMATION PartialInfo;
    HANDLE KeyHandle;
    NTSTATUS Status;
    ULONG ResultLength;
    BASE_CURRENT_DIR_PLACEMENT CurrentDirPlacement, OldCurrentDirPlacement;

    /* Acquire DLL directory lock */
    RtlEnterCriticalSection(&BaseDllDirectoryLock);

    /* Check if we have a base dll directory */
    if (BaseDllDirectory.Buffer)
    {
        /* Then compute the process path using DLL order (without curdir) */
        DllPath = BasepComputeProcessPath(BaseDllOrderNoCurrent, FullPath, Environment);

        /* Release DLL directory lock */
        RtlLeaveCriticalSection(&BaseDllDirectoryLock);

        /* Return dll path */
        return DllPath;
    }

    /* Release DLL directory lock */
    RtlLeaveCriticalSection(&BaseDllDirectoryLock);

    /* Read the current placement */
    CurrentDirPlacement = BasepDllCurrentDirPlacement;
    if (CurrentDirPlacement == BaseCurrentDirPlacementInvalid)
    {
        /* Open the configuration key */
        Status = NtOpenKey(&KeyHandle, KEY_QUERY_VALUE, &ObjectAttributes);
        if (NT_SUCCESS(Status))
        {
            /* Query if safe search is enabled */
            Status = NtQueryValueKey(KeyHandle,
                                     &ValueName,
                                     KeyValuePartialInformation,
                                     &PartialInfo,
                                     sizeof(PartialInfo),
                                     &ResultLength);
            if (NT_SUCCESS(Status))
            {
                /* Read the value if the size is OK */
                if (ResultLength == sizeof(PartialInfo))
                {
                    CurrentDirPlacement = *(PULONG)PartialInfo.Data;
                }
            }

            /* Close the handle */
            NtClose(KeyHandle);

            /* Validate the registry value */
            if ((CurrentDirPlacement <= BaseCurrentDirPlacementInvalid) ||
                (CurrentDirPlacement >= BaseCurrentDirPlacementMax))
            {
                /* Default to safe search */
                CurrentDirPlacement = BaseCurrentDirPlacementSafe;
            }
        }

        /* Update the placement and read the old one */
        OldCurrentDirPlacement = InterlockedCompareExchange((PLONG)&BasepDllCurrentDirPlacement,
                                                            CurrentDirPlacement,
                                                            BaseCurrentDirPlacementInvalid);
        if (OldCurrentDirPlacement != BaseCurrentDirPlacementInvalid)
        {
            /* If there already was a placement, use it */
            CurrentDirPlacement = OldCurrentDirPlacement;
        }
    }

    /* Check if the placement is invalid or not set */
    if ((CurrentDirPlacement <= BaseCurrentDirPlacementInvalid) ||
        (CurrentDirPlacement >= BaseCurrentDirPlacementMax))
    {
        /* Default to safe search */
        CurrentDirPlacement = BaseCurrentDirPlacementSafe;
    }

    /* Compute the process path using either normal or safe search */
    DllPath = BasepComputeProcessPath(BaseDllOrderCurrent[CurrentDirPlacement],
                                      FullPath,
                                      Environment);

    /* Return dll path */
    return DllPath;
}

BOOLEAN
WINAPI
CheckForSameCurdir(IN PUNICODE_STRING DirName)
{
    PUNICODE_STRING CurDir;
    USHORT CurLength;
    BOOLEAN Result;
    UNICODE_STRING CurDirCopy;

    CurDir = &NtCurrentPeb()->ProcessParameters->CurrentDirectory.DosPath;

    CurLength = CurDir->Length;
    if (CurDir->Length <= 6)
    {
        if (CurLength != DirName->Length) return FALSE;
    }
    else
    {
        if ((CurLength - 2) != DirName->Length) return FALSE;
    }

    RtlAcquirePebLock();

    CurDirCopy = *CurDir;
    if (CurDirCopy.Length > 6) CurDirCopy.Length -= 2;

    Result = 0;

    if (RtlEqualUnicodeString(&CurDirCopy, DirName, TRUE)) Result = TRUE;

    RtlReleasePebLock();

    return Result;
}

/*
 * Why not use RtlIsNameLegalDOS8Dot3? In fact the actual algorithm body is
 * identical (other than the Rtl can optionally check for spaces), however the
 * Rtl will always convert to OEM, while kernel32 has two possible file modes
 * (ANSI or OEM). Therefore we must duplicate the algorithm body to get
 * the correct compatible results
 */
BOOL
WINAPI
IsShortName_U(IN PWCHAR Name,
              IN ULONG Length)
{
    BOOLEAN HasExtension;
    UCHAR c;
    NTSTATUS Status;
    UNICODE_STRING UnicodeName;
    ANSI_STRING AnsiName;
    ULONG i, Dots;
    CHAR AnsiBuffer[MAX_PATH];
    ASSERT(Name);

    /* What do you think 8.3 means? */
    if (Length > 12) return FALSE;

    /* Sure, any empty name is a short name */
    if (!Length) return TRUE;

    /* This could be . or .. or something else */
    if (*Name == L'.')
    {
        /* Which one is it */
        if ((Length == 1) || ((Length == 2) && *(Name + 1) == L'.'))
        {
            /* . or .., this is good */
            return TRUE;
        }

        /* Some other bizare dot-based name, not good */
        return FALSE;
    }

    /* Initialize our two strings */
    RtlInitEmptyAnsiString(&AnsiName, AnsiBuffer, MAX_PATH);
    RtlInitEmptyUnicodeString(&UnicodeName, Name, (USHORT)Length * sizeof(WCHAR));
    UnicodeName.Length = UnicodeName.MaximumLength;

    /* Now do the conversion */
    Status = BasepUnicodeStringTo8BitString(&AnsiName, &UnicodeName, FALSE);
    if (!NT_SUCCESS(Status)) return FALSE;

    /* Now we loop the name */
    HasExtension = FALSE;
    for (i = 0, Dots = Length - 1; i < AnsiName.Length; i++, Dots--)
    {
        /* Read the current byte */
        c = AnsiName.Buffer[i];

        /* Is it DBCS? */
        if (IsDBCSLeadByte(c))
        {
            /* If we're near the end of the string, we can't allow a DBCS */
            if ((!(HasExtension) && (i >= 7)) || (i == AnsiName.Length - 1))
            {
                return FALSE;
            }

            /* Otherwise we skip over it */
            continue;
        }

        /* Check for illegal characters */
        if ((c > 0x7F) || (IllegalMask[c / 32] & (1 << (c % 32))))
        {
            return FALSE;
        }

        /* Check if this is perhaps an extension? */
        if (c == '.')
        {
            /* Unless the extension is too large or there's more than one */
            if ((HasExtension) || (Dots > 3)) return FALSE;

            /* This looks like an extension */
            HasExtension = TRUE;
        }

        /* 8.3 length was validated, but now we must guard against 9.2 or similar */
        if ((i >= 8) && !(HasExtension)) return FALSE;
    }

    /* You survived the loop, this is a good short name */
    return TRUE;
}

BOOL
WINAPI
IsLongName_U(IN PWCHAR FileName,
             IN ULONG Length)
{
    BOOLEAN HasExtension;
    ULONG i, Dots;

    /* More than 8.3, any combination of dots, and NULL names are all long */
    if (!(Length) || (Length > 12) || (*FileName == L'.')) return TRUE;

    /* Otherwise, initialize our scanning loop */
    HasExtension = FALSE;
    for (i = 0, Dots = Length - 1; i < Length; i++, Dots--)
    {
        /* Check if this could be an extension */
        if (FileName[i] == L'.')
        {
            /* Unlike the short case, we WANT more than one extension, or a long one */
            if ((HasExtension) || (Dots > 3))
            {
                return TRUE;
            }
            HasExtension = TRUE;
        }

        /* Check if this would violate the "8" in 8.3, ie. 9.2 */
        if ((i >= 8) && (!HasExtension)) return TRUE;
    }

    /* The name *seems* to conform to 8.3 */
    return FALSE;
}

BOOL
WINAPI
FindLFNorSFN_U(IN PWCHAR Path,
               OUT PWCHAR *First,
               OUT PWCHAR *Last,
               IN BOOL UseShort)
{
    PWCHAR p;
    ULONG Length;
    BOOL Found = 0;
    ASSERT(Path);

    /* Loop while there is something in the path */
    while (TRUE)
    {
        /* Loop within the path skipping slashes */
        while ((*Path == L'\\') || (*Path == L'/')) Path++;

        /* Make sure there's something after the slashes too! */
        if (*Path == UNICODE_NULL) break;

        /* Now skip past the file name until we get to the first slash */
        p = Path + 1;
        while ((*p) && ((*p != L'\\') && (*p != L'/'))) p++;

        /* Whatever is in between those two is now the file name length */
        Length = p - Path;

        /*
         * Check if it is valid
         * Note that !IsShortName != IsLongName, these two functions simply help
         * us determine if a conversion is necessary or not.
         * "Found" really means: "Is a conversion necessary?", hence the "!"
         */
        Found = UseShort ? !IsShortName_U(Path, Length) : !IsLongName_U(Path, Length);
        if (Found)
        {
            /* It is! did the caller request to know the markers? */
            if ((First) && (Last))
            {
                /* Return them */
                *First = Path;
                *Last = p;
            }
            break;
        }

        /* Is there anything else following this sub-path/filename? */
        if (*p == UNICODE_NULL) break;

        /* Yes, keep going */
        Path = p + 1;
    }

    /* Return if anything was found and valid */
    return Found;
}

PWCHAR
WINAPI
SkipPathTypeIndicator_U(IN LPWSTR Path)
{
    PWCHAR ReturnPath;
    ULONG i;

    /* Check what kind of path this is and how many slashes to skip */
    switch (RtlDetermineDosPathNameType_U(Path))
    {
        case RtlPathTypeUncAbsolute:
        case RtlPathTypeLocalDevice:
        {
            /* Keep going until we bypass the path indicators */
            for (ReturnPath = Path + 2, i = 2; (i > 0) && (*ReturnPath); ReturnPath++)
            {
                /* We look for 2 slashes, so keep at it until we find them */
                if ((*ReturnPath == L'\\') || (*ReturnPath == L'/')) i--;
            }

            return ReturnPath;
        }

        case RtlPathTypeDriveAbsolute:
            return Path + 3;

        case RtlPathTypeDriveRelative:
            return Path + 2;

        case RtlPathTypeRooted:
            return Path + 1;

        case RtlPathTypeRelative:
            return Path;

        case RtlPathTypeRootLocalDevice:
        default:
            return NULL;
    }
}

BOOL
WINAPI
BasepIsCurDirAllowedForPlainExeNames(VOID)
{
    NTSTATUS Status;
    UNICODE_STRING EmptyString;

    RtlInitEmptyUnicodeString(&EmptyString, NULL, 0);
    Status = RtlQueryEnvironmentVariable_U(NULL,
                                           &NoDefaultCurrentDirectoryInExePath,
                                           &EmptyString);
    return !NT_SUCCESS(Status) && Status != STATUS_BUFFER_TOO_SMALL;
}

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

/*
 * @implemented
 */
BOOL
WINAPI
SetDllDirectoryW(IN LPCWSTR lpPathName)
{
    UNICODE_STRING OldDirectory, DllDirectory;

    if (lpPathName)
    {
        if (wcschr(lpPathName, L';'))
        {
            SetLastError(ERROR_INVALID_PARAMETER);
            return FALSE;
        }
        if (!RtlCreateUnicodeString(&DllDirectory, lpPathName))
        {
            SetLastError(ERROR_NOT_ENOUGH_MEMORY);
            return FALSE;
        }
    }
    else
    {
        RtlInitUnicodeString(&DllDirectory, NULL);
    }

    RtlEnterCriticalSection(&BaseDllDirectoryLock);

    OldDirectory = BaseDllDirectory;
    BaseDllDirectory = DllDirectory;

    RtlLeaveCriticalSection(&BaseDllDirectoryLock);

    RtlFreeUnicodeString(&OldDirectory);
    return TRUE;
}

/*
 * @implemented
 */
BOOL
WINAPI
SetDllDirectoryA(IN LPCSTR lpPathName)
{
    ANSI_STRING AnsiDllDirectory;
    UNICODE_STRING OldDirectory, DllDirectory;
    NTSTATUS Status;

    if (lpPathName)
    {
        if (strchr(lpPathName, ';'))
        {
            SetLastError(ERROR_INVALID_PARAMETER);
            return FALSE;
        }

        Status = RtlInitAnsiStringEx(&AnsiDllDirectory, lpPathName);
        if (NT_SUCCESS(Status))
        {
            Status = Basep8BitStringToUnicodeString(&DllDirectory,
                                                    &AnsiDllDirectory,
                                                    TRUE);
        }

        if (!NT_SUCCESS(Status))
        {
            BaseSetLastNTError(Status);
            return FALSE;
        }
    }
    else
    {
        RtlInitUnicodeString(&DllDirectory, NULL);
    }

    RtlEnterCriticalSection(&BaseDllDirectoryLock);

    OldDirectory = BaseDllDirectory;
    BaseDllDirectory = DllDirectory;

    RtlLeaveCriticalSection(&BaseDllDirectoryLock);

    RtlFreeUnicodeString(&OldDirectory);
    return TRUE;
}

/*
 * @implemented
 */
DWORD
WINAPI
GetDllDirectoryW(IN DWORD nBufferLength,
                 OUT LPWSTR lpBuffer)
{
    ULONG Length;

    RtlEnterCriticalSection(&BaseDllDirectoryLock);

    if ((nBufferLength * sizeof(WCHAR)) > BaseDllDirectory.Length)
    {
        RtlCopyMemory(lpBuffer, BaseDllDirectory.Buffer, BaseDllDirectory.Length);
        Length = BaseDllDirectory.Length / sizeof(WCHAR);
        lpBuffer[Length] = UNICODE_NULL;
    }
    else
    {
        Length = (BaseDllDirectory.Length + sizeof(UNICODE_NULL)) / sizeof(WCHAR);
        if (lpBuffer) *lpBuffer = UNICODE_NULL;
    }

    RtlLeaveCriticalSection(&BaseDllDirectoryLock);
    return Length;
}

/*
 * @implemented
 */
DWORD
WINAPI
GetDllDirectoryA(IN DWORD nBufferLength,
                 OUT LPSTR lpBuffer)
{
    NTSTATUS Status;
    ANSI_STRING AnsiDllDirectory;
    ULONG Length;

    RtlInitEmptyAnsiString(&AnsiDllDirectory, lpBuffer, (USHORT)nBufferLength);

    RtlEnterCriticalSection(&BaseDllDirectoryLock);

    Length = BasepUnicodeStringTo8BitSize(&BaseDllDirectory);
    if (Length > nBufferLength)
    {
        Status = STATUS_SUCCESS;
        if (lpBuffer) *lpBuffer = ANSI_NULL;
    }
    else
    {
        --Length;
        Status = BasepUnicodeStringTo8BitString(&AnsiDllDirectory,
                                                &BaseDllDirectory,
                                                FALSE);
    }

    RtlLeaveCriticalSection(&BaseDllDirectoryLock);

    if (!NT_SUCCESS(Status))
    {
        BaseSetLastNTError(Status);
        Length = 0;
        if (lpBuffer) *lpBuffer = ANSI_NULL;
    }

    return Length;
}

/*
 * @implemented
 */
BOOL
WINAPI
NeedCurrentDirectoryForExePathW(IN LPCWSTR ExeName)
{
    if (wcschr(ExeName, L'\\')) return TRUE;

    return BasepIsCurDirAllowedForPlainExeNames();
}

/*
 * @implemented
 */
BOOL
WINAPI
NeedCurrentDirectoryForExePathA(IN LPCSTR ExeName)
{
    if (strchr(ExeName, '\\')) return TRUE;

    return BasepIsCurDirAllowedForPlainExeNames();
}

/*
 * @implemented
 *
 * NOTE: Many of these A functions may seem to do rather complex A<->W mapping
 * beyond what you would usually expect. There are two main reasons:
 *
 * First, these APIs are subject to the ANSI/OEM File API selection status that
 * the caller has chosen, so we must use the "8BitString" internal Base APIs.
 *
 * Secondly, the Wide APIs (coming from the 9x world) are coded to return the
 * length of the paths in "ANSI" by dividing their internal Wide character count
 * by two... this is usually correct when dealing with pure-ASCII codepages but
 * not necessarily when dealing with MBCS pre-Unicode sets, which NT supports
 * for CJK, for example.
 */
DWORD
WINAPI
GetFullPathNameA(IN LPCSTR lpFileName,
                 IN DWORD nBufferLength,
                 OUT LPSTR lpBuffer,
                 OUT LPSTR *lpFilePart)
{
    NTSTATUS Status;
    PWCHAR Buffer = NULL;
    ULONG PathSize, FilePartSize;
    ANSI_STRING AnsiString;
    UNICODE_STRING FileNameString, UniString;
    PWCHAR LocalFilePart;
    PWCHAR* FilePart;

    /* If the caller wants filepart, use a local wide buffer since this is A */
    FilePart = lpFilePart != NULL ? &LocalFilePart : NULL;

    /* Initialize for Quickie */
    FilePartSize = PathSize = 0;
    FileNameString.Buffer = NULL;

    /* First get our string in Unicode */
    Status = Basep8BitStringToDynamicUnicodeString(&FileNameString, lpFileName);
    if (!NT_SUCCESS(Status)) goto Quickie;

    /* Allocate a buffer to hold teh path name */
    Buffer = RtlAllocateHeap(RtlGetProcessHeap(),
                             0,
                             MAX_PATH * sizeof(WCHAR) + sizeof(UNICODE_NULL));
    if (!Buffer)
    {
        BaseSetLastNTError(STATUS_INSUFFICIENT_RESOURCES);
        goto Quickie;
    }

    /* Call into RTL to get the full Unicode path name */
    PathSize = RtlGetFullPathName_U(FileNameString.Buffer,
                                    MAX_PATH * sizeof(WCHAR),
                                    Buffer,
                                    FilePart);
    if (PathSize <= (MAX_PATH * sizeof(WCHAR)))
    {
        /* The buffer will fit, get the real ANSI string size now */
        Status = RtlUnicodeToMultiByteSize(&PathSize, Buffer, PathSize);
        if (NT_SUCCESS(Status))
        {
            /* Now check if the user wanted file part size as well */
            if ((PathSize) && (lpFilePart) && (LocalFilePart))
            {
                /* Yep, so in this case get the length of the file part too */
                Status = RtlUnicodeToMultiByteSize(&FilePartSize,
                                                   Buffer,
                                                   (ULONG)(LocalFilePart - Buffer) *
                                                   sizeof(WCHAR));
                if (!NT_SUCCESS(Status))
                {
                    /* We failed to do that, so fail the whole call */
                    BaseSetLastNTError(Status);
                    PathSize = 0;
                }
            }
        }
    }
    else
    {
        /* Reset the path size since the buffer is not large enough */
        PathSize = 0;
    }

    /* Either no path, or local buffer was too small, enter failure code */
    if (!PathSize) goto Quickie;

    /* If the *caller's* buffer was too small, fail, but add in space for NULL */
    if (PathSize >= nBufferLength)
    {
        PathSize++;
        goto Quickie;
    }

    /* So far so good, initialize a unicode string to convert back to ANSI/OEM */
    RtlInitUnicodeString(&UniString, Buffer);
    Status = BasepUnicodeStringTo8BitString(&AnsiString, &UniString, TRUE);
    if (!NT_SUCCESS(Status))
    {
        /* Final conversion failed, fail the call */
        BaseSetLastNTError(Status);
        PathSize = 0;
    }
    else
    {
        /* Conversion worked, now copy the ANSI/OEM buffer into the buffer */
        RtlCopyMemory(lpBuffer, AnsiString.Buffer, PathSize + 1);
        RtlFreeAnsiString(&AnsiString);

        /* And finally, did the caller request file part information? */
        if (lpFilePart)
        {
            /* Use the size we computed earlier and add it to the buffer */
            *lpFilePart = LocalFilePart ? &lpBuffer[FilePartSize] : 0;
        }
    }

Quickie:
    /* Cleanup and return the path size */
    if (FileNameString.Buffer) RtlFreeUnicodeString(&FileNameString);
    if (Buffer) RtlFreeHeap(RtlGetProcessHeap(), 0, Buffer);
    return PathSize;
}

/*
 * @implemented
 */
DWORD
WINAPI
GetFullPathNameW(IN LPCWSTR lpFileName,
                 IN DWORD nBufferLength,
                 OUT LPWSTR lpBuffer,
                 OUT LPWSTR *lpFilePart)
{
    /* Call Rtl to do the work */
    return RtlGetFullPathName_U(lpFileName,
                                nBufferLength * sizeof(WCHAR),
                                lpBuffer,
                                lpFilePart) / sizeof(WCHAR);
}

/*
 * @implemented
 */
DWORD
WINAPI
SearchPathA(IN LPCSTR lpPath OPTIONAL,
            IN LPCSTR lpFileName,
            IN LPCSTR lpExtension OPTIONAL,
            IN DWORD nBufferLength,
            OUT LPSTR lpBuffer,
            OUT LPSTR *lpFilePart OPTIONAL)
{
    PUNICODE_STRING FileNameString;
    UNICODE_STRING PathString, ExtensionString;
    NTSTATUS Status;
    ULONG PathSize, FilePartSize, AnsiLength;
    PWCHAR LocalFilePart, Buffer;
    PWCHAR* FilePart;

    /* If the caller wants filepart, use a local wide buffer since this is A */
    FilePart = lpFilePart != NULL ? &LocalFilePart : NULL;

    /* Initialize stuff for Quickie */
    PathSize = 0;
    Buffer = NULL;
    ExtensionString.Buffer = PathString.Buffer = NULL;

    /* Get the UNICODE_STRING file name */
    FileNameString = Basep8BitStringToStaticUnicodeString(lpFileName);
    if (!FileNameString) return 0;

    /* Did the caller specify an extension */
    if (lpExtension)
    {
        /* Yup, convert it into UNICODE_STRING */
        Status = Basep8BitStringToDynamicUnicodeString(&ExtensionString,
                                                       lpExtension);
        if (!NT_SUCCESS(Status)) goto Quickie;
    }

    /* Did the caller specify a path */
    if (lpPath)
    {
        /* Yup, convert it into UNICODE_STRING */
        Status = Basep8BitStringToDynamicUnicodeString(&PathString, lpPath);
        if (!NT_SUCCESS(Status)) goto Quickie;
    }

    /* Allocate our output buffer */
    Buffer = RtlAllocateHeap(RtlGetProcessHeap(), 0, nBufferLength * sizeof(WCHAR));
    if (!Buffer)
    {
        /* It failed, bail out */
        BaseSetLastNTError(STATUS_NO_MEMORY);
        goto Quickie;
    }

    /* Now run the Wide search with the input buffer lengths */
    PathSize = SearchPathW(PathString.Buffer,
                           FileNameString->Buffer,
                           ExtensionString.Buffer,
                           nBufferLength,
                           Buffer,
                           FilePart);
    if (PathSize <= nBufferLength)
    {
        /* It fits, but is it empty? If so, bail out */
        if (!PathSize) goto Quickie;

        /* The length above is inexact, we need it in ANSI */
        Status = RtlUnicodeToMultiByteSize(&AnsiLength, Buffer, PathSize * sizeof(WCHAR));
        if (!NT_SUCCESS(Status))
        {
            /* Conversion failed, fail the call */
            PathSize = 0;
            BaseSetLastNTError(Status);
            goto Quickie;
        }

        /* If the correct ANSI size is too big, return required length plus a NULL */
        if (AnsiLength >= nBufferLength)
        {
            PathSize = AnsiLength + 1;
            goto Quickie;
        }

        /* Now apply the final conversion to ANSI */
        Status = RtlUnicodeToMultiByteN(lpBuffer,
                                        nBufferLength - 1,
                                        &AnsiLength,
                                        Buffer,
                                        PathSize * sizeof(WCHAR));
        if (!NT_SUCCESS(Status))
        {
            /* Conversion failed, fail the whole call */
            PathSize = 0;
            BaseSetLastNTError(STATUS_NO_MEMORY);
            goto Quickie;
        }

        /* NULL-terminate and return the real ANSI length */
        lpBuffer[AnsiLength] = ANSI_NULL;
        PathSize = AnsiLength;

        /* Now check if the user wanted file part size as well */
        if (lpFilePart)
        {
            /* If we didn't get a file part, clear the caller's */
            if (!LocalFilePart)
            {
                *lpFilePart = NULL;
            }
            else
            {
                /* Yep, so in this case get the length of the file part too */
                Status = RtlUnicodeToMultiByteSize(&FilePartSize,
                                                   Buffer,
                                                   (ULONG)(LocalFilePart - Buffer) *
                                                   sizeof(WCHAR));
                if (!NT_SUCCESS(Status))
                {
                    /* We failed to do that, so fail the whole call */
                    BaseSetLastNTError(Status);
                    PathSize = 0;
                }

                /* Return the file part buffer */
                *lpFilePart = lpBuffer + FilePartSize;
            }
        }
    }
    else
    {
        /* Our initial buffer guess was too small, allocate a bigger one */
        RtlFreeHeap(RtlGetProcessHeap(), 0, Buffer);
        Buffer = RtlAllocateHeap(RtlGetProcessHeap(), 0, PathSize * sizeof(WCHAR));
        if (!Buffer)
        {
            /* Out of memory, fail everything */
            BaseSetLastNTError(STATUS_NO_MEMORY);
            goto Quickie;
        }

        /* Do the search again -- it will fail, we just want the path size */
        PathSize = SearchPathW(PathString.Buffer,
                               FileNameString->Buffer,
                               ExtensionString.Buffer,
                               PathSize,
                               Buffer,
                               FilePart);
        if (!PathSize) goto Quickie;

        /* Convert it to a correct size */
        Status = RtlUnicodeToMultiByteSize(&PathSize, Buffer, PathSize * sizeof(WCHAR));
        if (NT_SUCCESS(Status))
        {
            /* Make space for the NULL-char */
            PathSize++;
        }
        else
        {
            /* Conversion failed for some reason, fail the call */
            BaseSetLastNTError(Status);
            PathSize = 0;
        }
    }

Quickie:
    /* Cleanup/complete path */
    if (Buffer) RtlFreeHeap(RtlGetProcessHeap(), 0, Buffer);
    if (ExtensionString.Buffer) RtlFreeUnicodeString(&ExtensionString);
    if (PathString.Buffer) RtlFreeUnicodeString(&PathString);
    return PathSize;
}

/*
 * @implemented
 */
DWORD
WINAPI
SearchPathW(IN LPCWSTR lpPath OPTIONAL,
            IN LPCWSTR lpFileName,
            IN LPCWSTR lpExtension OPTIONAL,
            IN DWORD nBufferLength,
            OUT LPWSTR lpBuffer,
            OUT LPWSTR *lpFilePart OPTIONAL)
{
    UNICODE_STRING FileNameString, ExtensionString, PathString, CallerBuffer;
    ULONG Flags;
    SIZE_T LengthNeeded, FilePartSize;
    NTSTATUS Status;
    DWORD Result = 0;

    /* Default flags for RtlDosSearchPath_Ustr */
    Flags = 6;

    /* Clear file part in case we fail */
    if (lpFilePart) *lpFilePart = NULL;

    /* Initialize path buffer for free later */
    PathString.Buffer = NULL;

    /* Convert filename to a unicode string and eliminate trailing spaces */
    RtlInitUnicodeString(&FileNameString, lpFileName);
    while ((FileNameString.Length >= sizeof(WCHAR)) &&
           (FileNameString.Buffer[(FileNameString.Length / sizeof(WCHAR)) - 1] == L' '))
    {
        FileNameString.Length -= sizeof(WCHAR);
    }

    /* Was it all just spaces? */
    if (!FileNameString.Length)
    {
        /* Fail out */
        BaseSetLastNTError(STATUS_INVALID_PARAMETER);
        goto Quickie;
    }

    /* Convert extension to a unicode string */
    RtlInitUnicodeString(&ExtensionString, lpExtension);

    /* Check if the user sent a path */
    if (lpPath)
    {
        /* Convert it to a unicode string too */
        Status = RtlInitUnicodeStringEx(&PathString, lpPath);
        if (NT_ERROR(Status))
        {
            /* Fail if it was too long */
            BaseSetLastNTError(Status);
            goto Quickie;
        }
    }
    else
    {
        /* A path wasn't sent, so compute it ourselves */
        PathString.Buffer = BaseComputeProcessSearchPath();
        if (!PathString.Buffer)
        {
            /* Fail if we couldn't compute it */
            BaseSetLastNTError(STATUS_NO_MEMORY);
            goto Quickie;
        }

        /* See how big the computed path is */
        LengthNeeded = lstrlenW(PathString.Buffer);
        if (LengthNeeded > UNICODE_STRING_MAX_CHARS)
        {
            /* Fail if it's too long */
            BaseSetLastNTError(STATUS_NAME_TOO_LONG);
            goto Quickie;
        }

        /* Set the path size now that we have it */
        PathString.MaximumLength = PathString.Length = (USHORT)LengthNeeded * sizeof(WCHAR);

        /* Request SxS isolation from RtlDosSearchPath_Ustr */
        Flags |= 1;
    }

    /* Create the string that describes the output buffer from the caller */
    CallerBuffer.Length = 0;
    CallerBuffer.Buffer = lpBuffer;

    /* How much space does the caller have? */
    if (nBufferLength <= UNICODE_STRING_MAX_CHARS)
    {
        /* Add it into the string */
        CallerBuffer.MaximumLength = (USHORT)nBufferLength * sizeof(WCHAR);
    }
    else
    {
        /* Caller wants too much, limit it to the maximum length of a string */
        CallerBuffer.MaximumLength = UNICODE_STRING_MAX_BYTES;
    }

    /* Call Rtl to do the work */
    Status = RtlDosSearchPath_Ustr(Flags,
                                   &PathString,
                                   &FileNameString,
                                   &ExtensionString,
                                   &CallerBuffer,
                                   NULL,
                                   NULL,
                                   &FilePartSize,
                                   &LengthNeeded);
    if (NT_ERROR(Status))
    {
        /* Check for unusual status codes */
        if ((Status != STATUS_NO_SUCH_FILE) && (Status != STATUS_BUFFER_TOO_SMALL))
        {
            /* Print them out since maybe an app needs fixing */
            DbgPrint("%s on file %wZ failed; NTSTATUS = %08lx\n",
                     __FUNCTION__,
                     &FileNameString,
                     Status);
            DbgPrint("    Path = %wZ\n", &PathString);
        }

        /* Check if the failure was due to a small buffer */
        if (Status == STATUS_BUFFER_TOO_SMALL)
        {
            /* Check if the length was actually too big for Rtl to work with */
            Result = LengthNeeded / sizeof(WCHAR);
            if (Result > 0xFFFFFFFF) BaseSetLastNTError(STATUS_NAME_TOO_LONG);
        }
        else
        {
            /* Some other error, set the error code */
            BaseSetLastNTError(Status);
        }
    }
    else
    {
        /* It worked! Write the file part now */
        if (lpFilePart) *lpFilePart = &lpBuffer[FilePartSize];

        /* Convert the final result length */
        Result = CallerBuffer.Length / sizeof(WCHAR);
    }

Quickie:
    /* Check if there was a dynamic path string to free */
    if ((PathString.Buffer != lpPath) && (PathString.Buffer))
    {
        /* And free it */
        RtlFreeHeap(RtlGetProcessHeap(), 0, PathString.Buffer);
    }

    /* Return the final result length */
    return Result;
}

/*
 * @implemented
 */
DWORD
WINAPI
GetLongPathNameW(IN LPCWSTR lpszShortPath,
                 OUT LPWSTR lpszLongPath,
                 IN DWORD cchBuffer)
{
    PWCHAR Path, Original, First, Last, Buffer, Src, Dst;
    SIZE_T Length, ReturnLength;
    WCHAR LastChar;
    HANDLE FindHandle;
    ULONG ErrorMode;
    BOOLEAN Found = FALSE;
    WIN32_FIND_DATAW FindFileData;

    /* Initialize so Quickie knows there's nothing to do */
    Buffer = Original = NULL;
    ReturnLength = 0;

    /* First check if the input path was obviously NULL */
    if (!lpszShortPath)
    {
        /* Fail the request */
        SetLastError(ERROR_INVALID_PARAMETER);
        return 0;
    }

    /* We will be touching removed, removable drives -- don't warn the user */
    ErrorMode = SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);

    /* Do a simple check to see if the path exists */
    if (GetFileAttributesW(lpszShortPath) == INVALID_FILE_ATTRIBUTES)
    {
        /* It doesn't, so fail */
        ReturnLength = 0;
        goto Quickie;
    }

    /* Now get a pointer to the actual path, skipping indicators */
    Path = SkipPathTypeIndicator_U((LPWSTR)lpszShortPath);

    /* Is there any path or filename in there? */
    if (!(Path) ||
        (*Path == UNICODE_NULL) ||
        !(FindLFNorSFN_U(Path, &First, &Last, FALSE)))
    {
        /* There isn't, so the long path is simply the short path */
        ReturnLength = wcslen(lpszShortPath);

        /* Is there space for it? */
        if ((cchBuffer > ReturnLength) && (lpszLongPath))
        {
            /* Make sure the pointers aren't already the same */
            if (lpszLongPath != lpszShortPath)
            {
                /* They're not -- copy the short path into the long path */
                RtlMoveMemory(lpszLongPath,
                              lpszShortPath,
                              ReturnLength * sizeof(WCHAR) + sizeof(UNICODE_NULL));
            }
        }
        else
        {
            /* Otherwise, let caller know we need a bigger buffer, include NULL */
            ReturnLength++;
        }
        goto Quickie;
    }

    /* We are still in the game -- compute the current size */
    Length = wcslen(lpszShortPath) + sizeof(ANSI_NULL);
    Original = RtlAllocateHeap(RtlGetProcessHeap(), 0, Length * sizeof(WCHAR));
    if (!Original) goto ErrorQuickie;

    /* Make a copy of it */
    RtlMoveMemory(Original, lpszShortPath, Length * sizeof(WCHAR));

    /* Compute the new first and last markers */
    First = &Original[First - lpszShortPath];
    Last = &Original[Last - lpszShortPath];

    /* Set the current destination pointer for a copy */
    Dst = lpszLongPath;

    /*
     * Windows allows the paths to overlap -- we have to be careful with this and
     * see if it's same to do so, and if not, allocate our own internal buffer
     * that we'll return at the end.
     *
     * This is also why we use RtlMoveMemory everywhere. Don't use RtlCopyMemory!
     */
    if ((cchBuffer) && (lpszLongPath) &&
        (((lpszLongPath >= lpszShortPath) && (lpszLongPath < &lpszShortPath[Length])) ||
         ((lpszLongPath < lpszShortPath) && (&lpszLongPath[cchBuffer] >= lpszShortPath))))
    {
        Buffer = RtlAllocateHeap(RtlGetProcessHeap(), 0, cchBuffer * sizeof(WCHAR));
        if (!Buffer) goto ErrorQuickie;

        /* New destination */
        Dst = Buffer;
    }

    /* Prepare for the loop */
    Src = Original;
    ReturnLength = 0;
    while (TRUE)
    {
        /* Current delta in the loop */
        Length = First - Src;

        /* Update the return length by it */
        ReturnLength += Length;

        /* Is there a delta? If so, is there space and buffer for it? */
        if ((Length) && (cchBuffer > ReturnLength) && (lpszLongPath))
        {
            RtlMoveMemory(Dst, Src, Length * sizeof(WCHAR));
            Dst += Length;
        }

        /* "Terminate" this portion of the path's substring so we can do a find */
        LastChar = *Last;
        *Last = UNICODE_NULL;<--- *Last is assigned
        FindHandle = FindFirstFileW(Original, &FindFileData);
        *Last = LastChar;<--- *Last is overwritten

        /* This portion wasn't found, so fail */
        if (FindHandle == INVALID_HANDLE_VALUE)
        {
            ReturnLength = 0;
            break;
        }

        /* Close the find handle */
        FindClose(FindHandle);

        /* Now check the length of the long name */
        Length = wcslen(FindFileData.cFileName);
        if (Length)
        {
            /* This is our new first marker */
            First = FindFileData.cFileName;
        }
        else
        {
            /* Otherwise, the name is the delta between our current markers */
            Length = Last - First;
        }

        /* Update the return length with the short name length, if any */
        ReturnLength += Length;

        /* Once again check for appropriate space and buffer */
        if ((cchBuffer > ReturnLength) && (lpszLongPath))
        {
            /* And do the copy if there is */
            RtlMoveMemory(Dst, First, Length * sizeof(WCHAR));
            Dst += Length;
        }

        /* Now update the source pointer */
        Src = Last;
        if (*Src == UNICODE_NULL) break;

        /* Are there more names in there? */
        Found = FindLFNorSFN_U(Src, &First, &Last, FALSE);
        if (!Found) break;
    }

    /* The loop is done, is there anything left? */
    if (ReturnLength)
    {
        /* Get the length of the straggling path */
        Length = wcslen(Src);
        ReturnLength += Length;

        /* Once again check for appropriate space and buffer */
        if ((cchBuffer > ReturnLength) && (lpszLongPath))
        {
            /* And do the copy if there is -- accounting for NULL here */
            RtlMoveMemory(Dst, Src, Length * sizeof(WCHAR) + sizeof(UNICODE_NULL));

            /* What about our buffer? */
            if (Buffer)
            {
                /* Copy it into the caller's long path */
                RtlMoveMemory(lpszLongPath,
                              Buffer,
                              ReturnLength * sizeof(WCHAR)  + sizeof(UNICODE_NULL));
            }
        }
        else
        {
            /* Buffer is too small, let the caller know, making space for NULL */
            ReturnLength++;
        }
    }

    /* We're all done */
    goto Quickie;

ErrorQuickie:
    /* This is the goto for memory failures */
    SetLastError(ERROR_NOT_ENOUGH_MEMORY);

Quickie:
    /* General function end: free memory, restore error mode, return length */
    if (Original) RtlFreeHeap(RtlGetProcessHeap(), 0, Original);
    if (Buffer) RtlFreeHeap(RtlGetProcessHeap(), 0, Buffer);
    SetErrorMode(ErrorMode);
    return ReturnLength;
}

/*
 * @implemented
 */
DWORD
WINAPI
GetLongPathNameA(IN LPCSTR lpszShortPath,
                 OUT LPSTR lpszLongPath,
                 IN DWORD cchBuffer)
{
    ULONG Result, PathLength;
    PWCHAR LongPath;
    NTSTATUS Status;
    UNICODE_STRING LongPathUni, ShortPathUni;
    ANSI_STRING LongPathAnsi;
    WCHAR LongPathBuffer[MAX_PATH];

    LongPath = NULL;
    LongPathAnsi.Buffer = NULL;
    ShortPathUni.Buffer = NULL;
    Result = 0;

    if (!lpszShortPath)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return 0;
    }

    Status = Basep8BitStringToDynamicUnicodeString(&ShortPathUni, lpszShortPath);
    if (!NT_SUCCESS(Status)) goto Quickie;

    LongPath = LongPathBuffer;

    PathLength = GetLongPathNameW(ShortPathUni.Buffer, LongPathBuffer, MAX_PATH);
    if (PathLength >= MAX_PATH)
    {
        LongPath = RtlAllocateHeap(RtlGetProcessHeap(), 0, PathLength * sizeof(WCHAR));
        if (!LongPath)
        {
            PathLength = 0;
            SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        }
        else
        {
            PathLength = GetLongPathNameW(ShortPathUni.Buffer, LongPath, PathLength);
        }
    }

    if (!PathLength) goto Quickie;

    ShortPathUni.MaximumLength = (USHORT)PathLength * sizeof(WCHAR) + sizeof(UNICODE_NULL);
    LongPathUni.Buffer = LongPath;
    LongPathUni.Length = (USHORT)PathLength * sizeof(WCHAR);

    Status = BasepUnicodeStringTo8BitString(&LongPathAnsi, &LongPathUni, TRUE);
    if (!NT_SUCCESS(Status))
    {
        BaseSetLastNTError(Status);
        Result = 0;
    }

    Result = LongPathAnsi.Length;
    if ((lpszLongPath) && (cchBuffer > LongPathAnsi.Length))
    {
        RtlMoveMemory(lpszLongPath, LongPathAnsi.Buffer, LongPathAnsi.Length);
        lpszLongPath[Result] = ANSI_NULL;
    }
    else
    {
        Result = LongPathAnsi.Length + sizeof(ANSI_NULL);
    }

Quickie:
    if (ShortPathUni.Buffer) RtlFreeUnicodeString(&ShortPathUni);
    if (LongPathAnsi.Buffer) RtlFreeAnsiString(&LongPathAnsi);
    if ((LongPath) && (LongPath != LongPathBuffer))
    {
        RtlFreeHeap(RtlGetProcessHeap(), 0, LongPath);
    }
    return Result;
}

/*
 * @implemented
 */
DWORD
WINAPI
GetShortPathNameA(IN LPCSTR lpszLongPath,
                  OUT LPSTR lpszShortPath,
                  IN DWORD cchBuffer)
{
    ULONG Result, PathLength;
    PWCHAR ShortPath;
    NTSTATUS Status;
    UNICODE_STRING LongPathUni, ShortPathUni;
    ANSI_STRING ShortPathAnsi;
    WCHAR ShortPathBuffer[MAX_PATH];

    ShortPath = NULL;
    ShortPathAnsi.Buffer = NULL;
    LongPathUni.Buffer = NULL;
    Result = 0;

    if (!lpszLongPath)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return 0;
    }

    Status = Basep8BitStringToDynamicUnicodeString(&LongPathUni, lpszLongPath);
    if (!NT_SUCCESS(Status)) goto Quickie;

    ShortPath = ShortPathBuffer;

    PathLength = GetShortPathNameW(LongPathUni.Buffer, ShortPathBuffer, MAX_PATH);
    if (PathLength >= MAX_PATH)
    {
        ShortPath = RtlAllocateHeap(RtlGetProcessHeap(), 0, PathLength * sizeof(WCHAR));
        if (!ShortPath)
        {
            PathLength = 0;
            SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        }
        else
        {
            PathLength = GetShortPathNameW(LongPathUni.Buffer, ShortPath, PathLength);
        }
    }

    if (!PathLength) goto Quickie;

    LongPathUni.MaximumLength = (USHORT)PathLength * sizeof(WCHAR) + sizeof(UNICODE_NULL);
    ShortPathUni.Buffer = ShortPath;
    ShortPathUni.Length = (USHORT)PathLength * sizeof(WCHAR);

    Status = BasepUnicodeStringTo8BitString(&ShortPathAnsi, &ShortPathUni, TRUE);
    if (!NT_SUCCESS(Status))
    {
        BaseSetLastNTError(Status);
        Result = 0;
    }

    Result = ShortPathAnsi.Length;
    if ((lpszShortPath) && (cchBuffer > ShortPathAnsi.Length))
    {
        RtlMoveMemory(lpszShortPath, ShortPathAnsi.Buffer, ShortPathAnsi.Length);
        lpszShortPath[Result] = ANSI_NULL;
    }
    else
    {
        Result = ShortPathAnsi.Length + sizeof(ANSI_NULL);
    }

Quickie:
    if (LongPathUni.Buffer) RtlFreeUnicodeString(&LongPathUni);
    if (ShortPathAnsi.Buffer) RtlFreeAnsiString(&ShortPathAnsi);
    if ((ShortPath) && (ShortPath != ShortPathBuffer))
    {
        RtlFreeHeap(RtlGetProcessHeap(), 0, ShortPath);
    }
    return Result;
}

/*
 * @implemented
 */
DWORD
WINAPI
GetShortPathNameW(IN LPCWSTR lpszLongPath,
                  OUT LPWSTR lpszShortPath,
                  IN DWORD cchBuffer)
{
    PWCHAR Path, Original, First, Last, Buffer, Src, Dst;
    SIZE_T Length, ReturnLength;
    WCHAR LastChar;
    HANDLE FindHandle;
    ULONG ErrorMode;
    BOOLEAN Found = FALSE;
    WIN32_FIND_DATAW FindFileData;

    /* Initialize so Quickie knows there's nothing to do */
    Buffer = Original = NULL;
    ReturnLength = 0;

    /* First check if the input path was obviously NULL */
    if (!lpszLongPath)
    {
        /* Fail the request */
        SetLastError(ERROR_INVALID_PARAMETER);
        return 0;
    }

    /* We will be touching removed, removable drives -- don't warn the user */
    ErrorMode = SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);

    /* Do a simple check to see if the path exists */
    if (GetFileAttributesW(lpszLongPath) == INVALID_FILE_ATTRIBUTES)
    {
        /* Windows checks for an application compatibility flag to allow this */
        if (!(NtCurrentPeb()) || !(NtCurrentPeb()->AppCompatFlags.LowPart & GetShortPathNameNT4))
        {
            /* It doesn't, so fail */
            ReturnLength = 0;
            goto Quickie;
        }
    }

    /* Now get a pointer to the actual path, skipping indicators */
    Path = SkipPathTypeIndicator_U((LPWSTR)lpszLongPath);

    /* Is there any path or filename in there? */
    if (!(Path) ||
        (*Path == UNICODE_NULL) ||
        !(FindLFNorSFN_U(Path, &First, &Last, TRUE)))
    {
        /* There isn't, so the long path is simply the short path */
        ReturnLength = wcslen(lpszLongPath);

        /* Is there space for it? */
        if ((cchBuffer > ReturnLength) && (lpszShortPath))
        {
            /* Make sure the pointers aren't already the same */
            if (lpszLongPath != lpszShortPath)
            {
                /* They're not -- copy the short path into the long path */
                RtlMoveMemory(lpszShortPath,
                              lpszLongPath,
                              ReturnLength * sizeof(WCHAR) + sizeof(UNICODE_NULL));
            }
        }
        else
        {
            /* Otherwise, let caller know we need a bigger buffer, include NULL */
            ReturnLength++;
        }
        goto Quickie;
    }

    /* We are still in the game -- compute the current size */
    Length = wcslen(lpszLongPath) + sizeof(ANSI_NULL);
    Original = RtlAllocateHeap(RtlGetProcessHeap(), 0, Length * sizeof(WCHAR));
    if (!Original) goto ErrorQuickie;

    /* Make a copy of it */
    wcsncpy(Original, lpszLongPath, Length);

    /* Compute the new first and last markers */
    First = &Original[First - lpszLongPath];
    Last = &Original[Last - lpszLongPath];

    /* Set the current destination pointer for a copy */
    Dst = lpszShortPath;

    /*
     * Windows allows the paths to overlap -- we have to be careful with this and
     * see if it's same to do so, and if not, allocate our own internal buffer
     * that we'll return at the end.
     *
     * This is also why we use RtlMoveMemory everywhere. Don't use RtlCopyMemory!
     */
    if ((cchBuffer) && (lpszShortPath) &&
        (((lpszShortPath >= lpszLongPath) && (lpszShortPath < &lpszLongPath[Length])) ||
         ((lpszShortPath < lpszLongPath) && (&lpszShortPath[cchBuffer] >= lpszLongPath))))
    {
        Buffer = RtlAllocateHeap(RtlGetProcessHeap(), 0, cchBuffer * sizeof(WCHAR));
        if (!Buffer) goto ErrorQuickie;

        /* New destination */
        Dst = Buffer;
    }

    /* Prepare for the loop */
    Src = Original;
    ReturnLength = 0;
    while (TRUE)
    {
        /* Current delta in the loop */
        Length = First - Src;

        /* Update the return length by it */
        ReturnLength += Length;

        /* Is there a delta? If so, is there space and buffer for it? */
        if ((Length) && (cchBuffer > ReturnLength) && (lpszShortPath))
        {
            RtlMoveMemory(Dst, Src, Length * sizeof(WCHAR));
            Dst += Length;
        }

        /* "Terminate" this portion of the path's substring so we can do a find */
        LastChar = *Last;
        *Last = UNICODE_NULL;<--- *Last is assigned
        FindHandle = FindFirstFileW(Original, &FindFileData);
        *Last = LastChar;<--- *Last is overwritten

        /* This portion wasn't found, so fail */
        if (FindHandle == INVALID_HANDLE_VALUE)
        {
            ReturnLength = 0;
            break;
        }

        /* Close the find handle */
        FindClose(FindHandle);

        /* Now check the length of the short name */
        Length = wcslen(FindFileData.cAlternateFileName);
        if (Length)
        {
            /* This is our new first marker */
            First = FindFileData.cAlternateFileName;
        }
        else
        {
            /* Otherwise, the name is the delta between our current markers */
            Length = Last - First;
        }

        /* Update the return length with the short name length, if any */
        ReturnLength += Length;

        /* Once again check for appropriate space and buffer */
        if ((cchBuffer > ReturnLength) && (lpszShortPath))
        {
            /* And do the copy if there is */
            RtlMoveMemory(Dst, First, Length * sizeof(WCHAR));
            Dst += Length;
        }

        /* Now update the source pointer */
        Src = Last;
        if (*Src == UNICODE_NULL) break;

        /* Are there more names in there? */
        Found = FindLFNorSFN_U(Src, &First, &Last, TRUE);
        if (!Found) break;
    }

    /* The loop is done, is there anything left? */
    if (ReturnLength)
    {
        /* Get the length of the straggling path */
        Length = wcslen(Src);
        ReturnLength += Length;

        /* Once again check for appropriate space and buffer */
        if ((cchBuffer > ReturnLength) && (lpszShortPath))
        {
            /* And do the copy if there is -- accounting for NULL here */
            RtlMoveMemory(Dst, Src, Length * sizeof(WCHAR) + sizeof(UNICODE_NULL));

            /* What about our buffer? */
            if (Buffer)
            {
                /* Copy it into the caller's long path */
                RtlMoveMemory(lpszShortPath,
                              Buffer,
                              ReturnLength * sizeof(WCHAR)  + sizeof(UNICODE_NULL));
            }
        }
        else
        {
            /* Buffer is too small, let the caller know, making space for NULL */
            ReturnLength++;
        }
    }

    /* We're all done */
    goto Quickie;

ErrorQuickie:
    /* This is the goto for memory failures */
    SetLastError(ERROR_NOT_ENOUGH_MEMORY);

Quickie:
    /* General function end: free memory, restore error mode, return length */
    if (Original) RtlFreeHeap(RtlGetProcessHeap(), 0, Original);
    if (Buffer) RtlFreeHeap(RtlGetProcessHeap(), 0, Buffer);
    SetErrorMode(ErrorMode);
    return ReturnLength;
}

/*
 * @implemented
 *
 * NOTE: Windows returns a dos/short (8.3) path
 */
DWORD
WINAPI
GetTempPathA(IN DWORD nBufferLength,
             OUT LPSTR lpBuffer)
{
   WCHAR BufferW[MAX_PATH];
   DWORD ret;

   ret = GetTempPathW(MAX_PATH, BufferW);

   if (!ret) return 0;

   if (ret > MAX_PATH)
   {
      SetLastError(ERROR_FILENAME_EXCED_RANGE);
      return 0;
   }

   return FilenameW2A_FitOrFail(lpBuffer, nBufferLength, BufferW, ret+1);
}

/*
 * @implemented
 *
 * ripped from wine
 */
DWORD
WINAPI
GetTempPathW(IN DWORD count,
             OUT LPWSTR path)
{
    static const WCHAR tmp[]  = { 'T', 'M', 'P', 0 };
    static const WCHAR temp[] = { 'T', 'E', 'M', 'P', 0 };
    static const WCHAR userprofile[] = { 'U','S','E','R','P','R','O','F','I','L','E',0 };
    WCHAR tmp_path[MAX_PATH];
    WCHAR full_tmp_path[MAX_PATH];
    UINT ret;

    DPRINT("%u,%p\n", count, path);

    if (!(ret = GetEnvironmentVariableW( tmp, tmp_path, MAX_PATH )) &&
        !(ret = GetEnvironmentVariableW( temp, tmp_path, MAX_PATH )) &&
        !(ret = GetEnvironmentVariableW( userprofile, tmp_path, MAX_PATH )) &&
        !(ret = GetWindowsDirectoryW( tmp_path, MAX_PATH )))
    {
        return 0;
    }

    if (ret > MAX_PATH)
    {
        SetLastError(ERROR_FILENAME_EXCED_RANGE);
        return 0;
    }

    ret = GetFullPathNameW(tmp_path, MAX_PATH, full_tmp_path, NULL);
    if (!ret) return 0;

    if (ret > MAX_PATH - 2)
    {
        SetLastError(ERROR_FILENAME_EXCED_RANGE);
        return 0;
    }

    if (full_tmp_path[ret-1] != '\\')
    {
        full_tmp_path[ret++] = '\\';
        full_tmp_path[ret]   = '\0';
    }

    ret++; /* add space for terminating 0 */

    if (count >= ret)
    {
        lstrcpynW(path, full_tmp_path, count);
        /* the remaining buffer must be zeroed up to 32766 bytes in XP or 32767
         * bytes after it, we will assume the > XP behavior for now */
        memset(path + ret, 0, (min(count, 32767) - ret) * sizeof(WCHAR));
        ret--; /* return length without 0 */
    }
    else if (count)
    {
        /* the buffer must be cleared if contents will not fit */
        memset(path, 0, count * sizeof(WCHAR));
    }

    DPRINT("GetTempPathW returning %u, %S\n", ret, path);
    return ret;
}

/*
 * @implemented
 */
DWORD
WINAPI
GetCurrentDirectoryA(IN DWORD nBufferLength,
                     OUT LPSTR lpBuffer)
{
    ANSI_STRING AnsiString;
    NTSTATUS Status;
    PUNICODE_STRING StaticString;
    ULONG MaxLength;

    StaticString = &NtCurrentTeb()->StaticUnicodeString;

    MaxLength = nBufferLength;
    if (nBufferLength >= UNICODE_STRING_MAX_BYTES)
    {
        MaxLength = UNICODE_STRING_MAX_BYTES - 1;
    }

    StaticString->Length = (USHORT)RtlGetCurrentDirectory_U(StaticString->MaximumLength,
                                                            StaticString->Buffer);
    Status = RtlUnicodeToMultiByteSize(&nBufferLength,
                                       StaticString->Buffer,
                                       StaticString->Length);
    if (!NT_SUCCESS(Status))
    {
        BaseSetLastNTError(Status);
        return 0;
    }

    if (MaxLength <= nBufferLength)
    {
        return nBufferLength + 1;
    }

    AnsiString.Buffer = lpBuffer;
    AnsiString.MaximumLength = (USHORT)MaxLength;
    Status = BasepUnicodeStringTo8BitString(&AnsiString, StaticString, FALSE);
    if (!NT_SUCCESS(Status))
    {
        BaseSetLastNTError(Status);
        return 0;
    }

    return AnsiString.Length;
}

/*
 * @implemented
 */
DWORD
WINAPI
GetCurrentDirectoryW(IN DWORD nBufferLength,
                     OUT LPWSTR lpBuffer)
{
    return RtlGetCurrentDirectory_U(nBufferLength * sizeof(WCHAR), lpBuffer) / sizeof(WCHAR);
}

/*
 * @implemented
 */
BOOL
WINAPI
SetCurrentDirectoryA(IN LPCSTR lpPathName)
{
    PUNICODE_STRING DirName;
    NTSTATUS Status;

    if (!lpPathName)
    {
        BaseSetLastNTError(STATUS_INVALID_PARAMETER);
        return FALSE;
    }

    DirName = Basep8BitStringToStaticUnicodeString(lpPathName);
    if (!DirName) return FALSE;

    if (CheckForSameCurdir(DirName)) return TRUE;

    Status = RtlSetCurrentDirectory_U(DirName);
    if (NT_SUCCESS(Status)) return TRUE;

    if ((*DirName->Buffer != L'"') || (DirName->Length <= 2))
    {
        BaseSetLastNTError(Status);
        return 0;
    }

    DirName = Basep8BitStringToStaticUnicodeString(lpPathName + 1);
    if (!DirName) return FALSE;

    Status = RtlSetCurrentDirectory_U(DirName);
    if (!NT_SUCCESS(Status))
    {
        BaseSetLastNTError(Status);
        return FALSE;
    }

    return TRUE;
}

/*
 * @implemented
 */
BOOL
WINAPI
SetCurrentDirectoryW(IN LPCWSTR lpPathName)
{
    NTSTATUS Status;
    UNICODE_STRING UnicodeString;

    if (!lpPathName)
    {
        BaseSetLastNTError(STATUS_INVALID_PARAMETER);
        return FALSE;
    }

    Status = RtlInitUnicodeStringEx(&UnicodeString, lpPathName);
    if (NT_SUCCESS(Status))
    {
        if (!CheckForSameCurdir(&UnicodeString))
        {
            Status = RtlSetCurrentDirectory_U(&UnicodeString);
        }
    }

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

    return TRUE;
}

/*
 * @implemented
 */
UINT
WINAPI
GetSystemDirectoryA(OUT LPSTR lpBuffer,
                    IN UINT uSize)
{
    ANSI_STRING AnsiString;
    NTSTATUS Status;
    ULONG AnsiLength;

    /* Get the correct size of the Unicode Base directory */
    Status = RtlUnicodeToMultiByteSize(&AnsiLength,
                                       BaseWindowsSystemDirectory.Buffer,
                                       BaseWindowsSystemDirectory.MaximumLength);
    if (!NT_SUCCESS(Status)) return 0;

    if (uSize < AnsiLength) return AnsiLength;

    RtlInitEmptyAnsiString(&AnsiString, lpBuffer, uSize);

    Status = BasepUnicodeStringTo8BitString(&AnsiString,
                                            &BaseWindowsSystemDirectory,
                                            FALSE);
    if (!NT_SUCCESS(Status)) return 0;

    return AnsiString.Length;
}

/*
 * @implemented
 */
UINT
WINAPI
GetSystemDirectoryW(OUT LPWSTR lpBuffer,
                    IN UINT uSize)
{
    ULONG ReturnLength;

    ReturnLength = BaseWindowsSystemDirectory.MaximumLength;
    if ((uSize * sizeof(WCHAR)) >= ReturnLength)
    {
        RtlCopyMemory(lpBuffer,
                      BaseWindowsSystemDirectory.Buffer,
                      BaseWindowsSystemDirectory.Length);
        lpBuffer[BaseWindowsSystemDirectory.Length / sizeof(WCHAR)] = ANSI_NULL;

        ReturnLength = BaseWindowsSystemDirectory.Length;
    }

    return ReturnLength / sizeof(WCHAR);
}

/*
 * @implemented
 */
UINT
WINAPI
GetWindowsDirectoryA(OUT LPSTR lpBuffer,
                     IN UINT uSize)
{
    /* Is this a TS installation? */
    if (gpTermsrvGetWindowsDirectoryA) UNIMPLEMENTED;

    /* Otherwise, call the System API */
    return GetSystemWindowsDirectoryA(lpBuffer, uSize);
}

/*
 * @implemented
 */
UINT
WINAPI
GetWindowsDirectoryW(OUT LPWSTR lpBuffer,
                     IN UINT uSize)
{
    /* Is this a TS installation? */
    if (gpTermsrvGetWindowsDirectoryW) UNIMPLEMENTED;

    /* Otherwise, call the System API */
    return GetSystemWindowsDirectoryW(lpBuffer, uSize);
}

/*
 * @implemented
 */
UINT
WINAPI
GetSystemWindowsDirectoryA(OUT LPSTR lpBuffer,
                           IN UINT uSize)
{
    ANSI_STRING AnsiString;
    NTSTATUS Status;
    ULONG AnsiLength;

    /* Get the correct size of the Unicode Base directory */
    Status = RtlUnicodeToMultiByteSize(&AnsiLength,
                                       BaseWindowsDirectory.Buffer,
                                       BaseWindowsDirectory.MaximumLength);
    if (!NT_SUCCESS(Status)) return 0;

    if (uSize < AnsiLength) return AnsiLength;

    RtlInitEmptyAnsiString(&AnsiString, lpBuffer, uSize);

    Status = BasepUnicodeStringTo8BitString(&AnsiString,
                                            &BaseWindowsDirectory,
                                            FALSE);
    if (!NT_SUCCESS(Status)) return 0;

    return AnsiString.Length;
}

/*
 * @implemented
 */
UINT
WINAPI
GetSystemWindowsDirectoryW(OUT LPWSTR lpBuffer,
                           IN UINT uSize)
{
    ULONG ReturnLength;

    ReturnLength = BaseWindowsDirectory.MaximumLength;
    if ((uSize * sizeof(WCHAR)) >= ReturnLength)
    {
        RtlCopyMemory(lpBuffer,
                      BaseWindowsDirectory.Buffer,
                      BaseWindowsDirectory.Length);
        lpBuffer[BaseWindowsDirectory.Length / sizeof(WCHAR)] = ANSI_NULL;

        ReturnLength = BaseWindowsDirectory.Length;
    }

    return ReturnLength / sizeof(WCHAR);
}

/*
 * @unimplemented
 */
UINT
WINAPI
GetSystemWow64DirectoryW(OUT LPWSTR lpBuffer,
                         IN UINT uSize)
{
#ifdef _WIN64
    UNIMPLEMENTED;
    return 0;
#else
    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return 0;
#endif
}

/*
 * @unimplemented
 */
UINT
WINAPI
GetSystemWow64DirectoryA(OUT LPSTR lpBuffer,
                         IN UINT uSize)
{
#ifdef _WIN64
    UNIMPLEMENTED;
    return 0;
#else
    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return 0;
#endif
}

/* EOF */