Source

xemacs-beta / src / nt.c

Full commit
   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
/* Utility and Unix shadow routines under MS Windows (WIN32_NATIVE defined).
   Copyright (C) 1994, 1995 Free Software Foundation, Inc.
   Copyright (C) 2000, 2001, 2002, 2004, 2005 Ben Wing.

This file is part of XEmacs.

XEmacs is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2, or (at your option) any
later version.

XEmacs is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
for more details.

You should have received a copy of the GNU General Public License
along with XEmacs; see the file COPYING.  If not, write to the Free
Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.

*/

/* Authorship:

   Geoff Voelker (voelker@cs.washington.edu) 7-29-94
   Adapted for XEmacs by David Hobley <david@spook-le0.cia.com.au>
   Sync'ed with Emacs 19.34.6 by Marc Paquette <marcpa@cam.org>
   (Note: Sync messages from Marc Paquette may indicate
   incomplete synching, so beware.)
   Synched (completely!) with Emacs 20.6 by Ben Wing, 6-23-00.
   Largely rewritten by Ben Wing for XEmacs Mule support.
   Synched (completely!) with Emacs 21.0.103 by Ben Wing, 6-13-01.
*/

/* This file Mule-ized by Ben Wing, 6-23-00. */

#include <config.h>
#include "lisp.h"

#include "buffer.h"
#include "process.h"

#include "sysdir.h"
#include "sysfile.h"
#include "sysproc.h"
#include "syspwd.h"
#include "syssignal.h"
#include "systime.h"

#include "syswindows.h"

/* Control whether stat() attempts to determine file type and link count
   exactly, at the expense of slower operation.  Since true hard links
   are supported on NTFS volumes, this is only relevant on NT.  */
Lisp_Object Vmswindows_get_true_file_attributes;

/*  Vmswindows_generate_fake_inodes; deleted */

Fixnum mswindows_fake_unix_uid;

/* Emulate getpwuid, getpwnam and others.  */

static struct passwd the_passwd =
{
  "",
  "",
  0,
  0,
  0,
  "",
  "",
  "",
};

uid_t
getuid (void) 
{
  return mswindows_fake_unix_uid;
}

uid_t 
geteuid (void) 
{ 
  /* Emacs 20.6 says: [[I could imagine arguing for checking to see
     whether the user is in the Administrators group and returning a
     UID of 0 for that case, but I don't know how wise that would be
     in the long run.]]  */
  return mswindows_fake_unix_uid;
}

gid_t
getgid (void) 
{ 
  return the_passwd.pw_gid;
}

gid_t
getegid (void) 
{ 
  return getgid ();
}

struct passwd *
getpwuid (uid_t uid)
{
  if (uid == mswindows_fake_unix_uid)
    {
      the_passwd.pw_gid = the_passwd.pw_uid = uid;
      return &the_passwd;
    }
  else
    return NULL;
}

struct passwd *
getpwnam (const Ibyte *name)
{
  struct passwd *pw;
  
  pw = getpwuid (getuid ());
  if (!pw)
    return pw;

  if (qxestrcasecmp_i18n (name, (Ibyte *) pw->pw_name))
    return NULL;

  return pw;
}

static void
init_user_info (void)
{
  /* This code is pretty much of ad hoc nature. There is no unix-like
     UIDs under Windows NT. There is no concept of root user, because
     all security is ACL-based. Instead, let's use a simple variable,
     nt-fake-unix-uid, which would allow the user to have a uid of
     choice. --kkm, 02/03/2000 */
#if 0
  /* Find the user's real name by opening the process token and
     looking up the name associated with the user-sid in that token.

     Use the relative portion of the identifier authority value from
     the user-sid as the user id value (same for group id using the
     primary group sid from the process token). */

  TOKEN_USER sidinfo;
  Extbyte name[256], domain[256];
  Charcount length = sizeof (name) / XETCHAR_SIZE;
  Charcount dlength = sizeof (domain) / XETCHAR_SIZE;
  DWORD trash;
  HANDLE token = NULL;
  SID_NAME_USE user_type;

  if (OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &token)
      && GetTokenInformation (token, TokenUser, &sidinfo, sizeof (sidinfo),
			      &trash)
      && qxeLookupAccountSid (NULL, sidinfo.User.Sid, name, &length,
			      domain, &dlength, &user_type))
    {
      the_passwd.pw_name = (CIbyte *) TSTR_TO_ITEXT_MALLOC (name);
      /* Determine a reasonable uid value. */
      if (qxestrcasecmp ((Ibyte *) the_passwd.pw_name, "administrator") == 0)
	{
	  the_passwd.pw_uid = 0;
	  the_passwd.pw_gid = 0;
	}
      else
	{
	  SID_IDENTIFIER_AUTHORITY * pSIA;
	  TOKEN_PRIMARY_GROUP group;

	  pSIA = GetSidIdentifierAuthority (sidinfo.User.Sid);
	  /* I believe the relative portion is the last 4 bytes (of 6)
	     with msb first. */
	  the_passwd.pw_uid = ((pSIA->Value[2] << 24) +
			       (pSIA->Value[3] << 16) +
			       (pSIA->Value[4] << 8)  +
			       (pSIA->Value[5] << 0));
	  /* restrict to conventional uid range for normal users */
	  the_passwd.pw_uid = the_passwd.pw_uid % 60001;

	  /* Get group id */
	  if (GetTokenInformation (token, TokenPrimaryGroup,
				   &group, sizeof (group), &trash))
	    {
	      SID_IDENTIFIER_AUTHORITY * pSIA;

	      pSIA = GetSidIdentifierAuthority (group.PrimaryGroup);
	      the_passwd.pw_gid = ((pSIA->Value[2] << 24) +
				   (pSIA->Value[3] << 16) +
				   (pSIA->Value[4] << 8)  +
				   (pSIA->Value[5] << 0));
	      /* I don't know if this is necessary, but for safety... */
	      the_passwd.pw_gid = the_passwd.pw_gid % 60001;
	    }
	  else
	    the_passwd.pw_gid = the_passwd.pw_uid;
	}
    }
  /* If security calls are not supported (presumably because we
       are running under Windows 95), fallback to this. */
  else if (qxeGetUserName (name, &length))
    {
      the_passwd.pw_name = (CIbyte *) TSTR_TO_ITEXT_MALLOC (name);
      if (qxestrcasecmp_ascii ((Ibyte *) the_passwd.pw_name,
			       "administrator") == 0)
	the_passwd.pw_uid = 0;
      else
	the_passwd.pw_uid = 123;
      the_passwd.pw_gid = the_passwd.pw_uid;
    }
  else
    {
      the_passwd.pw_name = "unknown";
      the_passwd.pw_uid = 123;
      the_passwd.pw_gid = 123;
    }

  if (token)
    CloseHandle (token);
#else
  /* Obtain only logon id here, uid part is moved to getuid */
  DWORD length = UNLEN + 1;
  Extbyte name[MAX_XETCHAR_SIZE * (UNLEN + 1)];
  if (qxeGetUserName (name, &length))
    the_passwd.pw_name = (CIbyte *) TSTR_TO_ITEXT_MALLOC (name);
  else
    the_passwd.pw_name = "unknown";
#endif

#if 0
  /* Ensure HOME and SHELL are defined. */
  /*
   * With XEmacs, setting $HOME is deprecated.
   */
  if (egetenv ("HOME") == NULL)
    eputenv ("HOME=c:/");
#endif

  /* Set dir from environment variables. */
  the_passwd.pw_dir = (CIbyte *) qxestrdup (get_home_directory ());
  /* We used to set pw_shell here, but the order is wrong (SHELL gets
     initted in process.c, called later in the init process) and pw_shell
     is not used anywhere. */
}

/* Parse the root part of file name, if present.  Return length and
   optionally store pointer to Ibyte after root.  */
static Bytecount
parse_root (Ibyte *name, Ibyte **pPath)
{
  Ibyte *start = name;

  if (name == NULL)
    return 0;

  /* find the root name of the volume if given */
  if (isalpha (name[0]) && name[1] == ':')
    {
      /* skip past drive specifier */
      name += 2;
      if (IS_DIRECTORY_SEP (name[0]))
	name++;
    }
  else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
    {
      int slashes = 2;
      name += 2;
      do
        {
	  if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
	    break;
	  name++;
	}
      while (*name);
      if (IS_DIRECTORY_SEP (name[0]))
	name++;
    }

  if (pPath)
    *pPath = name;

  return name - start;
}

/* Get long base name for name; name is assumed to be absolute.  */
static Ibyte *
get_long_basename (Ibyte *name)
{
  WIN32_FIND_DATAW find_data;
  HANDLE dir_handle;
  Extbyte *nameext;

  /* must be valid filename, no wild cards or other invalid characters */
  if (qxestrpbrk (name, "*?|<>\""))
    return 0;

  PATHNAME_CONVERT_OUT (name, nameext);
  dir_handle = qxeFindFirstFile (nameext, &find_data);
  if (dir_handle != INVALID_HANDLE_VALUE)
    {
      Ibyte *fileint;

      fileint = TSTR_TO_ITEXT_MALLOC (find_data.cFileName);
      FindClose (dir_handle);
      return fileint;
    }
  return 0;
}

/* Get long name for file, if possible (assumed to be absolute).  */
Ibyte *
mswindows_get_long_filename (Ibyte *name)
{
  Ibyte *full = mswindows_canonicalize_filename (name);
  Ibyte *p;
  Ibyte *q;
  DECLARE_EISTRING (o);
  Bytecount len;

  /* Copy root part verbatim.  */
  len = parse_root (full, &p);
  eicpy_raw (o, full, len);

  while (p != NULL && *p)
    {
      Ibyte *component;

      q = p;
      p = qxestrchr (q, '\\');
      if (p) *p = '\0';
      component = get_long_basename (full);
      if (component)
	{
	  eicat_rawz (o, component);
	  if (p != NULL)
	    {
	      *p++ = '\\';
	      eicat_ch (o, '\\');
	    }
	  xfree (component);
	}
      else
	{
	  xfree (full);
	  return 0;
	}
    }

  xfree (full);
  return eicpyout_malloc (o, 0);
}

static int
is_unc_volume (const Ibyte *filename)
{
  const Ibyte *ptr = filename;

  if (!IS_DIRECTORY_SEP (ptr[0]) || !IS_DIRECTORY_SEP (ptr[1]) || !ptr[2])
    return 0;

  if (qxestrpbrk (ptr + 2, "*?|<>\"\\/"))
    return 0;

  return 1;
}

/* NOTE: Value returned is still in external format.  Callers need to
   convert. */
#define REG_ROOT "SOFTWARE\\XEmacs\\XEmacs"

static LPBYTE 
nt_get_resource (Ibyte *key, LPDWORD lpdwtype)
{
  LPBYTE lpvalue;
  HKEY hrootkey = NULL;
  DWORD cbData;
  Extbyte *keyext;

  keyext = ITEXT_TO_TSTR (key);
  
  /* Check both the current user and the local machine to see if 
     we have any resources.  */
  
  if (qxeRegOpenKeyEx (HKEY_CURRENT_USER, XETEXT (REG_ROOT), 0, KEY_READ,
		       &hrootkey) == ERROR_SUCCESS)
    {
      lpvalue = NULL;

      if (qxeRegQueryValueEx (hrootkey, keyext, NULL, NULL, NULL,
			      &cbData) == ERROR_SUCCESS 
	  && (lpvalue = xnew_array (BYTE, cbData)) != NULL 
	  && qxeRegQueryValueEx (hrootkey, keyext, NULL, lpdwtype, lpvalue,
			      &cbData) == ERROR_SUCCESS)
	return (lpvalue);

      if (lpvalue)
	xfree (lpvalue);
	
      RegCloseKey (hrootkey);
    } 
  
  if (qxeRegOpenKeyEx (HKEY_LOCAL_MACHINE, XETEXT (REG_ROOT), 0, KEY_READ,
		       &hrootkey) == ERROR_SUCCESS)
    {
      lpvalue = NULL;
	
      if (qxeRegQueryValueEx (hrootkey, keyext, NULL, NULL, NULL,
			      &cbData) == ERROR_SUCCESS &&
	  (lpvalue = xnew_array (BYTE, cbData)) != NULL &&
	  qxeRegQueryValueEx (hrootkey, keyext, NULL, lpdwtype, lpvalue,
			      &cbData) == ERROR_SUCCESS)
	return (lpvalue);
	
      if (lpvalue)
	xfree (lpvalue);
	
      RegCloseKey (hrootkey);
    } 
  
  return (NULL);
}

void
init_mswindows_environment (void)
{
  /* Check for environment variables and use registry if they don't exist */
  /* Emacs 20.6 sets default values for these; not necessary here because
     we already supply them. (except SHELL, which is set in init_user_info().)
     Emacs 20.6 messes with TMPDIR; not necessary here. */
  {
    int i;
    LPBYTE lpval;
    DWORD dwType;

    static Ascbyte *env_vars[] = 
    {
      "HOME",
      "EMACSLOADPATH",
      "EMACSDEBUGPATHS",
      "SHELL",
      "CMDPROXY",
      "EMACSDATA",
      "EMACSPATH",
      "EMACSPACKAGEPATH",
      "EMACSEARLYPACKAGES",
      "EMACSLATEPACKAGES",
      "EMACSLASTPACKAGES",
      "EMACSLOCKMETHOD",
      "INFOPATH"
    };
#if defined (HEAP_IN_DATA) && !defined (PDUMP)
    cache_system_info ();
#endif

#if 0 /* FSF 21.1 */
    /* !!#### i think i already do the equivalent elsewhere.
       delete when i'm sure i do.
       (but maybe i should be playing with LANG when the user changes
       the locale, so that subprocesses get it right.) */
       /* Get default locale info and use it for LANG.  */
      if (GetLocaleInfo (LOCALE_USER_DEFAULT,
			 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
			 locale_name, sizeof (locale_name)))
	{
	  for (i = 0; i < (sizeof (env_vars) / sizeof (env_vars[0])); i++)
	    {
	      if (strcmp (env_vars[i].name, "LANG") == 0)
		{
		  env_vars[i].def_value = locale_name;
		  break;
		}
	    }
	}
#endif /* 0 */

    for (i = 0; i < countof (env_vars); i++) 
      {
	if (!egetenv (env_vars[i]) &&
	    (lpval = nt_get_resource ((Ibyte *) env_vars[i], &dwType)) != NULL)
	  {
	    if (dwType == REG_EXPAND_SZ)
	      {
		Extbyte *buf = NULL;
		Ibyte *envval;
		Charcount cch;

		cch = qxeExpandEnvironmentStrings ((Extbyte *) lpval, buf, 0);
		buf = alloca_extbytes (cch * XETCHAR_SIZE);
		qxeExpandEnvironmentStrings ((Extbyte *) lpval, buf, cch);
		envval = TSTR_TO_ITEXT (buf);
		eputenv (env_vars[i], (CIbyte *) envval);
	      }
	    else if (dwType == REG_SZ)
	      {
		Ibyte *envval;

		envval = TSTR_TO_ITEXT (lpval);
		eputenv (env_vars[i], (CIbyte *) envval);
	      }

	    xfree (lpval);
	  }
      }
  }

  /* Another special case: on NT, the PATH variable is actually named
     "Path" although cmd.exe (perhaps NT itself) arranges for
     environment variable lookup and setting to be case insensitive.
     However, Emacs assumes a fully case sensitive environment, so we
     need to change "Path" to "PATH" to match the expectations of
     various elisp packages.

     The same applies to COMSPEC.  */
  {
    EXTERNAL_LIST_LOOP_2 (str, Vprocess_environment)
      {
	if (STRINGP (str))
	  {
	    Ibyte *dat = XSTRING_DATA (str);
	    if (qxestrncasecmp_ascii (dat, "PATH=", 5) == 0)
	      memcpy (dat, "PATH=", 5);
	    else if (qxestrncasecmp_ascii (dat, "COMSPEC=", 8) == 0)
	      memcpy (dat, "COMSPEC=", 8);
	  }
      }
  }

  init_user_info ();
}

/* Emacs 20.6 contains a routine get_emacs_configuration() here to set
   EMACS_CONFIGURATION. */ 
#ifndef HAVE_X_WINDOWS
/* X11R6 on NT provides the single parameter version of this command. */

#include <sys/timeb.h>

/* Emulate gettimeofday (Ulrich Leodolter, 1/11/95).  */
void 
gettimeofday (struct timeval *tv, struct timezone *tz)
{
  struct _timeb tb;
  _ftime (&tb);

  tv->tv_sec = tb.time;
  tv->tv_usec = tb.millitm * 1000L;
  if (tz) 
    {
      tz->tz_minuteswest = tb.timezone;	/* minutes west of Greenwich  */
      tz->tz_dsttime = tb.dstflag;	/* type of dst correction  */
    }
}

#endif /* HAVE_X_WINDOWS */


/* ------------------------------------------------------------------------- */
/*               IO support and wrapper functions for Win32 API.             */
/* ------------------------------------------------------------------------- */

typedef struct volume_info_data
{
  struct volume_info_data *next;

  /* time when info was obtained */
  DWORD timestamp;

  /* actual volume info */
  Ibyte *root_dir;
  DWORD serialnum;
  DWORD maxcomp;
  DWORD flags;
  Ibyte *name;
  Ibyte *type;
} volume_info_data;

/* Global referenced by various functions.  */
static volume_info_data volume_info;

/* Vector to indicate which drives are local and fixed (for which cached
   data never expires).  */
static BOOL fixed_drives[26];

/* Consider cached volume information to be stale if older than 10s,
   at least for non-local drives.  Info for fixed drives is never stale.  */
#define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
#define VOLINFO_STILL_VALID( root_dir, info )		\
  ( ( isalpha (root_dir[0]) &&				\
      fixed_drives[ DRIVE_INDEX (root_dir[0]) ] )	\
    || GetTickCount () - info->timestamp < 10000 )

/* Cache support functions.  */

/* Simple linked list with linear search is sufficient.  */
static volume_info_data *volume_cache = NULL;

static volume_info_data *
lookup_volume_info (Ibyte *root_dir)
{
  volume_info_data *info;

  for (info = volume_cache; info; info = info->next)
    if (qxestrcasecmp_i18n (info->root_dir, root_dir) == 0)
      break;
  return info;
}

static void
add_volume_info (Ibyte *root_dir, volume_info_data *info)
{
  info->root_dir = qxestrdup (root_dir);
  info->next = volume_cache;
  volume_cache = info;
}


/* Wrapper for GetVolumeInformation, which uses caching to avoid
   performance penalty (~2ms on 486 for local drives, 7.5ms for local
   cdrom drive, ~5-10ms or more for remote drives on LAN).  */
static volume_info_data *
get_cached_volume_information (Ibyte *root_dir)
{
  volume_info_data *info;
  Ibyte *default_root;

  /* NULL for root_dir means use root from current directory.  */
  if (root_dir == NULL)
    {
      Charcount nchars = qxeGetCurrentDirectory (0, NULL);
      Extbyte *rootext;

      if (!nchars)
	return NULL;
      rootext = alloca_extbytes (nchars * XETCHAR_SIZE);
      if (!qxeGetCurrentDirectory (nchars, rootext))
	return NULL;
      default_root = TSTR_TO_ITEXT (rootext);
      parse_root (default_root, &root_dir);
      *root_dir = 0;
      root_dir = default_root;
    }

  /* Local fixed drives can be cached permanently.  Removable drives
     cannot be cached permanently, since the volume name and serial
     number (if nothing else) can change.  Remote drives should be
     treated as if they are removable, since there is no sure way to
     tell whether they are or not.  Also, the UNC association of drive
     letters mapped to remote volumes can be changed at any time (even
     by other processes) without notice.
   
     As a compromise, so we can benefit from caching info for remote
     volumes, we use a simple expiry mechanism to invalidate cache
     entries that are more than ten seconds old.  */

#if 0
  /* No point doing this, because WNetGetConnection is even slower than
     GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
     GetDriveType is about the only call of this type which does not
     involve network access, and so is extremely quick).  */

  /* Map drive letter to UNC if remote. */
  if (isalpha (root_dir[0]) && !fixed [DRIVE_INDEX (root_dir[0])])
    {
      Extbyte remote_name[256 * XETCHAR_SIZE];
      Ibyte drive[3] = { root_dir[0], ':' };
      Extbyte *driveext;

      PATHNAME_CONVERT_OUT (drive, driveext);
      if (qxeWNetGetConnection (driveext, remote_name,
				sizeof (remote_name) / XETCHAR_SIZE)
	  == NO_ERROR)
	/* do something */ ;
    }
#endif

  info = lookup_volume_info (root_dir);

  if (info == NULL || ! VOLINFO_STILL_VALID (root_dir, info))
    {
      Extbyte name[256 * MAX_XETCHAR_SIZE];
      DWORD serialnum;
      DWORD maxcomp;
      DWORD flags;
      Extbyte type[256 * MAX_XETCHAR_SIZE];
      Extbyte *rootdirext;

      PATHNAME_CONVERT_OUT (root_dir, rootdirext);

      /* Info is not cached, or is stale. */
      if (!qxeGetVolumeInformation (rootdirext,
				    name, sizeof (name) / XETCHAR_SIZE,
				    &serialnum,
				    &maxcomp,
				    &flags,
				    type, sizeof (type) / XETCHAR_SIZE))
	return NULL;

      /* Cache the volume information for future use, overwriting existing
	 entry if present.  */
      if (info == NULL)
	{
	  info = xnew (volume_info_data);
	  add_volume_info (root_dir, info);
	}
      else
	{
	  xfree (info->name);
	  xfree (info->type);
	}

      info->name = TSTR_TO_ITEXT_MALLOC (name);
      info->serialnum = serialnum;
      info->maxcomp = maxcomp;
      info->flags = flags;
      info->type = TSTR_TO_ITEXT_MALLOC (type);
      info->timestamp = GetTickCount ();
    }

  return info;
}

/* Get information on the volume where name is held; set path pointer to
   start of pathname in name (past UNC header\volume header if present).  */
static int
get_volume_info (const Ibyte *name, const Ibyte **pPath)
{
  /* We probably only need a couple of bytes, but let's be generous in
     case this function gets changed */
  Ibyte *temp = alloca_ibytes (qxestrlen (name) + 10);
  Ibyte *rootname = NULL;  /* default to current volume */
  volume_info_data *info;

  if (name == NULL)
    return FALSE;

  /* find the root name of the volume if given */
  if (isalpha (name[0]) && name[1] == ':')
    {
      rootname = temp;
      temp[0] = *name++;
      temp[1] = *name++;
      temp[2] = '\\';
      temp[3] = 0;
    }
  else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
    {
      Ibyte *str = temp;
      int slashes = 4;
      rootname = temp;
      do
        {
	  if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
	    break;
	  *str++ = *name++;
	}
      while (*name);

      *str++ = '\\';
      *str = 0;
    }

  if (pPath)
    *pPath = name;
    
  info = get_cached_volume_information (rootname);
  if (info != NULL)
    {
      /* Set global referenced by other functions.  */
      volume_info = *info;
      return TRUE;
    }
  return FALSE;
}

/* XEmacs: Everything referring to map_win32_filename() aka map_w32_filename()
   removed; it was only for NT 3.1, which we hereby do not support. (NT 3.5
   predates Windows 95!) */

int
mswindows_is_executable (const Ibyte *name)
{
  Ibyte *p = qxestrrchr (name, '.');
  return (p != NULL && (qxestrcasecmp_ascii (p, ".exe") == 0 ||
			qxestrcasecmp_ascii (p, ".com") == 0 ||
			qxestrcasecmp_ascii (p, ".bat") == 0 ||
			qxestrcasecmp_ascii (p, ".cmd") == 0));
}

/* Emulate the Unix directory procedures opendir, closedir, 
   and readdir.  We can't use the procedures supplied in sysdep.c,
   so we provide them here.  */

struct direct dir_static;       /* simulated directory contents */
static HANDLE dir_find_handle = INVALID_HANDLE_VALUE;
/*  dir_is_fat deleted */
static Ibyte *dir_pathname;
static WIN32_FIND_DATAW dir_find_data;

/* Support shares on a network resource as subdirectories of a read-only
   root directory. */
static HANDLE wnet_enum_handle = INVALID_HANDLE_VALUE;
static HANDLE open_unc_volume (const Ibyte *);
static Ibyte *read_unc_volume (HANDLE);
static int close_unc_volume (HANDLE);

DIR *
mswindows_opendir (const Ibyte *filename)
{
  DIR *dirp;

  /* Opening is done by FindFirstFile.  However, a read is inherent to
     this operation, so we defer the open until read time.  */

  if (dir_find_handle != INVALID_HANDLE_VALUE)
    return NULL;
  if (wnet_enum_handle != INVALID_HANDLE_VALUE)
    return NULL;

  if (is_unc_volume (filename))
    {
      wnet_enum_handle = open_unc_volume (filename);
      if (wnet_enum_handle == INVALID_HANDLE_VALUE)
	return NULL;
    }

  if (!(dirp = xnew_and_zero (DIR)))
    return NULL;

  if (dir_pathname)
    xfree (dir_pathname);
  dir_pathname = qxestrdup (filename);

  return dirp;
}

int
mswindows_closedir (DIR *dirp)
{
  int retval = -1;

  /* If we have a find-handle open, close it.  */
  if (dir_find_handle != INVALID_HANDLE_VALUE)
    {
      retval = FindClose (dir_find_handle) ? 0 : -1;
      dir_find_handle = INVALID_HANDLE_VALUE;
    }
  else if (wnet_enum_handle != INVALID_HANDLE_VALUE)
    {
      retval = close_unc_volume (wnet_enum_handle);
      wnet_enum_handle = INVALID_HANDLE_VALUE;
    }
  xfree (dirp);

  return retval;
}

struct direct *
mswindows_readdir (DIR *UNUSED (dirp))
{
  Ibyte *val;
  int need_to_free = 0;

  if (wnet_enum_handle != INVALID_HANDLE_VALUE)
    {
      if (!(val = read_unc_volume (wnet_enum_handle)))
	return NULL;
      need_to_free = 1;
    }
  /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
  else if (dir_find_handle == INVALID_HANDLE_VALUE)
    {
      DECLARE_EISTRING (filename);
      Ichar lastch;
      Extbyte *fileext;

      eicpy_rawz (filename, dir_pathname);
      lastch = eigetch_char (filename, eicharlen (filename) - 1);
      if (!IS_DIRECTORY_SEP (lastch))
	eicat_ch (filename, '\\');
      eicat_ch (filename, '*');
      PATHNAME_CONVERT_OUT (eidata (filename), fileext);

      dir_find_handle = qxeFindFirstFile (fileext, &dir_find_data);

      if (dir_find_handle == INVALID_HANDLE_VALUE)
	return NULL;
      val = TSTR_TO_ITEXT (dir_find_data.cFileName);
    }
  else
    {
      if (!qxeFindNextFile (dir_find_handle, &dir_find_data))
	return NULL;
      val = TSTR_TO_ITEXT (dir_find_data.cFileName);
    }
  
  /* XEmacs never uses this value, so don't bother making it match
     value returned by qxe_stat().  */
  dir_static.d_ino = 1;
  
  dir_static.d_reclen = sizeof (struct direct) - MAXNAMLEN + 3 +
    dir_static.d_namlen - dir_static.d_namlen % 4;

  {
    DECLARE_EISTRING (found);
    Bytecount namlen;

    if (mswindows_shortcuts_are_symlinks)
      {
	int len = qxestrlen (val);
	if (len > 4 && !qxestrcasecmp_ascii (val + len - 4, ".LNK"))
	  {
	    /* If we've found a valid link, then chop off the .LNK ending */
	    DECLARE_EISTRING (linkname);
	    Ichar lastch;
	    Ibyte *resolved;

	    /* First check if link is valid */
	    PATHNAME_RESOLVE_LINKS (dir_pathname, resolved);
	    eicpy_rawz (linkname, resolved);
	    lastch = eigetch_char (linkname, eicharlen (linkname) - 1);
	    if (!IS_DIRECTORY_SEP (lastch))
	      eicat_ch (linkname, '\\');
	    eicat_rawz (linkname, val);
	    resolved = mswindows_read_link (eidata (linkname));
	    if (resolved)
	      {
		xfree (resolved);
		len -= 4;
		val[len] = '\0';
	      }
	  }
      }

    eicpy_rawz (found, val);
    if (need_to_free)
      xfree (val);

    if (!NILP (Vmswindows_downcase_file_names))
      eilwr (found);

    namlen = min (eilen (found), sizeof (dir_static.d_name) - 1);
    qxestrncpy ((Ibyte *) dir_static.d_name, eidata (found), namlen);
    dir_static.d_name[namlen] = '\0';
    dir_static.d_namlen = (unsigned short) namlen;
  }

  return &dir_static;
}

static HANDLE
open_unc_volume (const Ibyte *path)
{
  NETRESOURCEW nr; 
  HANDLE henum;
  int result;
  Extbyte *extpath;

  nr.dwScope = RESOURCE_GLOBALNET; 
  nr.dwType = RESOURCETYPE_DISK; 
  nr.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER; 
  nr.dwUsage = RESOURCEUSAGE_CONTAINER; 
  nr.lpLocalName = NULL;
  PATHNAME_CONVERT_OUT (path, extpath);
  nr.lpRemoteName = (XELPTSTR) extpath;
  nr.lpComment = NULL; 
  nr.lpProvider = NULL;   

  result = qxeWNetOpenEnum (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,  
			    RESOURCEUSAGE_CONNECTABLE, &nr, &henum);

  if (result == NO_ERROR)
    return henum;
  else
    return INVALID_HANDLE_VALUE;
}

static Ibyte *
read_unc_volume (HANDLE UNUSED (henum))
{
  DWORD count;
  int result;
  Extbyte buf[16384];
  Ibyte *ptr;
  DWORD bufsize = sizeof (buf);

  count = 1;
  /* #### we should just be querying the size and then allocating the
     right amount, like for all similar API's.  but the docs say this ?!

     An application cannot set the lpBuffer parameter to NULL and
     retrieve the required buffer size from the lpBufferSize
     parameter. Instead, the application should allocate a buffer of a
     reasonable size --  16 kilobytes (K) is typical -- and use the value
     of lpBufferSize for error detection.
     */

  result = qxeWNetEnumResource (wnet_enum_handle, &count, buf, &bufsize);
  if (result != NO_ERROR)
    return NULL;

  /* WNetEnumResource returns \\resource\share...skip forward to "share". */
  ptr = TSTR_TO_ITEXT (((LPNETRESOURCEW) buf)->lpRemoteName);
  INC_IBYTEPTR (ptr);
  INC_IBYTEPTR (ptr);
  while (*ptr && !IS_DIRECTORY_SEP (itext_ichar (ptr)))
    INC_IBYTEPTR (ptr);
  INC_IBYTEPTR (ptr);

  return qxestrdup (ptr);
}

static int
close_unc_volume (HANDLE henum)
{
  if (henum != INVALID_HANDLE_VALUE)
    return WNetCloseEnum (henum) == NO_ERROR ? 0 : -1;
  else
    return -1;
}

static DWORD
unc_volume_file_attributes (const Ibyte *path)
{
  HANDLE henum;
  DWORD attrs;

  henum = open_unc_volume (path);
  if (henum == INVALID_HANDLE_VALUE)
    return -1;

  attrs = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_DIRECTORY;

  close_unc_volume (henum);

  return attrs;
}

int
mswindows_access (const Ibyte *path, int mode)
{
  DWORD attributes;

  /* MSVC implementation doesn't recognize D_OK.  */
  if (is_unc_volume (path))
    {
      attributes = unc_volume_file_attributes (path);
      if (attributes == -1)
	{
	  errno = EACCES;
	  return -1;
	}
    }
  else
    {
      Extbyte *pathext;

      PATHNAME_CONVERT_OUT (path, pathext);
      if ((attributes = qxeGetFileAttributes (pathext)) == -1)
	{
	  /* Should try mapping GetLastError to errno; for now just indicate
	     that path doesn't exist.  */
	  errno = EACCES;
	  return -1;
	}
    }
  if ((mode & X_OK) != 0 && !mswindows_is_executable (path))
    {
      errno = EACCES;
      return -1;
    }
  if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
    {
      errno = EACCES;
      return -1;
    }
  if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
    {
      errno = EACCES;
      return -1;
    }
  return 0;
}

/* This only works on NTFS volumes, but is useful to have.  */
/* #### NT 5.0 has a function CreateHardLink to do this directly,
   and it may do more things. */
int
mswindows_link (const Ibyte *old, const Ibyte *new_)
{
  HANDLE fileh;
  int result = -1;
  Extbyte *oldext;

  if (old == NULL || new_ == NULL)
    {
      errno = ENOENT;
      return -1;
    }

  PATHNAME_CONVERT_OUT (old, oldext);
  fileh = qxeCreateFile (oldext, 0, 0, NULL, OPEN_EXISTING,
			 FILE_FLAG_BACKUP_SEMANTICS, NULL);
  if (fileh != INVALID_HANDLE_VALUE)
    {
      int wlen;
      WCHAR *newuni;

      /* Confusingly, the "alternate" stream name field does not apply
         when restoring a hard link, and instead contains the actual
         stream data for the link (ie. the name of the link to create).
         The WIN32_STREAM_ID structure before the cStreamName field is
         the stream header, which is then immediately followed by the
         stream data.  */

      struct
	{
	  WIN32_STREAM_ID wid;
	  WCHAR wbuffer[_MAX_PATH];	/* extra space for link name */
	} data;

      TO_EXTERNAL_FORMAT (C_STRING, new_,
			  ALLOCA, (newuni, wlen), Qmswindows_unicode);
      if (wlen / sizeof (WCHAR) < _MAX_PATH)
	{
	  LPVOID context = NULL;
	  DWORD wbytes = 0;

	  wcscpy (data.wid.cStreamName, newuni);
	  data.wid.dwStreamId = BACKUP_LINK;
	  data.wid.dwStreamAttributes = 0;
	  /* Include the trailing null.  In bytes, not chars! */
	  data.wid.Size.LowPart = wlen + sizeof (WCHAR);
	  data.wid.Size.HighPart = 0;
	  data.wid.dwStreamNameSize = 0;

	  if (BackupWrite (fileh, (LPBYTE)&data,
			   offsetof (WIN32_STREAM_ID, cStreamName)
			   + data.wid.Size.LowPart,
			   &wbytes, FALSE, FALSE, &context)
	      && BackupWrite (fileh, NULL, 0, &wbytes, TRUE, FALSE, &context))
	    {
	      /* succeeded */
	      result = 0;
	    }
	  else
	    {
	      /* Should try mapping GetLastError to errno; for now just
		 indicate a general error (eg. links not supported).  */
	      errno = EINVAL;  /* perhaps EMLINK? */
	    }
	}

      CloseHandle (fileh);
    }
  else
    errno = ENOENT;

  return result;
}

/* sys_open() merged into sysdep.c sys_open() */

int
mswindows_rename (const Ibyte *oldname, const Ibyte *newname)
{
  int result;
  Ibyte *temp;

  /* MoveFile on Windows 95 doesn't correctly change the short file name
     alias in a number of circumstances (it is not easy to predict when
     just by looking at oldname and newname, unfortunately).  In these
     cases, renaming through a temporary name avoids the problem.

     A second problem on Windows 95 is that renaming through a temp name when
     newname is uppercase fails (the final long name ends up in
     lowercase, although the short alias might be uppercase) UNLESS the
     long temp name is not 8.3.

     So, on Windows 95 we always rename through a temp name, and we make sure
     the temp name has a long extension to ensure correct renaming.  */

  /* XEmacs: We sprintf() part of OLDNAME into part of OLDNAME + a number,
     so the following calculation should certainly be enough. */

  temp = qxestrcpy (alloca_ibytes (2 * qxestrlen (oldname) + 100), oldname);

  if (mswindows_windows9x_p)
    {
      Ibyte *o;
      Ibyte *p;
      int i = 0;

      if (o = qxestrrchr (oldname, '\\'))
	o++;
      else
	o = (Ibyte *) oldname;

      if (p = qxestrrchr (temp, '\\'))
	p++;
      else
	p = temp;

      do
	{
	  Extbyte *oldext, *tempext;
	  /* Force temp name to require a manufactured 8.3 alias - this
	     seems to make the second rename work properly.  */
	  qxesprintf (p, "_.%s.%u", o, i);
	  i++;
	  PATHNAME_CONVERT_OUT (oldname, oldext);
	  PATHNAME_CONVERT_OUT (temp, tempext);
	  result = rename (oldext, tempext);
	}
      /* This loop must surely terminate!  */
      while (result < 0 && errno == EEXIST);
      if (result < 0)
	return -1;
    }

  /* Emulate Unix behaviour - newname is deleted if it already exists
     (at least if it is a file; don't do this for directories).

     Since we mustn't do this if we are just changing the case of the
     file name (we would end up deleting the file we are trying to
     rename!), we let rename detect if the destination file already
     exists - that way we avoid the possible pitfalls of trying to
     determine ourselves whether two names really refer to the same
     file, which is not always possible in the general case.  (Consider
     all the permutations of shared or subst'd drives, etc.)  */
  {
    Extbyte *newext, *tempext;
    
    PATHNAME_CONVERT_OUT (newname, newext);
    PATHNAME_CONVERT_OUT (temp, tempext);
    if (XEUNICODE_P)
      {
	result = _wrename ((const wchar_t *) tempext,
			   (const wchar_t *) newext);
	if (result < 0
	    && (errno == EEXIST || errno == EACCES)
	    && _wchmod ((const wchar_t *) newext, 0666) == 0
	    && _wunlink ((const wchar_t *) newext) == 0)
	  result = _wrename ((const wchar_t *) tempext,
			     (const wchar_t *) newext);
      }
    else
      {
	result = rename (tempext, newext);
	if (result < 0
	    && (errno == EEXIST || errno == EACCES)
	    && _chmod (newext, 0666) == 0
	    && _unlink (newext) == 0)
	  result = rename (tempext, newext);
      }
  }

  return result;
}

int
mswindows_unlink (const Ibyte *path)
{
  Extbyte *pathout;

  PATHNAME_CONVERT_OUT (path, pathout);
  /* On Unix, unlink works without write permission. */
  if (XEUNICODE_P)
    {
      _wchmod ((const wchar_t *) pathout, 0666);
      return _wunlink ((const wchar_t *) pathout);
    }
  else
    {
      _chmod (pathout, 0666);
      return _unlink (pathout);
    }
}

static FILETIME utc_base_ft;
static long double utc_base;
static int init = 0;
static LARGE_INTEGER utc_base_li;

/* XEmacs: We seem to have a new definition of
   mswindows_convert_time(), although I'm not sure why. --ben */

time_t
mswindows_convert_time (FILETIME uft)
{
  time_t ret;
#ifndef MAXLONGLONG
  SYSTEMTIME st;
  struct tm t;
  FILETIME ft;
  TIME_ZONE_INFORMATION tzi;
  DWORD tzid;
#else
  LARGE_INTEGER lft;
#endif

  if (!init)
    {
      /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
      SYSTEMTIME st;

      st.wYear = 1970;
      st.wMonth = 1;
      st.wDay = 1;
      st.wHour = 0;
      st.wMinute = 0;
      st.wSecond = 0;
      st.wMilliseconds = 0;

      SystemTimeToFileTime (&st, &utc_base_ft);

      utc_base_li.LowPart = utc_base_ft.dwLowDateTime;
      utc_base_li.HighPart = utc_base_ft.dwHighDateTime;

      init = 1;
    }

#ifdef MAXLONGLONG

  /* On a compiler that supports long integers, do it the easy way */
  lft.LowPart = uft.dwLowDateTime;
  lft.HighPart = uft.dwHighDateTime;
  ret = (time_t) ((lft.QuadPart - utc_base_li.QuadPart) / 10000000);

#else

  /* Do it the hard way using mktime. */
  FileTimeToLocalFileTime(&uft, &ft);
  FileTimeToSystemTime (&ft, &st);
  tzid = GetTimeZoneInformation (&tzi);
  t.tm_year = st.wYear - 1900;
  t.tm_mon = st.wMonth - 1;
  t.tm_mday = st.wDay;
  t.tm_hour = st.wHour;
  t.tm_min = st.wMinute;
  t.tm_sec = st.wSecond;
  t.tm_isdst = (tzid == TIME_ZONE_ID_DAYLIGHT);
  /* st.wMilliseconds not applicable */
  ret = mktime(&t);
  if (ret == -1)
    {
      ret = 0;
    }

#endif

  return ret;
}

static void
convert_from_time_t (time_t time, FILETIME * pft)
{
  long double tmp;

  if (!init)
    {
      /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
      SYSTEMTIME st;

      st.wYear = 1970;
      st.wMonth = 1;
      st.wDay = 1;
      st.wHour = 0;
      st.wMinute = 0;
      st.wSecond = 0;
      st.wMilliseconds = 0;

      SystemTimeToFileTime (&st, &utc_base_ft);
      utc_base = (long double) utc_base_ft.dwHighDateTime
	* 4096 * 1024 * 1024 + utc_base_ft.dwLowDateTime;
      init = 1;
    }

  /* time in 100ns units since 1-Jan-1601 */
  tmp = (long double) time * 1e7 + utc_base;
  pft->dwHighDateTime = (DWORD) (tmp / (4096.0 * 1024 * 1024));
  pft->dwLowDateTime = (DWORD) (tmp - (4096.0 * 1024 * 1024) *
                                pft->dwHighDateTime);
}

#if 0
/* A comment from Emacs 20.6:

   No reason to keep this; faking inode values either by hashing or even
   using the file index from GetInformationByHandle, is not perfect and
   so by default Emacs doesn't use the inode values on Windows.
   Instead, we now determine file-truename correctly (except for
   possible drive aliasing etc).  */

/* XEmacs: Removed the fake-inodes code here, which was if 0'd out.
   If you want it, look in w32.c in Emacs 20.6. */
#endif

/* #### aichner@ecf.teradyne.com reported that with the library
   provided stat/fstat, (file-exist "d:\\tmp\\") =>> nil,
   (file-exist "d:\\tmp") =>> t, when d:\tmp exists. Whenever
   we opt to use non-encapsulated stat(), this should serve as
   a compatibility test. --kkm */

/* Provide fstat and utime as well as stat for consistent handling of
   file timestamps. */
int
mswindows_fstat (int desc, struct stat *buf)
{
  HANDLE fh = (HANDLE) _get_osfhandle (desc);
  BY_HANDLE_FILE_INFORMATION info;
  DWORD fake_inode;
  int permission;

  switch (GetFileType (fh) & ~FILE_TYPE_REMOTE)
    {
    case FILE_TYPE_DISK:
      buf->st_mode = _S_IFREG;
      if (!GetFileInformationByHandle (fh, &info))
	{
	  errno = EACCES;
	  return -1;
	}
      break;
    case FILE_TYPE_PIPE:
      buf->st_mode = _S_IFIFO;
      goto non_disk;
    case FILE_TYPE_CHAR:
    case FILE_TYPE_UNKNOWN:
    default:
      buf->st_mode = _S_IFCHR;
    non_disk:
      memset (&info, 0, sizeof (info));
      info.dwFileAttributes = 0;
      info.ftCreationTime = utc_base_ft;
      info.ftLastAccessTime = utc_base_ft;
      info.ftLastWriteTime = utc_base_ft;
    }

  if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
    {
      buf->st_mode = _S_IFDIR;
      buf->st_nlink = 2;	/* doesn't really matter */
      fake_inode = 0;		/* this doesn't either I think */
    }
  else
    {
      buf->st_nlink = (short) info.nNumberOfLinks;
      /* Might as well use file index to fake inode values, but this
	 is not guaranteed to be unique unless we keep a handle open
	 all the time (even then there are situations where it is
	 not unique).  Reputedly, there are at most 48 bits of info
      (on NTFS, presumably less on FAT). */
      fake_inode = info.nFileIndexLow ^ info.nFileIndexHigh;
    }

  /* MSVC defines _ino_t to be short; other libc's might not.  */
  if (sizeof (buf->st_ino) == 2)
    buf->st_ino = (unsigned short) (fake_inode ^ (fake_inode >> 16));
  else
    buf->st_ino = (unsigned short) fake_inode;

  /* consider files to belong to current user */
  buf->st_uid = 0;
  buf->st_gid = 0;

  buf->st_dev = info.dwVolumeSerialNumber;
  buf->st_rdev = info.dwVolumeSerialNumber;

  buf->st_size = info.nFileSizeLow;

  /* Convert timestamps to Unix format. */
  buf->st_mtime = mswindows_convert_time (info.ftLastWriteTime);
  buf->st_atime = mswindows_convert_time (info.ftLastAccessTime);
  if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
  buf->st_ctime = mswindows_convert_time (info.ftCreationTime);
  if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;

  /* determine rwx permissions */
  if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
    permission = _S_IREAD;
  else
    permission = _S_IREAD | _S_IWRITE;
  
  if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
    permission |= _S_IEXEC;
  else
    {
#if 0 /* no way of knowing the filename */
      if (mswindows_is_executable (name))
	permission |= _S_IEXEC;
#endif
    }

  buf->st_mode |= permission | (permission >> 3) | (permission >> 6);

  return 0;
}

/* MSVC stat function can't cope with UNC names and has other bugs, so
   replace it with our own.  This also allows us to calculate consistent
   inode values without hacks in the main Emacs code. */
int
mswindows_stat (const Ibyte *path, struct stat *buf)
{
  Ibyte *name, *r;
  WIN32_FIND_DATAW wfd;
  HANDLE fh;
  DWORD fake_inode;
  int permission;
  Bytecount len;
  int rootdir = FALSE;
  Extbyte *nameext;
  int errm;

  if (path == NULL || buf == NULL)
    {
      errno = EFAULT;
      return -1;
    }

  name = qxestrcpy (alloca_ibytes (qxestrlen (path) + 10), path);
  errm = SetErrorMode (SEM_FAILCRITICALERRORS
		       | SEM_NOOPENFILEERRORBOX);

  get_volume_info (name, &path);
  /* must be valid filename, no wild cards or other invalid characters */
  if (qxestrpbrk (name, "*?|<>\""))
    {
      errno = ENOENT;
      return -1;
    }

  /* If name is "c:/.." or "/.." then stat "c:/" or "/".  */
  r = IS_DEVICE_SEP (name[1]) ? &name[2] : name;
  if (IS_DIRECTORY_SEP (r[0]) && r[1] == '.' && r[2] == '.' && r[3] == '\0')
    {
      r[1] = r[2] = '\0';
    }

  /* Remove trailing directory separator, unless name is the root
     directory of a drive or UNC volume in which case ensure there
     is a trailing separator. */
  len = qxestrlen (name);
  rootdir = (path >= name + len - 1
	     && (IS_DIRECTORY_SEP (*path) || *path == 0));

  if (is_unc_volume (name))
    {
      DWORD attrs = unc_volume_file_attributes (name);

      if (attrs == -1)
	return -1;

      memset (&wfd, 0, sizeof (wfd));
      wfd.dwFileAttributes = attrs;
      wfd.ftCreationTime = utc_base_ft;
      wfd.ftLastAccessTime = utc_base_ft;
      wfd.ftLastWriteTime = utc_base_ft;
      /* XEmacs deleted: strcpy (wfd.cFileName, name);
	 Not used later on. */
    }
  else if (rootdir)
    {
      if (!IS_DIRECTORY_SEP (name[len-1]))
	qxestrcat (name, (Ibyte *) "\\");
      /* File has already been resolved and we don't want to do it again
	 in case of lstat() */
      nameext = ITEXT_TO_TSTR (name);
      if (qxeGetDriveType (nameext) < 2)
	{
	  SetErrorMode (errm);
	  errno = ENOENT;
	  return -1;
	}
      memset (&wfd, 0, sizeof (wfd));
      wfd.dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
      wfd.ftCreationTime = utc_base_ft;
      wfd.ftLastAccessTime = utc_base_ft;
      wfd.ftLastWriteTime = utc_base_ft;
      /* XEmacs deleted: strcpy (wfd.cFileName, name);
	 Not used later on. */
    }
  else
    {
      if (IS_DIRECTORY_SEP (name[len-1]))
	name[len - 1] = 0;

      /* (This is hacky, but helps when doing file completions on
	 network drives.)  Optimize by using information available from
	 active readdir if possible.  */
      if (dir_pathname)
	{
	  len = qxestrlen (dir_pathname);
	  if (len && IS_DIRECTORY_SEP (dir_pathname[len-1]))
	    len--;
	}
      if (dir_find_handle != INVALID_HANDLE_VALUE
	  && dir_pathname
	  && qxestrncasecmp_i18n (dir_pathname, name, len) == 0
	  && IS_DIRECTORY_SEP (name[len])
	  && qxestrcasecmp_i18n (name + len + 1,
				 (Ibyte *) dir_static.d_name) == 0)
	{
	  /* This was the last entry returned by readdir.  */
	  wfd = dir_find_data;
	}
      else
	{
	  nameext = ITEXT_TO_TSTR (name);
	  fh = qxeFindFirstFile (nameext, &wfd);
	  if (fh == INVALID_HANDLE_VALUE)
	    {
	      SetErrorMode (errm);
	      errno = ENOENT;
	      return -1;
	    }
	  FindClose (fh);
	  /* XEmacs: Don't need to convert wfd.cFileName because
	     not used later on. */
	}
    }

  if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
    {
      buf->st_mode = _S_IFDIR;
      buf->st_nlink = 2;	/* doesn't really matter */
      fake_inode = 0;		/* this doesn't either I think */
    }
  else 
    {
      if (!NILP (Vmswindows_get_true_file_attributes))
	/* File has already been resolved and we don't want to do it again
	   in case of lstat() */
	nameext = ITEXT_TO_TSTR (name);
      if (!NILP (Vmswindows_get_true_file_attributes)
	  /* No access rights required to get info.  */
	  && (fh = qxeCreateFile (nameext, 0, 0, NULL, OPEN_EXISTING, 0, NULL))
	  != INVALID_HANDLE_VALUE)
	{
	  /* This is more accurate in terms of getting the correct number
	     of links, but is quite slow (it is noticeable when Emacs is
	     making a list of file name completions). */
	  BY_HANDLE_FILE_INFORMATION info;

	  if (GetFileInformationByHandle (fh, &info))
	    {
	      buf->st_nlink = (short) info.nNumberOfLinks;
	      /* Might as well use file index to fake inode values, but this
		 is not guaranteed to be unique unless we keep a handle open
		 all the time (even then there are situations where it is
		 not unique).  Reputedly, there are at most 48 bits of info
		 (on NTFS, presumably less on FAT). */
	      fake_inode = info.nFileIndexLow ^ info.nFileIndexHigh;
	    }
	  else
	    {
	      buf->st_nlink = 1;
	      fake_inode = 0;
	    }

	  switch (GetFileType (fh))
	    {
	    case FILE_TYPE_DISK:
	      buf->st_mode = _S_IFREG;
	      break;
	    case FILE_TYPE_PIPE:
	      buf->st_mode = _S_IFIFO;
	      break;
	    case FILE_TYPE_CHAR:
	    case FILE_TYPE_UNKNOWN:
	    default:
	      buf->st_mode = _S_IFCHR;
	    }
	  CloseHandle (fh);
	}
      else
	{
	  /* Don't bother to make this information more accurate.  */
	  buf->st_mode = _S_IFREG;
	  buf->st_nlink = 1;
	  fake_inode = 0;
	}

      if (mswindows_shortcuts_are_symlinks &&
	  buf->st_mode == _S_IFREG)
	{
	  len = qxestrlen (name);
	  if (len > 4 && !qxestrcasecmp_ascii (name + len - 4, ".LNK"))
	    {
	      /* check if link is valid */
	      Ibyte *resolved = mswindows_read_link (name);
	      if (resolved)
		{
		  xfree (resolved);
		  buf->st_mode = S_IFLNK;
		}
	    }
	}
    }

  SetErrorMode (errm);

#if 0
  /* XEmacs: Removed the fake-inodes code here, which was if 0'd out.
     If you want it, look in w32.c in Emacs 20.6. */
#endif

  /* MSVC defines _ino_t to be short; other libc's might not.  */
  if (sizeof (buf->st_ino) == 2)
    buf->st_ino = (unsigned short) (fake_inode ^ (fake_inode >> 16));
  else
    buf->st_ino = (unsigned short) fake_inode;

  /* consider files to belong to current user */
  buf->st_uid = the_passwd.pw_uid;
  buf->st_gid = the_passwd.pw_gid;

  /* volume_info is set by get_volume_info */
  buf->st_dev = volume_info.serialnum;
  buf->st_rdev = volume_info.serialnum;


  buf->st_size = wfd.nFileSizeLow;

  /* Convert timestamps to Unix format. */
  buf->st_mtime = mswindows_convert_time (wfd.ftLastWriteTime);
  buf->st_atime = mswindows_convert_time (wfd.ftLastAccessTime);
  if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
  buf->st_ctime = mswindows_convert_time (wfd.ftCreationTime);
  if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;

  /* determine rwx permissions */
  if (wfd.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
    permission = _S_IREAD;
  else
    permission = _S_IREAD | _S_IWRITE;
  
  if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
    permission |= _S_IEXEC;
  else if (mswindows_is_executable (name))
    permission |= _S_IEXEC;

  buf->st_mode |= permission | (permission >> 3) | (permission >> 6);

  return 0;
}

int
mswindows_utime (Lisp_Object path, struct utimbuf *times)
{
  /* #### Supposedly we're providing this because standard utime()
     might not work; or at the very least to get consistent results
     since we replace other time-handling routines in stat.  But out
     replacement doesn't seem to work, probably due to some subtle bug
     in this routine, which should be investigated eventually.  So for
     the moment, we just use utime(), which conceivably might be
     slightly off in comparison with our own routines?  Seems strange,
     and so far no problems seen. --ben */

  struct utimbuf deftime;
#if 0
  HANDLE fh;
#endif
  static FILETIME mtime;
  static FILETIME atime;
  Extbyte *filename;

  if (times == NULL)
    {
      deftime.modtime = deftime.actime = time (NULL);
      times = &deftime;
    }

  LISP_PATHNAME_CONVERT_OUT (path, filename);
  /* APA: SetFileTime fails to set mtime correctly (always 1-Jan-1970) */
#if 0
  /* Need write access to set times.  */
  fh = qxeCreateFile (filename, GENERIC_WRITE,
		      FILE_SHARE_READ | FILE_SHARE_WRITE,
		      0, OPEN_EXISTING, 0, NULL);
  if (fh)
    {
      convert_from_time_t (times->actime, &atime);
      convert_from_time_t (times->modtime, &mtime);
      if (!SetFileTime (fh, NULL, &atime, &mtime))
	{
	  CloseHandle (fh);
	  errno = EACCES;
	  return -1;
	}
      CloseHandle (fh);
    }
  else
    {
      errno = EINVAL;
      return -1;
    }
  return 0;
#else
  {
    struct _utimbuf newtimes;

    newtimes.actime = times->actime;
    newtimes.modtime = times->modtime;

  if (XEUNICODE_P)
    return _wutime ((const wchar_t *) filename, &newtimes);
  else
    return _utime (filename, &newtimes);
  }
#endif
}

Ibyte *
mswindows_getdcwd (int drivelet)
{
  Extbyte *cwdext;
  Ibyte *cwd;
  /* Following comment and two-liner fix comes from
     https://bugzilla.mozilla.org/show_bug.cgi?id=419326 which
     apparently fell prey to this feature of msvcrt8 as well. */
  /* We need to worry about IPH, for details read bug 419326.
   * _getdrives - http://msdn2.microsoft.com/en-us/library/xdhk0xd2.aspx 
   * uses a bitmask, bit 0 is 'a:'
   * _chdrive - http://msdn2.microsoft.com/en-us/library/0d1409hb.aspx
   * _getdcwd - http://msdn2.microsoft.com/en-us/library/7t2zk3s4.aspx
   * take an int, 1 is 'a:'.
   *
   * Because of this, we need to do some math. Subtract 1 to convert from
   * _chdrive/_getdcwd format to _getdrives drive numbering.
   * Shift left x bits to convert from integer indexing to bitfield indexing.
   * And of course, we need to find out if the drive is in the bitmask.
   *
   * If we're really unlucky, we can still lose, but only if the user
   * manages to eject the drive between our call to _getdrives() and
   * our *calls* to _wgetdcwd.
   */
  if (!((1 << (drivelet - 1)) & _getdrives()))
    return NULL;
  if (XEUNICODE_P)
    cwdext = (Extbyte *) _wgetdcwd (drivelet, NULL, 0);
  else
    cwdext = _getdcwd (drivelet, NULL, 0);
  if (cwdext == NULL) return NULL;
  cwd = TSTR_TO_ITEXT_MALLOC (cwdext);
  xfree (cwdext);
  return cwd;
}


/*--------------------------------------------------------------------*/
/*                        Memory-mapped files                         */
/*--------------------------------------------------------------------*/

int
open_input_file (file_data *p_file, const Ibyte *filename)
{
  /* Synched with FSF 20.6.  We fixed some warnings. */
  HANDLE file;
  HANDLE file_mapping;
  void *file_base;
  DWORD size, upper_size;
  Extbyte *fileext;

  PATHNAME_CONVERT_OUT (filename, fileext);

  file = qxeCreateFile (fileext, GENERIC_READ, FILE_SHARE_READ, NULL,
			OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  if (file == INVALID_HANDLE_VALUE) 
    return FALSE;

  size = GetFileSize (file, &upper_size);
  file_mapping = qxeCreateFileMapping (file, NULL, PAGE_READONLY, 
				       0, size, NULL);
  if (!file_mapping) 
    return FALSE;

  file_base = MapViewOfFile (file_mapping, FILE_MAP_READ, 0, 0, size);
  if (file_base == 0) 
    return FALSE;

  p_file->name = filename;
  p_file->size = size;
  p_file->file = file;
  p_file->file_mapping = file_mapping;
  p_file->file_base = file_base;

  return TRUE;
}

int
open_output_file (file_data *p_file, const Ibyte *filename,
		  unsigned long size)
{
  /* Synched with FSF 20.6.  We fixed some warnings. */
  HANDLE file;
  HANDLE file_mapping;
  void *file_base;
  Extbyte *fileext;

  PATHNAME_CONVERT_OUT (filename, fileext);

  file = qxeCreateFile (fileext, GENERIC_READ | GENERIC_WRITE, 0, NULL,
			CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  if (file == INVALID_HANDLE_VALUE) 
    return FALSE;

  file_mapping = qxeCreateFileMapping (file, NULL, PAGE_READWRITE, 
				       0, size, NULL);
  if (!file_mapping) 
    return FALSE;
  
  file_base = MapViewOfFile (file_mapping, FILE_MAP_WRITE, 0, 0, size);
  if (file_base == NULL) 
    return FALSE;
  
  p_file->name = filename;
  p_file->size = size;
  p_file->file = file;
  p_file->file_mapping = file_mapping;
  p_file->file_base = file_base;

  return TRUE;
}

#if 1 /* !defined(MINGW) */
/* Return pointer to section header for section containing the given
   relative virtual address. */
static IMAGE_SECTION_HEADER *
rva_to_section (DWORD rva, IMAGE_NT_HEADERS *nt_header)
{
  /* Synched with FSF 20.6.  We added MINGW stuff. */
  PIMAGE_SECTION_HEADER section;
  int i;

  section = IMAGE_FIRST_SECTION (nt_header);

  for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
    {
      /* Some linkers (eg. the NT SDK linker I believe) swapped the
	 meaning of these two values - or rather, they ignored
	 VirtualSize entirely and always set it to zero.  This affects
	 some very old exes (eg. gzip dated Dec 1993).  Since
	 mswindows_executable_type relies on this function to work reliably,
	 we need to cope with this.  */
      DWORD real_size = max (section->SizeOfRawData,
			     section->Misc.VirtualSize);
      if (rva >= section->VirtualAddress
	  && rva < section->VirtualAddress + real_size)
	return section;
      section++;
    }
  return NULL;
}
#endif

void
mswindows_executable_type (const Ibyte *filename, int *is_dos_app,
			   int *is_cygnus_app)
{
  /* Synched with FSF 20.6.  We added MINGW stuff and casts. */
  file_data executable;
  Ibyte *p;

  /* Default values in case we can't tell for sure.  */
  *is_dos_app = FALSE;
  *is_cygnus_app = FALSE;

  if (!open_input_file (&executable, filename))
    return;

  p = qxestrrchr (filename, '.');

  /* We can only identify DOS .com programs from the extension. */
  if (p && qxestrcasecmp_ascii (p, ".com") == 0)
    *is_dos_app = TRUE;
  else if (p && (qxestrcasecmp_ascii (p, ".bat") == 0 ||
		 qxestrcasecmp_ascii (p, ".cmd") == 0))
    {
      /* A DOS shell script - it appears that CreateProcess is happy to
	 accept this (somewhat surprisingly); presumably it looks at
	 COMSPEC to determine what executable to actually invoke.
	 Therefore, we have to do the same here as well. */
      /* Actually, I think it uses the program association for that
	 extension, which is defined in the registry.  */
      p = egetenv ("COMSPEC");
      if (p)
	mswindows_executable_type (p, is_dos_app, is_cygnus_app);
    }
  else
    {
      /* Look for DOS .exe signature - if found, we must also check that
	 it isn't really a 16- or 32-bit Windows exe, since both formats
	 start with a DOS program stub.  Note that 16-bit Windows
	 executables use the OS/2 1.x format. */

#if 0 /* defined( MINGW ) */
      /* mingw doesn't have enough headers to detect cygwin
	 apps, just do what we can. */
      FILHDR *exe_header;

      exe_header = (FILHDR *) executable.file_base;
      if (exe_header->e_magic != DOSMAGIC)
	goto unwind;

      if ((Rawbyte *) exe_header->e_lfanew > (Rawbyte *) executable.size)
	{
	  /* Some dos headers (pkunzip) have bogus e_lfanew fields.  */
	  *is_dos_app = TRUE;
	} 
      else if (exe_header->nt_signature != NT_SIGNATURE)
	{
	  *is_dos_app = TRUE;
	}
#else
      IMAGE_DOS_HEADER *dos_header;
      IMAGE_NT_HEADERS *nt_header;

      dos_header = (PIMAGE_DOS_HEADER) executable.file_base;
      if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
	goto unwind;
	  
      nt_header = (PIMAGE_NT_HEADERS) ((Rawbyte *) dos_header +
				       dos_header->e_lfanew);
	  
      if ((Rawbyte *) nt_header > (Rawbyte *) dos_header + executable.size) 
	{
	  /* Some dos headers (pkunzip) have bogus e_lfanew fields.  */
	  *is_dos_app = TRUE;
	} 
      else if (nt_header->Signature != IMAGE_NT_SIGNATURE &&
	       LOWORD (nt_header->Signature) != IMAGE_OS2_SIGNATURE)
	{
	  *is_dos_app = TRUE;
	}
      else if (nt_header->Signature == IMAGE_NT_SIGNATURE)
	{
	  /* Look for cygwin.dll in DLL import list. */
	  IMAGE_DATA_DIRECTORY import_dir =
	    nt_header->OptionalHeader.
	      DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
	  IMAGE_IMPORT_DESCRIPTOR *imports;
	  IMAGE_SECTION_HEADER *section;

	  section = rva_to_section (import_dir.VirtualAddress, nt_header);
	  imports =
	    (IMAGE_IMPORT_DESCRIPTOR *) RVA_TO_PTR (import_dir.VirtualAddress,
						    section, executable);

	  for ( ; imports->Name; imports++)
	    {
	      Extbyte *dllname_ext =
		(Extbyte *) RVA_TO_PTR (imports->Name, section, executable);
	      Ibyte *dllname;

	      dllname = EXTERNAL_TO_ITEXT (dllname_ext, Qbinary);

	      /* The exact name of the cygwin dll has changed with
		 various releases, but hopefully this will be reasonably
		 future proof.  */
	      if (qxestrncasecmp (dllname, (Ibyte *) "cygwin", 6) == 0)
		{
		  *is_cygnus_app = TRUE;
		  break;
		}
	    }
	}
#endif
    }

 unwind:
  close_file_data (&executable);
}

/* Close the system structures associated with the given file.  */
void
close_file_data (file_data *p_file)
{
  UnmapViewOfFile (p_file->file_base);
  CloseHandle (p_file->file_mapping);
  CloseHandle (p_file->file);
}


/* Some miscellaneous functions that are Windows specific, but not GUI
   specific (ie. are applicable in terminal or batch mode as well).  */

DEFUN ("mswindows-short-file-name", Fmswindows_short_file_name, 1, 1, 0, /*
  Return the short file name version (8.3) of the full path of FILENAME.
If FILENAME does not exist, return nil.
All path elements in FILENAME are converted to their short names.
*/
       (filename))
{
  Extbyte shortname[PATH_MAX_TCHAR];
  Extbyte *fileext;
  Ibyte *shortint;

  CHECK_STRING (filename);

  /* first expand it.  */
  filename = Fexpand_file_name (filename, Qnil);

  LISP_PATHNAME_CONVERT_OUT (filename, fileext);
  /* luckily, this returns the short version of each element in the path.  */
  if (qxeGetShortPathName (fileext, shortname,
			   sizeof (shortname) / XETCHAR_SIZE) == 0)
    return Qnil;

  shortint = TSTR_TO_ITEXT (shortname);
  MSWINDOWS_NORMALIZE_FILENAME (shortint);

  return build_istring (shortint);
}


DEFUN ("mswindows-long-file-name", Fmswindows_long_file_name, 1, 1, 0, /*
  Return the long file name version of the full path of FILENAME.
If FILENAME does not exist, return nil.
All path elements in FILENAME are converted to their long names.
*/
       (filename))
{
  Ibyte *longname, *canon;
  Lisp_Object ret;

  CHECK_STRING (filename);

  /* first expand it.  */
  filename = Fexpand_file_name (filename, Qnil);

  if (!(longname = mswindows_get_long_filename (XSTRING_DATA (filename))))
    return Qnil;

  canon = mswindows_canonicalize_filename (longname);
  ret = build_istring (canon);
  xfree (canon);
  xfree (longname);
  return ret;
}


void
init_nt (void)
{
  /* Initial preparation for subprocess support: replace our standard
     handles with non-inheritable versions.

     #### Do we still need this?  This is left over from the old process
     support. */
  {
    HANDLE parent;
    HANDLE stdin_save =  INVALID_HANDLE_VALUE;
    HANDLE stdout_save = INVALID_HANDLE_VALUE;
    HANDLE stderr_save = INVALID_HANDLE_VALUE;

    parent = GetCurrentProcess ();

    /* ignore errors when duplicating and closing; typically the
       handles will be invalid when running as a gui program. */
    DuplicateHandle (parent, 
		     GetStdHandle (STD_INPUT_HANDLE), 
		     parent,
		     &stdin_save, 
		     0, 
		     FALSE, 
		     DUPLICATE_SAME_ACCESS);
    
    DuplicateHandle (parent,
		     GetStdHandle (STD_OUTPUT_HANDLE),
		     parent,
		     &stdout_save,
		     0,
		     FALSE,
		     DUPLICATE_SAME_ACCESS);
    
    DuplicateHandle (parent,
		     GetStdHandle (STD_ERROR_HANDLE),
		     parent,
		     &stderr_save,
		     0,
		     FALSE,
		     DUPLICATE_SAME_ACCESS);
    
    retry_fclose (stdin);
    retry_fclose (stdout);
    retry_fclose (stderr);

    if (stdin_save != INVALID_HANDLE_VALUE)
      _open_osfhandle ((long) stdin_save, O_TEXT);
    else
      _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
    _fdopen (0, "r");

    if (stdout_save != INVALID_HANDLE_VALUE)
      _open_osfhandle ((long) stdout_save, O_TEXT);
    else
      _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
    _fdopen (1, "w");

    if (stderr_save != INVALID_HANDLE_VALUE)
      _open_osfhandle ((long) stderr_save, O_TEXT);
    else
      _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
    _fdopen (2, "w");
  }

  /* determine which drives are fixed, for get_cached_volume_information */
  {
    /* GetDriveType must have trailing backslash. */
    Ibyte drive[] = "A:\\";

    /* Loop over all possible drive letters */
    while (*drive <= 'Z')
    {
      Extbyte *driveext;

      PATHNAME_CONVERT_OUT (drive, driveext);

      /* Record if this drive letter refers to a fixed drive. */
      fixed_drives[DRIVE_INDEX (*drive)] =
	(qxeGetDriveType (driveext) == DRIVE_FIXED);

      (*drive)++;
    }

    /* Reset the volume info cache.  */
    volume_cache = NULL;
  }
}

void
syms_of_nt (void)
{
  DEFSUBR (Fmswindows_short_file_name);
  DEFSUBR (Fmswindows_long_file_name);
}

void
vars_of_nt (void)
{
  DEFVAR_INT ("mswindows-fake-unix-uid", &mswindows_fake_unix_uid /*
*Set uid returned by `user-uid' and `user-real-uid'.
Under NT and 9x, there are no uids, and even no almighty user called root.
By setting this variable, you can have any uid of choice.  Default is 0.
Changes to this variable take effect immediately.
*/ );
  mswindows_fake_unix_uid = 0;

  DEFVAR_LISP ("mswindows-get-true-file-attributes", &Vmswindows_get_true_file_attributes /*
Non-nil means determine accurate link count in file-attributes.
This option slows down file-attributes noticeably, so is disabled by
default.  Note that it is only useful for files on NTFS volumes,
where hard links are supported.
*/ );
  Vmswindows_get_true_file_attributes = Qnil;
}

/* end of nt.c */