summaryrefslogtreecommitdiff
path: root/src/kash/shfile.c
blob: 84511ca130b998bba779263037d47cb286f5b689 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
/* $Id: shfile.c 2681 2013-04-14 18:41:58Z bird $ */
/** @file
 *
 * File management.
 *
 * Copyright (c) 2007-2010 knut st. osmundsen <bird-kBuild-spamx@anduin.net>
 *
 *
 * This file is part of kBuild.
 *
 * kBuild 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 of the License, or
 * (at your option) any later version.
 *
 * kBuild 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 kBuild; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

/*******************************************************************************
*   Header Files                                                               *
*******************************************************************************/
#include "shfile.h"
#include "shinstance.h" /* TRACE2 */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>

#if K_OS == K_OS_WINDOWS
# include <limits.h>
# ifndef PIPE_BUF
#  define PIPE_BUF 512
# endif
# include <ntstatus.h>
# define WIN32_NO_STATUS
# include <Windows.h>
# if !defined(_WIN32_WINNT)
#  define _WIN32_WINNT 0x0502 /* Windows Server 2003 */
# endif
# include <winternl.h> //NTSTATUS
#else
# include <unistd.h>
# include <fcntl.h>
# include <dirent.h>
#endif


/*******************************************************************************
*   Defined Constants And Macros                                               *
*******************************************************************************/
/** @def SHFILE_IN_USE
 * Whether the file descriptor table stuff is actually in use or not.
 */
#if K_OS == K_OS_WINDOWS \
 || K_OS == K_OS_OPENBSD /* because of ugly pthread library pipe hacks */ \
 || !defined(SH_FORKED_MODE)
# define SHFILE_IN_USE
#endif
/** The max file table size. */
#define SHFILE_MAX          1024
/** The file table growth rate. */
#define SHFILE_GROW         64
/** The min native unix file descriptor. */
#define SHFILE_UNIX_MIN_FD  32
/** The path buffer size we use. */
#define SHFILE_MAX_PATH     4096

/** Set errno and return. Doing a trace in debug build. */
#define RETURN_ERROR(rc, err, msg)  \
    do { \
        TRACE2((NULL, "%s: " ## msg ## " - returning %d / %d\n", __FUNCTION__, (rc), (err))); \
        errno = (err); \
        return (rc); \
    } while (0)

#if K_OS == K_OS_WINDOWS
 /* See msdos.h for description. */
# define FOPEN              0x01
# define FEOFLAG            0x02
# define FCRLF              0x04
# define FPIPE              0x08
# define FNOINHERIT         0x10
# define FAPPEND            0x20
# define FDEV               0x40
# define FTEXT              0x80

# define MY_ObjectBasicInformation 0
# define MY_FileNamesInformation 12

typedef struct
{
    ULONG           Attributes;
	ACCESS_MASK     GrantedAccess;
	ULONG           HandleCount;
	ULONG           PointerCount;
	ULONG           PagedPoolUsage;
	ULONG           NonPagedPoolUsage;
	ULONG           Reserved[3];
	ULONG           NameInformationLength;
	ULONG           TypeInformationLength;
	ULONG           SecurityDescriptorLength;
	LARGE_INTEGER   CreateTime;
} MY_OBJECT_BASIC_INFORMATION;

#if 0
typedef struct
{
    union
    {
        LONG    Status;
        PVOID   Pointer;
    };
    ULONG_PTR   Information;
} MY_IO_STATUS_BLOCK;
#else
typedef IO_STATUS_BLOCK MY_IO_STATUS_BLOCK;
#endif
typedef MY_IO_STATUS_BLOCK *PMY_IO_STATUS_BLOCK;

typedef struct
{
    ULONG   NextEntryOffset;
    ULONG   FileIndex;
    ULONG   FileNameLength;
    WCHAR   FileName[1];
} MY_FILE_NAMES_INFORMATION, *PMY_FILE_NAMES_INFORMATION;

typedef NTSTATUS (NTAPI * PFN_NtQueryObject)(HANDLE, int, void *, size_t, size_t *);
typedef NTSTATUS (NTAPI * PFN_NtQueryDirectoryFile)(HANDLE, HANDLE, void *,  void *, PMY_IO_STATUS_BLOCK, void *,
                                                    ULONG, int, int, PUNICODE_STRING, int);
typedef NTSTATUS (NTAPI * PFN_RtlUnicodeStringToAnsiString)(PANSI_STRING, PCUNICODE_STRING, int);


#endif /* K_OS_WINDOWS */


/*******************************************************************************
*   Global Variables                                                           *
*******************************************************************************/
#if K_OS == K_OS_WINDOWS
static int                              g_shfile_globals_initialized = 0;
static PFN_NtQueryObject                g_pfnNtQueryObject = NULL;
static PFN_NtQueryDirectoryFile         g_pfnNtQueryDirectoryFile = NULL;
static PFN_RtlUnicodeStringToAnsiString g_pfnRtlUnicodeStringToAnsiString = NULL;
#endif /* K_OS_WINDOWS */


#ifdef SHFILE_IN_USE

/**
 * Close the specified native handle.
 *
 * @param   native      The native file handle.
 * @param   flags       The flags in case they might come in handy later.
 */
static void shfile_native_close(intptr_t native, unsigned flags)
{
# if K_OS == K_OS_WINDOWS
    BOOL fRc = CloseHandle((HANDLE)native);
    assert(fRc); (void)fRc;
# else
    int s = errno;
    close(native);
    errno = s;
# endif
    (void)flags;
}

/**
 * Grows the descriptor table, making sure that it can hold @a fdMin,
 *
 * @returns The max(fdMin, fdFirstNew) on success, -1 on failure.
 * @param   pfdtab      The table to grow.
 * @param   fdMin       Grow to include this index.
 */
static int shfile_grow_tab_locked(shfdtab *pfdtab, int fdMin)
{
    /*
     * Grow the descriptor table.
     */
    int         fdRet = -1;
    shfile     *new_tab;
    int         new_size = pfdtab->size + SHFILE_GROW;
    while (new_size < fdMin)
        new_size += SHFILE_GROW;
    new_tab = sh_realloc(shthread_get_shell(), pfdtab->tab, new_size * sizeof(shfile));
    if (new_tab)
    {
        int     i;
        for (i = pfdtab->size; i < new_size; i++)
        {
            new_tab[i].fd = -1;
            new_tab[i].oflags = 0;
            new_tab[i].shflags = 0;
            new_tab[i].native = -1;
        }

        fdRet = pfdtab->size;
        if (fdRet < fdMin)
            fdRet = fdMin;

        pfdtab->tab = new_tab;
        pfdtab->size = new_size;
    }

    return fdRet;
}

/**
 * Inserts the file into the descriptor table.
 *
 * If we're out of memory and cannot extend the table, we'll close the
 * file, set errno to EMFILE and return -1.
 *
 * @returns The file descriptor number. -1 and errno on failure.
 * @param   pfdtab      The file descriptor table.
 * @param   native      The native file handle.
 * @param   oflags      The flags the it was opened/created with.
 * @param   shflags     The shell file flags.
 * @param   fdMin       The minimum file descriptor number, pass -1 if any is ok.
 * @param   who         Who we're doing this for (for logging purposes).
 */
static int shfile_insert(shfdtab *pfdtab, intptr_t native, unsigned oflags, unsigned shflags, int fdMin, const char *who)
{
    shmtxtmp tmp;
    int fd;
    int i;

    /*
     * Fend of bad stuff.
     */
    if (fdMin >= SHFILE_MAX)
    {
        errno = EMFILE;
        return -1;
    }
# if K_OS != K_OS_WINDOWS
    if (fcntl((int)native, F_SETFD, fcntl((int)native, F_GETFD, 0) | FD_CLOEXEC) == -1)
    {
        int e = errno;
        close((int)native);
        errno = e;
        return -1;
    }
# endif

    shmtx_enter(&pfdtab->mtx, &tmp);

    /*
     * Search for a fitting unused location.
     */
    fd = -1;
    for (i = fdMin >= 0 ? fdMin : 0; (unsigned)i < pfdtab->size; i++)
        if (pfdtab->tab[i].fd == -1)
        {
            fd = i;
            break;
        }
    if (fd == -1)
        fd = shfile_grow_tab_locked(pfdtab, fdMin);

    /*
     * Fill in the entry if we've found one.
     */
    if (fd != -1)
    {
        pfdtab->tab[fd].fd = fd;
        pfdtab->tab[fd].oflags = oflags;
        pfdtab->tab[fd].shflags = shflags;
        pfdtab->tab[fd].native = native;
    }
    else
        shfile_native_close(native, oflags);

    shmtx_leave(&pfdtab->mtx, &tmp);

    if (fd == -1)
        errno = EMFILE;
    (void)who;
    return fd;
}

# if K_OS != K_OS_WINDOWS
/**
 * Makes a copy of the native file, closes the original, and inserts the copy
 * into the descriptor table.
 *
 * If we're out of memory and cannot extend the table, we'll close the
 * file, set errno to EMFILE and return -1.
 *
 * @returns The file descriptor number. -1 and errno on failure.
 * @param   pfdtab      The file descriptor table.
 * @param   pnative     The native file handle on input, -1 on output.
 * @param   oflags      The flags the it was opened/created with.
 * @param   shflags     The shell file flags.
 * @param   fdMin       The minimum file descriptor number, pass -1 if any is ok.
 * @param   who         Who we're doing this for (for logging purposes).
 */
static int shfile_copy_insert_and_close(shfdtab *pfdtab, int *pnative, unsigned oflags, unsigned shflags, int fdMin, const char *who)
{
    int fd          = -1;
    int s           = errno;
    int native_copy = fcntl(*pnative, F_DUPFD, SHFILE_UNIX_MIN_FD);
    close(*pnative);
    *pnative = -1;
    errno = s;

    if (native_copy != -1)
        fd = shfile_insert(pfdtab, native_copy, oflags, shflags, fdMin, who);
    return fd;
}
# endif /* !K_OS_WINDOWS */

/**
 * Gets a file descriptor and lock the file descriptor table.
 *
 * @returns Pointer to the file and table ownership on success,
 *          NULL and errno set to EBADF on failure.
 * @param   pfdtab      The file descriptor table.
 * @param   fd          The file descriptor number.
 * @param   ptmp        See shmtx_enter.
 */
static shfile *shfile_get(shfdtab *pfdtab, int fd, shmtxtmp *ptmp)
{
    shfile *file = NULL;
    if (    fd >= 0
        &&  (unsigned)fd < pfdtab->size)
    {
        shmtx_enter(&pfdtab->mtx, ptmp);
        if ((unsigned)fd < pfdtab->size
            &&  pfdtab->tab[fd].fd != -1)
            file = &pfdtab->tab[fd];
        else
            shmtx_leave(&pfdtab->mtx, ptmp);
    }
    if (!file)
        errno = EBADF;
    return file;
}

/**
 * Puts back a file descriptor and releases the table ownership.
 *
 * @param   pfdtab      The file descriptor table.
 * @param   file        The file.
 * @param   ptmp        See shmtx_leave.
 */
static void shfile_put(shfdtab *pfdtab, shfile *file, shmtxtmp *ptmp)
{
    shmtx_leave(&pfdtab->mtx, ptmp);
    assert(file);
    (void)file;
}

/**
 * Constructs a path from the current directory and the passed in path.
 *
 * @returns 0 on success, -1 and errno set to ENAMETOOLONG or EINVAL on failure.
 *
 * @param   pfdtab      The file descriptor table
 * @param   path        The path the caller supplied.
 * @param   buf         Where to put the path. This is assumed to be SHFILE_MAX_PATH
 *                      chars in size.
 */
int shfile_make_path(shfdtab *pfdtab, const char *path, char *buf)
{
    size_t path_len = strlen(path);
    if (path_len == 0)
    {
        errno = EINVAL;
        return -1;
    }
    if (path_len >= SHFILE_MAX_PATH)
    {
        errno = ENAMETOOLONG;
        return -1;
    }
    if (    *path == '/'
# if K_OS == K_OS_WINDOWS || K_OS == K_OS_OS2
        ||  *path == '\\'
        ||  (   *path
             && path[1] == ':'
             && (   (*path >= 'A' && *path <= 'Z')
                 || (*path >= 'a' && *path <= 'z')))
# endif
        )
    {
        memcpy(buf, path, path_len + 1);
    }
    else
    {
        size_t      cwd_len;
        shmtxtmp    tmp;

        shmtx_enter(&pfdtab->mtx, &tmp);

        cwd_len = strlen(pfdtab->cwd);
        memcpy(buf, pfdtab->cwd, cwd_len);

        shmtx_leave(&pfdtab->mtx, &tmp);

        if (cwd_len + path_len + 1 >= SHFILE_MAX_PATH)
        {
            errno = ENAMETOOLONG;
            return -1;
        }
        if (    !cwd_len
            ||  buf[cwd_len - 1] != '/')
            buf[cwd_len++] = '/';
        memcpy(buf + cwd_len, path, path_len + 1);
    }

# if K_OS == K_OS_WINDOWS || K_OS == K_OS_OS2
    if (!strcmp(buf, "/dev/null"))
        strcpy(buf, "NUL");
# endif
    return 0;
}

# if K_OS == K_OS_WINDOWS

/**
 * Adjusts the file name if it ends with a trailing directory slash.
 *
 * Windows APIs doesn't like trailing slashes.
 *
 * @returns 1 if it has a directory slash, 0 if not.
 *
 * @param   abspath     The path to adjust (SHFILE_MAX_PATH).
 */
static int shfile_trailing_slash_hack(char *abspath)
{
    /*
     * Anything worth adjust here?
     */
    size_t path_len = strlen(abspath);
    if (   path_len == 0
        || (   abspath[path_len - 1] != '/'
#  if K_OS == K_OS_WINDOWS || K_OS == K_OS_OS2
            && abspath[path_len - 1] != '\\'
#  endif
           )
       )
        return 0;

    /*
     * Ok, make the adjustment.
     */
    if (path_len + 2 <= SHFILE_MAX_PATH)
    {
        /* Add a '.' to the end. */
        abspath[path_len++] = '.';
        abspath[path_len]   = '\0';
    }
    else
    {
        /* No space for a dot, remove the slash if it's alone or just remove
           one and add a dot like above. */
        if (   abspath[path_len - 2] != '/'
#  if K_OS == K_OS_WINDOWS || K_OS == K_OS_OS2
            && abspath[path_len - 2] != '\\'
#  endif
           )
            abspath[--path_len] = '\0';
        else
            abspath[path_len - 1] = '.';
    }

    return 1;
}


/**
 * Converts a DOS(/Windows) error code to errno,
 * assigning it to errno.
 *
 * @returns -1
 * @param   err     The DOS error.
 */
static int shfile_dos2errno(int err)
{
    switch (err)
    {
        case ERROR_BAD_ENVIRONMENT:         errno = E2BIG;      break;
        case ERROR_ACCESS_DENIED:           errno = EACCES;     break;
        case ERROR_CURRENT_DIRECTORY:       errno = EACCES;     break;
        case ERROR_LOCK_VIOLATION:          errno = EACCES;     break;
        case ERROR_NETWORK_ACCESS_DENIED:   errno = EACCES;     break;
        case ERROR_CANNOT_MAKE:             errno = EACCES;     break;
        case ERROR_FAIL_I24:                errno = EACCES;     break;
        case ERROR_DRIVE_LOCKED:            errno = EACCES;     break;
        case ERROR_SEEK_ON_DEVICE:          errno = EACCES;     break;
        case ERROR_NOT_LOCKED:              errno = EACCES;     break;
        case ERROR_LOCK_FAILED:             errno = EACCES;     break;
        case ERROR_NO_PROC_SLOTS:           errno = EAGAIN;     break;
        case ERROR_MAX_THRDS_REACHED:       errno = EAGAIN;     break;
        case ERROR_NESTING_NOT_ALLOWED:     errno = EAGAIN;     break;
        case ERROR_INVALID_HANDLE:          errno = EBADF;      break;
        case ERROR_INVALID_TARGET_HANDLE:   errno = EBADF;      break;
        case ERROR_DIRECT_ACCESS_HANDLE:    errno = EBADF;      break;
        case ERROR_WAIT_NO_CHILDREN:        errno = ECHILD;     break;
        case ERROR_CHILD_NOT_COMPLETE:      errno = ECHILD;     break;
        case ERROR_FILE_EXISTS:             errno = EEXIST;     break;
        case ERROR_ALREADY_EXISTS:          errno = EEXIST;     break;
        case ERROR_INVALID_FUNCTION:        errno = EINVAL;     break;
        case ERROR_INVALID_ACCESS:          errno = EINVAL;     break;
        case ERROR_INVALID_DATA:            errno = EINVAL;     break;
        case ERROR_INVALID_PARAMETER:       errno = EINVAL;     break;
        case ERROR_NEGATIVE_SEEK:           errno = EINVAL;     break;
        case ERROR_TOO_MANY_OPEN_FILES:     errno = EMFILE;     break;
        case ERROR_FILE_NOT_FOUND:          errno = ENOENT;     break;
        case ERROR_PATH_NOT_FOUND:          errno = ENOENT;     break;
        case ERROR_INVALID_DRIVE:           errno = ENOENT;     break;
        case ERROR_NO_MORE_FILES:           errno = ENOENT;     break;
        case ERROR_BAD_NETPATH:             errno = ENOENT;     break;
        case ERROR_BAD_NET_NAME:            errno = ENOENT;     break;
        case ERROR_BAD_PATHNAME:            errno = ENOENT;     break;
        case ERROR_FILENAME_EXCED_RANGE:    errno = ENOENT;     break;
        case ERROR_BAD_FORMAT:              errno = ENOEXEC;    break;
        case ERROR_ARENA_TRASHED:           errno = ENOMEM;     break;
        case ERROR_NOT_ENOUGH_MEMORY:       errno = ENOMEM;     break;
        case ERROR_INVALID_BLOCK:           errno = ENOMEM;     break;
        case ERROR_NOT_ENOUGH_QUOTA:        errno = ENOMEM;     break;
        case ERROR_DISK_FULL:               errno = ENOSPC;     break;
        case ERROR_DIR_NOT_EMPTY:           errno = ENOTEMPTY;  break;
        case ERROR_BROKEN_PIPE:             errno = EPIPE;      break;
        case ERROR_NOT_SAME_DEVICE:         errno = EXDEV;      break;
        default:                            errno = EINVAL;     break;
    }
    return -1;
}

/**
 * Converts an NT status code to errno,
 * assigning it to errno.
 *
 * @returns -1
 * @param   rcNt        The NT status code.
 */
static int shfile_nt2errno(NTSTATUS rcNt)
{
    switch (rcNt)
    {
        default:                            errno = EINVAL; break;
    }
    return -1;
}

DWORD shfile_query_handle_access_mask(HANDLE h, PACCESS_MASK pMask)
{
    MY_OBJECT_BASIC_INFORMATION     BasicInfo;
    NTSTATUS                        rcNt;

    if (!g_pfnNtQueryObject)
        return ERROR_NOT_SUPPORTED;

    rcNt = g_pfnNtQueryObject(h, MY_ObjectBasicInformation, &BasicInfo, sizeof(BasicInfo), NULL);
    if (rcNt >= 0)
    {
        *pMask = BasicInfo.GrantedAccess;
        return NO_ERROR;
    }
    if (rcNt != STATUS_INVALID_HANDLE)
        return ERROR_GEN_FAILURE;
    return ERROR_INVALID_HANDLE;
}

# endif /* K_OS == K_OS_WINDOWS */

#endif /* SHFILE_IN_USE */

/**
 * Converts DOS slashes to UNIX slashes if necessary.
 *
 * @param   pszPath             The path to fix.
 */
static void shfile_fix_slashes(char *pszPath)
{
#if K_OS == K_OS_WINDOWS || K_OS == K_OS_OS2
    while ((pszPath = strchr(pszPath, '\\')))
        *pszPath++ = '/';
#else
    (void)pszPath;
#endif
}

/**
 * Initializes the global variables in this file.
 */
static void shfile_init_globals(void)
{
#if K_OS == K_OS_WINDOWS
    if (!g_shfile_globals_initialized)
    {
        HMODULE hNtDll = GetModuleHandle("NTDLL");
        g_pfnNtQueryObject                = (PFN_NtQueryObject)       GetProcAddress(hNtDll, "NtQueryObject");
        g_pfnNtQueryDirectoryFile         = (PFN_NtQueryDirectoryFile)GetProcAddress(hNtDll, "NtQueryDirectoryFile");
        g_pfnRtlUnicodeStringToAnsiString = (PFN_RtlUnicodeStringToAnsiString)GetProcAddress(hNtDll, "RtlUnicodeStringToAnsiString");
        if (   !g_pfnRtlUnicodeStringToAnsiString
            || !g_pfnNtQueryDirectoryFile)
        {
            /* fatal error */
        }
        g_shfile_globals_initialized = 1;
    }
#endif
}

/**
 * Initializes a file descriptor table.
 *
 * @returns 0 on success, -1 and errno on failure.
 * @param   pfdtab      The table to initialize.
 * @param   inherit     File descriptor table to inherit from. If not specified
 *                      we will inherit from the current process as it were.
 */
int shfile_init(shfdtab *pfdtab, shfdtab *inherit)
{
    int rc;

    shfile_init_globals();

    pfdtab->cwd  = NULL;
    pfdtab->size = 0;
    pfdtab->tab  = NULL;
    rc = shmtx_init(&pfdtab->mtx);
    if (!rc)
    {
#ifdef SHFILE_IN_USE
        /* Get CWD with unix slashes. */
        char buf[SHFILE_MAX_PATH];
        if (getcwd(buf, sizeof(buf)))
        {
            shfile_fix_slashes(buf);

            pfdtab->cwd = sh_strdup(NULL, buf);
            if (!inherit)
            {
# if K_OS == K_OS_WINDOWS
                static const struct
                {
                    DWORD dwStdHandle;
                    unsigned fFlags;
                } aStdHandles[3] =
                {
                    { STD_INPUT_HANDLE,   _O_RDONLY },
                    { STD_OUTPUT_HANDLE,  _O_WRONLY },
                    { STD_ERROR_HANDLE,   _O_WRONLY }
                };
                int             i;
                STARTUPINFO     Info;
                ACCESS_MASK     Mask;
                DWORD           dwErr;

                rc = 0;

                /* Try pick up the Visual C++ CRT file descriptor info. */
                __try {
                    GetStartupInfo(&Info);
                } __except (EXCEPTION_EXECUTE_HANDLER) {
                    memset(&Info, 0, sizeof(Info));
                }

                if (    Info.cbReserved2 > sizeof(int)
                    &&  (uintptr_t)Info.lpReserved2 >= 0x1000
                    &&  (i = *(int *)Info.lpReserved2) >= 1
                    &&  i <= 2048
                    &&  (   Info.cbReserved2 == i * 5 + 4
                         //|| Info.cbReserved2 == i * 5 + 1 - check the cygwin sources.
                         || Info.cbReserved2 == i * 9 + 4))
                {
                    uint8_t    *paf    = (uint8_t *)Info.lpReserved2 + sizeof(int);
                    int         dwPerH = 1 + (Info.cbReserved2 == i * 9 + 4);
                    DWORD      *ph     = (DWORD *)(paf + i) + dwPerH * i;
                    HANDLE      aStdHandles2[3];
                    int         j;

                    //if (Info.cbReserved2 == i * 5 + 1) - check the cygwin sources.
                    //    i--;

                    for (j = 0; j < 3; j++)
                        aStdHandles2[j] = GetStdHandle(aStdHandles[j].dwStdHandle);

                    while (i-- > 0)
                    {
                        ph -= dwPerH;

                        if (    (paf[i] & (FOPEN | FNOINHERIT)) == FOPEN
                            &&  *ph != (uint32_t)INVALID_HANDLE_VALUE)
                        {
                            HANDLE  h = (HANDLE)(intptr_t)*ph;
                            int     fd2;
                            int     fFlags;
                            int     fFlags2;

                            if (    h == aStdHandles2[j = 0]
                                ||  h == aStdHandles2[j = 1]
                                ||  h == aStdHandles2[j = 2])
                                fFlags = aStdHandles[j].fFlags;
                            else
                            {
                                dwErr = shfile_query_handle_access_mask(h, &Mask);
                                if (dwErr == ERROR_INVALID_HANDLE)
                                    continue;
                                else if (dwErr == NO_ERROR)
                                {
                                    fFlags = 0;
                                    if (    (Mask & (GENERIC_READ | FILE_READ_DATA))
                                        &&  (Mask & (GENERIC_WRITE | FILE_WRITE_DATA | FILE_APPEND_DATA)))
                                        fFlags |= O_RDWR;
                                    else if (Mask & (GENERIC_READ | FILE_READ_DATA))
                                        fFlags |= O_RDONLY;
                                    else if (Mask & (GENERIC_WRITE | FILE_WRITE_DATA | FILE_APPEND_DATA))
                                        fFlags |= O_WRONLY;
                                    else
                                        fFlags |= O_RDWR;
                                    if ((Mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) == FILE_APPEND_DATA)
                                        fFlags |= O_APPEND;
                                }
                                else
                                    fFlags = O_RDWR;
                            }

                            if (paf[i] & FPIPE)
                                fFlags2 = SHFILE_FLAGS_PIPE;
                            else if (paf[i] & FDEV)
                                fFlags2 = SHFILE_FLAGS_TTY;
                            else
                                fFlags2 = 0;

                            fd2 = shfile_insert(pfdtab, (intptr_t)h, fFlags, fFlags2, i, "shtab_init");
                            assert(fd2 == i); (void)fd2;
                            if (fd2 != i)
                                rc = -1;
                        }
                    }
                }

                /* Check the three standard handles. */
                for (i = 0; i < 3; i++)
                    if (    (unsigned)i >= pfdtab->size
                        ||  pfdtab->tab[i].fd == -1)
                    {
                        HANDLE hFile = GetStdHandle(aStdHandles[i].dwStdHandle);
                        if (hFile != INVALID_HANDLE_VALUE)
                        {
                            DWORD       dwType  = GetFileType(hFile);
                            unsigned    fFlags  = aStdHandles[i].fFlags;
                            unsigned    fFlags2;
                            int         fd2;
                            if (dwType == FILE_TYPE_CHAR)
                                fFlags2 = SHFILE_FLAGS_TTY;
                            else if (dwType == FILE_TYPE_PIPE)
                                fFlags2 = SHFILE_FLAGS_PIPE;
                            else
                                fFlags2 = SHFILE_FLAGS_FILE;
                            fd2 = shfile_insert(pfdtab, (intptr_t)hFile, fFlags, fFlags2, i, "shtab_init");
                            assert(fd2 == i); (void)fd2;
                            if (fd2 != i)
                                rc = -1;
                        }
                    }
# else
                /*
                 * Annoying...
                 */
                int fd;

                for (fd = 0; fd < 10; fd++)
                {
                    int oflags = fcntl(fd, F_GETFL, 0);
                    if (oflags != -1)
                    {
                        int cox = fcntl(fd, F_GETFD, 0);
                        struct stat st;
                        if (   cox != -1
                            && fstat(fd, &st) != -1)
                        {
                            int native;
                            int fd2;
                            int fFlags2 = 0;
                            if (cox & FD_CLOEXEC)
                                fFlags2 |= SHFILE_FLAGS_CLOSE_ON_EXEC;
                            if (S_ISREG(st.st_mode))
                                fFlags2 |= SHFILE_FLAGS_FILE;
                            else if (S_ISDIR(st.st_mode))
                                fFlags2 |= SHFILE_FLAGS_DIR;
                            else if (S_ISCHR(st.st_mode))
                                fFlags2 |= SHFILE_FLAGS_TTY;
                            else if (S_ISFIFO(st.st_mode))
                                fFlags2 |= SHFILE_FLAGS_PIPE;
                            else
                                fFlags2 |= SHFILE_FLAGS_TTY;

                            native = fcntl(fd, F_DUPFD, SHFILE_UNIX_MIN_FD);
                            if (native == -1)
                                native = fd;
                            fd2 = shfile_insert(pfdtab, native, oflags, fFlags2, fd, "shtab_init");
                            assert(fd2 == fd); (void)fd2;
                            if (fd2 != fd)
                                rc = -1;
                            if (native != fd)
                                close(fd);
                        }
                    }
                }

# endif
            }
            else
            {
                /** @todo */
                errno = ENOSYS;
                rc = -1;
            }
        }
        else
            rc = -1;
#endif
    }
    return rc;
}

#if K_OS == K_OS_WINDOWS && defined(SHFILE_IN_USE)

/**
 * Changes the inheritability of a file descriptro, taking console handles into
 * account.
 *
 * @note    This MAY change the native handle for the entry.
 *
 * @returns The native handle.
 * @param   pfd     The file descriptor to change.
 * @param   set     If set, make child processes inherit the handle, if clear
 *                  make them not inherit it.
 */
static HANDLE shfile_set_inherit_win(shfile *pfd, int set)
{
    HANDLE hFile = (HANDLE)pfd->native;
    if (!SetHandleInformation(hFile, HANDLE_FLAG_INHERIT, set ? HANDLE_FLAG_INHERIT : 0))
    {
        /* SetHandleInformation doesn't work for console handles,
           so we have to duplicate the handle to change the
           inheritability. */
        DWORD err = GetLastError();
        if (   err == ERROR_INVALID_PARAMETER
            && DuplicateHandle(GetCurrentProcess(),
                               hFile,
                               GetCurrentProcess(),
                               &hFile,
                               0,
                               set ? TRUE : FALSE /* bInheritHandle */,
                               DUPLICATE_SAME_ACCESS))
        {
            TRACE2((NULL, "shfile_set_inherit_win: %p -> %p (set=%d)\n", pfd->native, hFile, set));
            if (!CloseHandle((HANDLE)pfd->native))
                assert(0);
            pfd->native = (intptr_t)hFile;
        }
        else
        {
            err = GetLastError();
            assert(0);
            hFile = (HANDLE)pfd->native;
        }
    }
    return hFile;
}

/**
 * Helper for shfork.
 *
 * @param   pfdtab  The file descriptor table.
 * @param   set     Whether to make all handles inheritable (1) or
 *                  to restore them to the rigth state (0).
 * @param   hndls   Where to store the three standard handles.
 */
void shfile_fork_win(shfdtab *pfdtab, int set, intptr_t *hndls)
{
    shmtxtmp tmp;
    unsigned i;

    shmtx_enter(&pfdtab->mtx, &tmp);
    TRACE2((NULL, "shfile_fork_win: set=%d\n", set));

    i = pfdtab->size;
    while (i-- > 0)
    {
        if (pfdtab->tab[i].fd == i)
        {
            shfile_set_inherit_win(&pfdtab->tab[i], set);
            if (set)
                TRACE2((NULL, "  #%d: native=%#x oflags=%#x shflags=%#x\n",
                        i, pfdtab->tab[i].native, pfdtab->tab[i].oflags, pfdtab->tab[i].shflags));
        }
    }

    if (hndls)
    {
        for (i = 0; i < 3; i++)
        {
            if (    pfdtab->size > i
                &&  pfdtab->tab[i].fd == i)
                hndls[i] = pfdtab->tab[i].native;
            else
                hndls[i] = (intptr_t)INVALID_HANDLE_VALUE;
            TRACE2((NULL, "shfile_fork_win: i=%d size=%d fd=%d native=%d hndls[%d]=%p\n",
                    i, pfdtab->size, pfdtab->tab[i].fd, pfdtab->tab[i].native, i, hndls[i]));
        }
    }

    shmtx_leave(&pfdtab->mtx, &tmp);
}

/**
 * Helper for sh_execve.
 *
 * This is called before and after CreateProcess. On the first call it
 * will mark the non-close-on-exec handles as inheritable and produce
 * the startup info for the CRT. On the second call, after CreateProcess,
 * it will restore the handle inheritability properties.
 *
 * @returns Pointer to CRT data if prepare is 1, NULL if prepare is 0.
 * @param   pfdtab  The file descriptor table.
 * @param   prepare Which call, 1 if before and 0 if after.
 * @param   sizep   Where to store the size of the returned data.
 * @param   hndls   Where to store the three standard handles.
 */
void *shfile_exec_win(shfdtab *pfdtab, int prepare, unsigned short *sizep, intptr_t *hndls)
{
    void       *pvRet;
    shmtxtmp    tmp;
    unsigned    count;
    unsigned    i;

    shmtx_enter(&pfdtab->mtx, &tmp);
    TRACE2((NULL, "shfile_exec_win: prepare=%p\n", prepare));

    count  = pfdtab->size < (0x10000-4) / (1 + sizeof(HANDLE))
           ? pfdtab->size
           : (0x10000-4) / (1 + sizeof(HANDLE));
    while (count > 3 && pfdtab->tab[count - 1].fd == -1)
        count--;

    if (prepare)
    {
        size_t      cbData = sizeof(int) + count * (1 + sizeof(HANDLE));
        uint8_t    *pbData = sh_malloc(shthread_get_shell(), cbData);
        uint8_t    *paf = pbData + sizeof(int);
        HANDLE     *pah = (HANDLE *)(paf + count);

        *(int *)pbData = count;

        i = count;
        while (i-- > 0)
        {
            if (    pfdtab->tab[i].fd == i
                &&  !(pfdtab->tab[i].shflags & SHFILE_FLAGS_CLOSE_ON_EXEC))
            {
                HANDLE hFile = shfile_set_inherit_win(&pfdtab->tab[i], 1);
                TRACE2((NULL, "  #%d: native=%#x oflags=%#x shflags=%#x\n",
                        i, hFile, pfdtab->tab[i].oflags, pfdtab->tab[i].shflags));
                paf[i] = FOPEN;
                if (pfdtab->tab[i].oflags & _O_APPEND)
                    paf[i] |= FAPPEND;
                if (pfdtab->tab[i].oflags & _O_TEXT)
                    paf[i] |= FTEXT;
                switch (pfdtab->tab[i].shflags & SHFILE_FLAGS_TYPE_MASK)
                {
                    case SHFILE_FLAGS_TTY:  paf[i] |= FDEV; break;
                    case SHFILE_FLAGS_PIPE: paf[i] |= FPIPE; break;
                }
                pah[i] = hFile;
            }
            else
            {
                paf[i] = 0;
                pah[i] = INVALID_HANDLE_VALUE;
            }
        }

        for (i = 0; i < 3; i++)
        {
            if (    i < count
                &&  pfdtab->tab[i].fd == i)
                hndls[i] = pfdtab->tab[i].native;
            else
                hndls[i] = (intptr_t)INVALID_HANDLE_VALUE;
            TRACE2((NULL, "shfile_exec_win: i=%d count=%d fd=%d native=%d hndls[%d]=\n",
                    i, count, pfdtab->tab[i].fd, pfdtab->tab[i].native, i, hndls[i]));
        }

        *sizep = (unsigned short)cbData;
        pvRet = pbData;
    }
    else
    {
        assert(!hndls);
        assert(!sizep);
        i = count;
        while (i-- > 0)
        {
            if (    pfdtab->tab[i].fd == i
                &&  !(pfdtab->tab[i].shflags & SHFILE_FLAGS_CLOSE_ON_EXEC))
                shfile_set_inherit_win(&pfdtab->tab[i], 0);
        }
        pvRet = NULL;
    }

    shmtx_leave(&pfdtab->mtx, &tmp);
    return pvRet;
}

#endif /* K_OS_WINDOWS */

#if K_OS != K_OS_WINDOWS
/**
 * Prepare file handles for inherting before a execve call.
 *
 * This is only used in the normal mode, so we've forked and need not worry
 * about cleaning anything up after us.  Nor do we need think about locking.
 *
 * @returns 0 on success, -1 on failure.
 */
int shfile_exec_unix(shfdtab *pfdtab)
{
    int rc = 0;
# ifdef SHFILE_IN_USE
    unsigned fd;

    for (fd = 0; fd < pfdtab->size; fd++)
    {
        if (   pfdtab->tab[fd].fd != -1
            && !(pfdtab->tab[fd].shflags & SHFILE_FLAGS_CLOSE_ON_EXEC) )
        {
            TRACE2((NULL, "shfile_exec_unix: %d => %d\n", pfdtab->tab[fd].native, fd));
            if (dup2(pfdtab->tab[fd].native, fd) < 0)
            {
                /* fatal_error(NULL, "shfile_exec_unix: failed to move %d to %d", pfdtab->tab[fd].fd, fd); */
                rc = -1;
            }
        }
    }
# endif
    return rc;
}
#endif /* !K_OS_WINDOWS */

/**
 * open().
 */
int shfile_open(shfdtab *pfdtab, const char *name, unsigned flags, mode_t mode)
{
    int fd;
#ifdef SHFILE_IN_USE
    char    absname[SHFILE_MAX_PATH];
# if K_OS == K_OS_WINDOWS
    HANDLE  hFile;
    DWORD   dwDesiredAccess;
    DWORD   dwShareMode;
    DWORD   dwCreationDisposition;
    DWORD   dwFlagsAndAttributes;
    SECURITY_ATTRIBUTES SecurityAttributes;

# ifndef _O_ACCMODE
#  define _O_ACCMODE	(_O_RDONLY|_O_WRONLY|_O_RDWR)
# endif
    switch (flags & (_O_ACCMODE | _O_APPEND))
    {
        case _O_RDONLY:             dwDesiredAccess = GENERIC_READ; break;
        case _O_RDONLY | _O_APPEND: dwDesiredAccess = GENERIC_READ; break;
        case _O_WRONLY:             dwDesiredAccess = GENERIC_WRITE; break;
        case _O_WRONLY | _O_APPEND: dwDesiredAccess = (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA); break;
        case _O_RDWR:               dwDesiredAccess = GENERIC_READ | GENERIC_WRITE; break;
        case _O_RDWR   | _O_APPEND: dwDesiredAccess = GENERIC_READ | (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA); break;

        default:
            RETURN_ERROR(-1, EINVAL, "invalid mode");
    }

    dwShareMode = FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE;

    SecurityAttributes.nLength = sizeof(SecurityAttributes);
    SecurityAttributes.lpSecurityDescriptor = NULL;
    SecurityAttributes.bInheritHandle = FALSE;

    if (flags & _O_CREAT)
    {
        if ((flags & (_O_EXCL | _O_TRUNC)) == (_O_EXCL | _O_TRUNC))
            RETURN_ERROR(-1, EINVAL, "_O_EXCL | _O_TRUNC");

        if (flags & _O_TRUNC)
            dwCreationDisposition = CREATE_ALWAYS; /* not 100%, but close enough */
        else if (flags & _O_EXCL)
            dwCreationDisposition = CREATE_NEW;
        else
            dwCreationDisposition = OPEN_ALWAYS;
    }
    else if (flags & _O_TRUNC)
        dwCreationDisposition = TRUNCATE_EXISTING;
    else
        dwCreationDisposition = OPEN_EXISTING;

    if (!(flags & _O_CREAT) || (mode & 0222))
        dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
    else
        dwFlagsAndAttributes = FILE_ATTRIBUTE_READONLY;

    fd = shfile_make_path(pfdtab, name, &absname[0]);
    if (!fd)
    {
        SetLastError(0);
        hFile = CreateFileA(absname,
                            dwDesiredAccess,
                            dwShareMode,
                            &SecurityAttributes,
                            dwCreationDisposition,
                            dwFlagsAndAttributes,
                            NULL /* hTemplateFile */);
        if (hFile != INVALID_HANDLE_VALUE)
            fd = shfile_insert(pfdtab, (intptr_t)hFile, flags, 0, -1, "shfile_open");
        else
            fd = shfile_dos2errno(GetLastError());
    }

# else  /* K_OS != K_OS_WINDOWS */
    fd = shfile_make_path(pfdtab, name, &absname[0]);
    if (!fd)
    {
        fd = open(absname, flags, mode);
        if (fd != -1)
            fd = shfile_copy_insert_and_close(pfdtab, &fd, flags, 0, -1, "shfile_open");
    }

# endif /* K_OS != K_OS_WINDOWS */

#else
    fd = open(name, flags, mode);
#endif

    TRACE2((NULL, "shfile_open(%p:{%s}, %#x, 0%o) -> %d [%d]\n", name, name, flags, mode, fd, errno));
    return fd;
}

int shfile_pipe(shfdtab *pfdtab, int fds[2])
{
    int rc = -1;
#ifdef SHFILE_IN_USE
# if K_OS == K_OS_WINDOWS
    HANDLE hRead  = INVALID_HANDLE_VALUE;
    HANDLE hWrite = INVALID_HANDLE_VALUE;
    SECURITY_ATTRIBUTES SecurityAttributes;

    SecurityAttributes.nLength = sizeof(SecurityAttributes);
    SecurityAttributes.lpSecurityDescriptor = NULL;
    SecurityAttributes.bInheritHandle = FALSE;

    fds[1] = fds[0] = -1;
    if (CreatePipe(&hRead, &hWrite, &SecurityAttributes, 4096))
    {
        fds[0] = shfile_insert(pfdtab, (intptr_t)hRead, O_RDONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe");
        if (fds[0] != -1)
        {
            fds[1] = shfile_insert(pfdtab, (intptr_t)hWrite, O_WRONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe");
            if (fds[1] != -1)
                rc = 0;
        }

# else
    int native_fds[2];

    fds[1] = fds[0] = -1;
    if (!pipe(native_fds))
    {
        fds[0] = shfile_copy_insert_and_close(pfdtab, &native_fds[0], O_RDONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe");
        if (fds[0] != -1)
        {
            fds[1] = shfile_copy_insert_and_close(pfdtab, &native_fds[1], O_WRONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe");
            if (fds[1] != -1)
                rc = 0;
        }
# endif
        if (fds[1] == -1)
        {
            int s = errno;
            if (fds[0] != -1)
            {
                shmtxtmp tmp;
                shmtx_enter(&pfdtab->mtx, &tmp);
                rc = fds[0];
                pfdtab->tab[rc].fd = -1;
                pfdtab->tab[rc].oflags = 0;
                pfdtab->tab[rc].shflags = 0;
                pfdtab->tab[rc].native = -1;
                shmtx_leave(&pfdtab->mtx, &tmp);
            }

# if K_OS == K_OS_WINDOWS
            CloseHandle(hRead);
            CloseHandle(hWrite);
# else
            close(native_fds[0]);
            close(native_fds[1]);
# endif
            fds[0] = fds[1] = -1;
            errno = s;
            rc = -1;
        }
    }
    else
    {
# if K_OS == K_OS_WINDOWS
        errno = shfile_dos2errno(GetLastError());
# endif
        rc = -1;
    }

#else
    rc = pipe(fds);
#endif

    TRACE2((NULL, "shfile_pipe() -> %d{%d,%d} [%d]\n", rc, fds[0], fds[1], errno));
    return rc;
}

/**
 * dup().
 */
int shfile_dup(shfdtab *pfdtab, int fd)
{
    return shfile_fcntl(pfdtab,fd, F_DUPFD, 0);
}

/**
 * Move the file descriptor, closing any existing descriptor at @a fdto.
 *
 * @returns fdto on success, -1 and errno on failure.
 * @param   pfdtab          The file descriptor table.
 * @param   fdfrom          The descriptor to move.
 * @param   fdto            Where to move it.
 */
int shfile_movefd(shfdtab *pfdtab, int fdfrom, int fdto)
{
#ifdef SHFILE_IN_USE
    int         rc;
    shmtxtmp    tmp;
    shfile     *file = shfile_get(pfdtab, fdfrom, &tmp);
    if (file)
    {
        /* prepare the new entry */
        if (fdto >= (int)pfdtab->size)
            shfile_grow_tab_locked(pfdtab, fdto);
        if (fdto < (int)pfdtab->size)
        {
            if (pfdtab->tab[fdto].fd != -1)
                shfile_native_close(pfdtab->tab[fdto].native, pfdtab->tab[fdto].oflags);

            /* setup the target. */
            pfdtab->tab[fdto].fd      = fdto;
            pfdtab->tab[fdto].oflags  = file->oflags;
            pfdtab->tab[fdto].shflags = file->shflags;
            pfdtab->tab[fdto].native  = file->native;

            /* close the source. */
            file->fd        = -1;
            file->oflags    = 0;
            file->shflags   = 0;
            file->native    = -1;

            rc = fdto;
        }
        else
        {
            errno = EMFILE;
            rc = -1;
        }

        shfile_put(pfdtab, file, &tmp);
    }
    else
        rc = -1;
    return rc;

#else
    int fdnew = dup2(fdfrom, fdto);
    if (fdnew >= 0)
        close(fdfrom);
    return fdnew;
#endif
}

/**
 * Move the file descriptor to somewhere at @a fdMin or above.
 *
 * @returns the new file descriptor success, -1 and errno on failure.
 * @param   pfdtab          The file descriptor table.
 * @param   fdfrom          The descriptor to move.
 * @param   fdMin           The minimum descriptor.
 */
int shfile_movefd_above(shfdtab *pfdtab, int fdfrom, int fdMin)
{
#ifdef SHFILE_IN_USE
    int         fdto;
    shmtxtmp    tmp;
    shfile     *file = shfile_get(pfdtab, fdfrom, &tmp);
    if (file)
    {
        /* find a new place */
        int i;
        fdto = -1;
        for (i = fdMin; (unsigned)i < pfdtab->size; i++)
            if (pfdtab->tab[i].fd == -1)
            {
                fdto = i;
                break;
            }
        if (fdto == -1)
            fdto = shfile_grow_tab_locked(pfdtab, fdMin);
        if (fdto != -1)
        {
            /* setup the target. */
            pfdtab->tab[fdto].fd      = fdto;
            pfdtab->tab[fdto].oflags  = file->oflags;
            pfdtab->tab[fdto].shflags = file->shflags;
            pfdtab->tab[fdto].native  = file->native;

            /* close the source. */
            file->fd        = -1;
            file->oflags    = 0;
            file->shflags   = 0;
            file->native    = -1;
        }
        else
        {
            errno = EMFILE;
            fdto = -1;
        }

        shfile_put(pfdtab, file, &tmp);
    }
    else
        fdto = -1;
    return fdto;

#else
    int fdnew = fcntl(fdfrom, F_DUPFD, fdMin);
    if (fdnew >= 0)
        close(fdfrom);
    return fdnew;
#endif
}

/**
 * close().
 */
int shfile_close(shfdtab *pfdtab, unsigned fd)
{
    int         rc;
#ifdef SHFILE_IN_USE
    shmtxtmp    tmp;
    shfile     *file = shfile_get(pfdtab, fd, &tmp);
    if (file)
    {
        shfile_native_close(file->native, file->oflags);

        file->fd = -1;
        file->oflags = 0;
        file->shflags = 0;
        file->native = -1;

        shfile_put(pfdtab, file, &tmp);
        rc = 0;
    }
    else
        rc = -1;

#else
    rc = close(fd);
#endif

    TRACE2((NULL, "shfile_close(%d) -> %d [%d]\n", fd, rc, errno));
    return rc;
}

/**
 * read().
 */
long shfile_read(shfdtab *pfdtab, int fd, void *buf, size_t len)
{
    long        rc;
#ifdef SHFILE_IN_USE
    shmtxtmp    tmp;
    shfile     *file = shfile_get(pfdtab, fd, &tmp);
    if (file)
    {
# if K_OS == K_OS_WINDOWS
        DWORD dwRead = 0;
        if (ReadFile((HANDLE)file->native, buf, (DWORD)len, &dwRead, NULL))
            rc = dwRead;
        else
            rc = shfile_dos2errno(GetLastError());
# else
        rc = read(file->native, buf, len);
# endif

        shfile_put(pfdtab, file, &tmp);
    }
    else
        rc = -1;

#else
    rc = read(fd, buf, len);
#endif
    return rc;
}

/**
 * write().
 */
long shfile_write(shfdtab *pfdtab, int fd, const void *buf, size_t len)
{
    long        rc;
#ifdef SHFILE_IN_USE
    shmtxtmp    tmp;
    shfile     *file = shfile_get(pfdtab, fd, &tmp);
    if (file)
    {
# if K_OS == K_OS_WINDOWS
        DWORD dwWritten = 0;
        if (WriteFile((HANDLE)file->native, buf, (DWORD)len, &dwWritten, NULL))
            rc = dwWritten;
        else
            rc = shfile_dos2errno(GetLastError());
# else
        rc = write(file->native, buf, len);
# endif

        shfile_put(pfdtab, file, &tmp);
    }
    else
        rc = -1;

# ifdef DEBUG
    if (fd != shthread_get_shell()->tracefd)
        TRACE2((NULL, "shfile_write(%d,,%d) -> %d [%d]\n", fd, len, rc, errno));
# endif

#else
    if (fd != shthread_get_shell()->tracefd)
    {
        int iSavedErrno = errno;
        struct stat s;
        int x;
        x = fstat(fd, &s);
        TRACE2((NULL, "shfile_write(%d) - %lu bytes (%d) - pos %lu - before; %o\n",
                fd, (long)s.st_size, x, (long)lseek(fd, 0, SEEK_CUR), s.st_mode ));
        errno = iSavedErrno;
    }

    rc = write(fd, buf, len);
#endif
    return rc;
}

/**
 * lseek().
 */
long shfile_lseek(shfdtab *pfdtab, int fd, long off, int whench)
{
    long        rc;
#ifdef SHFILE_IN_USE
    shmtxtmp    tmp;
    shfile     *file = shfile_get(pfdtab, fd, &tmp);
    if (file)
    {
# if K_OS == K_OS_WINDOWS
        assert(SEEK_SET == FILE_BEGIN);
        assert(SEEK_CUR == FILE_CURRENT);
        assert(SEEK_END == FILE_END);
        rc = SetFilePointer((HANDLE)file->native, off, NULL, whench);
        if (rc == INVALID_SET_FILE_POINTER)
            rc = shfile_dos2errno(GetLastError());
# else
        rc = lseek(file->native, off, whench);
# endif

        shfile_put(pfdtab, file, &tmp);
    }
    else
        rc = -1;

#else
    rc = lseek(fd, off, whench);
#endif

    return rc;
}

int shfile_fcntl(shfdtab *pfdtab, int fd, int cmd, int arg)
{
    int rc;
#ifdef SHFILE_IN_USE
    shmtxtmp    tmp;
    shfile     *file = shfile_get(pfdtab, fd, &tmp);
    if (file)
    {
        switch (cmd)
        {
            case F_GETFL:
                rc = file->oflags;
                break;

            case F_SETFL:
            {
                unsigned mask = O_NONBLOCK | O_APPEND | O_BINARY | O_TEXT;
# ifdef O_DIRECT
                mask |= O_DIRECT;
# endif
# ifdef O_ASYNC
                mask |= O_ASYNC;
# endif
# ifdef O_SYNC
                mask |= O_SYNC;
# endif
                if ((file->oflags & mask) == (arg & mask))
                    rc = 0;
                else
                {
# if K_OS == K_OS_WINDOWS
                    assert(0);
                    errno = EINVAL;
                    rc = -1;
# else
                    rc = fcntl(file->native, F_SETFL, arg);
                    if (rc != -1)
                        file->oflags = (file->oflags & ~mask) | (arg & mask);
# endif
                }
                break;
            }

            case F_DUPFD:
            {
# if K_OS == K_OS_WINDOWS
                HANDLE hNew = INVALID_HANDLE_VALUE;
                if (DuplicateHandle(GetCurrentProcess(),
                                    (HANDLE)file->native,
                                    GetCurrentProcess(),
                                    &hNew,
                                    0,
                                    FALSE /* bInheritHandle */,
                                    DUPLICATE_SAME_ACCESS))
                    rc = shfile_insert(pfdtab, (intptr_t)hNew, file->oflags, file->shflags, arg, "shfile_fcntl");
                else
                    rc = shfile_dos2errno(GetLastError());
# else
                int nativeNew = fcntl(file->native, F_DUPFD, SHFILE_UNIX_MIN_FD);
                if (nativeNew != -1)
                    rc = shfile_insert(pfdtab, nativeNew, file->oflags, file->shflags, arg, "shfile_fcntl");
                else
                    rc = -1;
# endif
                break;
            }

            default:
                errno = -EINVAL;
                rc = -1;
                break;
        }

        shfile_put(pfdtab, file, &tmp);
    }
    else
        rc = -1;

#else
    rc = fcntl(fd, cmd, arg);
#endif

    switch (cmd)
    {
        case F_GETFL: TRACE2((NULL, "shfile_fcntl(%d,F_GETFL,ignored=%d) -> %d [%d]\n", fd, arg, rc, errno));  break;
        case F_SETFL: TRACE2((NULL, "shfile_fcntl(%d,F_SETFL,newflags=%#x) -> %d [%d]\n", fd, arg, rc, errno)); break;
        case F_DUPFD: TRACE2((NULL, "shfile_fcntl(%d,F_DUPFD,minfd=%d) -> %d [%d]\n", fd, arg, rc, errno)); break;
        default:  TRACE2((NULL, "shfile_fcntl(%d,%d,%d) -> %d [%d]\n", fd, cmd, arg, rc, errno)); break;
    }
    return rc;
}

int shfile_stat(shfdtab *pfdtab, const char *path, struct stat *pst)
{
#ifdef SHFILE_IN_USE
    char    abspath[SHFILE_MAX_PATH];
    int     rc;
    rc = shfile_make_path(pfdtab, path, &abspath[0]);
    if (!rc)
    {
# if K_OS == K_OS_WINDOWS
        int dir_slash = shfile_trailing_slash_hack(abspath);
        rc = stat(abspath, pst); /** @todo re-implement stat. */
        if (!rc && dir_slash && !S_ISDIR(pst->st_mode))
        {
            rc = -1;
            errno = ENOTDIR;
        }
# else
        rc = stat(abspath, pst);
# endif
    }
    TRACE2((NULL, "shfile_stat(,%s,) -> %d [%d]\n", path, rc, errno));
    return rc;
#else
    return stat(path, pst);
#endif
}

int shfile_lstat(shfdtab *pfdtab, const char *path, struct stat *pst)
{
    int     rc;
#ifdef SHFILE_IN_USE
    char    abspath[SHFILE_MAX_PATH];

    rc = shfile_make_path(pfdtab, path, &abspath[0]);
    if (!rc)
    {
# if K_OS == K_OS_WINDOWS
        int dir_slash = shfile_trailing_slash_hack(abspath);
        rc = stat(abspath, pst); /** @todo re-implement stat. */
        if (!rc && dir_slash && !S_ISDIR(pst->st_mode))
        {
            rc = -1;
            errno = ENOTDIR;
        }
# else
        rc = lstat(abspath, pst);
# endif
    }
#else
    rc = stat(path, pst);
#endif
    TRACE2((NULL, "shfile_stat(,%s,) -> %d [%d]\n", path, rc, errno));
    return rc;
}

/**
 * chdir().
 */
int shfile_chdir(shfdtab *pfdtab, const char *path)
{
    int         rc;
#ifdef SHFILE_IN_USE
    shinstance *psh = shthread_get_shell();
    char        abspath[SHFILE_MAX_PATH];

    rc = shfile_make_path(pfdtab, path, &abspath[0]);
    if (!rc)
    {
        char *abspath_copy = sh_strdup(psh, abspath);
        char *free_me = abspath_copy;
        rc = chdir(abspath);
        if (!rc)
        {
            shmtxtmp    tmp;
            shmtx_enter(&pfdtab->mtx, &tmp);

            shfile_fix_slashes(abspath_copy);
            free_me = pfdtab->cwd;
            pfdtab->cwd = abspath_copy;

            shmtx_leave(&pfdtab->mtx, &tmp);
        }
        sh_free(psh, free_me);
    }
    else
        rc = -1;
#else
    rc = chdir(path);
#endif

    TRACE2((NULL, "shfile_chdir(,%s) -> %d [%d]\n", path, rc, errno));
    return rc;
}

/**
 * getcwd().
 */
char *shfile_getcwd(shfdtab *pfdtab, char *buf, int size)
{
    char       *ret;
#ifdef SHFILE_IN_USE

    ret = NULL;
    if (buf && !size)
        errno = -EINVAL;
    else
    {
        size_t      cwd_size;
        shmtxtmp    tmp;
        shmtx_enter(&pfdtab->mtx, &tmp);

        cwd_size = strlen(pfdtab->cwd) + 1;
        if (buf)
        {
            if (cwd_size <= (size_t)size)
                ret = memcpy(buf, pfdtab->cwd, cwd_size);
            else
                errno = ERANGE;
        }
        else
        {
            if ((size_t)size < cwd_size)
                size = (int)cwd_size;
            ret = sh_malloc(shthread_get_shell(), size);
            if (ret)
                ret = memcpy(ret, pfdtab->cwd, cwd_size);
            else
                errno = ENOMEM;
        }

        shmtx_leave(&pfdtab->mtx, &tmp);
    }
#else
    ret = getcwd(buf, size);
#endif

    TRACE2((NULL, "shfile_getcwd(,%p,%d) -> %s [%d]\n", buf, size, ret, errno));
    return ret;
}

/**
 * access().
 */
int shfile_access(shfdtab *pfdtab, const char *path, int type)
{
    int         rc;
#ifdef SHFILE_IN_USE
    char        abspath[SHFILE_MAX_PATH];

    rc = shfile_make_path(pfdtab, path, &abspath[0]);
    if (!rc)
    {
# ifdef _MSC_VER
        if (type & X_OK)
            type = (type & ~X_OK) | R_OK;
# endif
        rc = access(abspath, type);
    }
#else
# ifdef _MSC_VER
    if (type & X_OK)
        type = (type & ~X_OK) | R_OK;
# endif
    rc = access(path, type);
#endif

    TRACE2((NULL, "shfile_access(,%s,%#x) -> %d [%d]\n", path, type, rc, errno));
    return rc;
}

/**
 * isatty()
 */
int shfile_isatty(shfdtab *pfdtab, int fd)
{
    int         rc;
#ifdef SHFILE_IN_USE
    shmtxtmp    tmp;
    shfile     *file = shfile_get(pfdtab, fd, &tmp);
    if (file)
    {
# if K_OS == K_OS_WINDOWS
        rc = (file->shflags & SHFILE_FLAGS_TYPE_MASK) == SHFILE_FLAGS_TTY;
# else
        rc = isatty(file->native);
# endif
        shfile_put(pfdtab, file, &tmp);
    }
    else
        rc = 0;
#else
    rc = isatty(fd);
#endif

    TRACE2((NULL, "isatty(%d) -> %d [%d]\n", fd, rc, errno));
    return rc;
}

/**
 * fcntl F_SETFD / FD_CLOEXEC.
 */
int shfile_cloexec(shfdtab *pfdtab, int fd, int closeit)
{
    int         rc;
#ifdef SHFILE_IN_USE
    shmtxtmp    tmp;
    shfile     *file = shfile_get(pfdtab, fd, &tmp);
    if (file)
    {
        if (closeit)
            file->shflags |= SHFILE_FLAGS_CLOSE_ON_EXEC;
        else
            file->shflags &= ~SHFILE_FLAGS_CLOSE_ON_EXEC;
        shfile_put(pfdtab, file, &tmp);
        rc = 0;
    }
    else
        rc = -1;
#else
    rc = fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0)
                          | (closeit ? FD_CLOEXEC : 0));
#endif

    TRACE2((NULL, "shfile_cloexec(%d, %d) -> %d [%d]\n", fd, closeit, rc, errno));
    return rc;
}


int shfile_ioctl(shfdtab *pfdtab, int fd, unsigned long request, void *buf)
{
    int         rc;
#ifdef SHFILE_IN_USE
    shmtxtmp    tmp;
    shfile     *file = shfile_get(pfdtab, fd, &tmp);
    if (file)
    {
# if K_OS == K_OS_WINDOWS
        rc = -1;
        errno = ENOSYS;
# else
        rc = ioctl(file->native, request, buf);
# endif
        shfile_put(pfdtab, file, &tmp);
    }
    else
        rc = -1;
#else
    rc = ioctl(fd, request, buf);
#endif

    TRACE2((NULL, "ioctl(%d, %#x, %p) -> %d\n", fd, request, buf, rc));
    return rc;
}


mode_t shfile_get_umask(shfdtab *pfdtab)
{
    /** @todo */
    return 022;
}

void shfile_set_umask(shfdtab *pfdtab, mode_t mask)
{
    /** @todo */
    (void)mask;
}



shdir *shfile_opendir(shfdtab *pfdtab, const char *dir)
{
#if defined(SHFILE_IN_USE) && K_OS == K_OS_WINDOWS
    shdir  *pdir = NULL;

    TRACE2((NULL, "shfile_opendir: dir='%s'\n", dir));
    shfile_init_globals();
    if (g_pfnNtQueryDirectoryFile)
    {
        char abspath[SHFILE_MAX_PATH];
        if (shfile_make_path(pfdtab, dir, &abspath[0]) == 0)
        {
            HANDLE              hFile;
            SECURITY_ATTRIBUTES SecurityAttributes;

            SecurityAttributes.nLength = sizeof(SecurityAttributes);
            SecurityAttributes.lpSecurityDescriptor = NULL;
            SecurityAttributes.bInheritHandle = FALSE;

            hFile = CreateFileA(abspath,
                                GENERIC_READ,
                                FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
                                &SecurityAttributes,
                                OPEN_EXISTING,
                                FILE_ATTRIBUTE_DIRECTORY | FILE_FLAG_BACKUP_SEMANTICS,
                                NULL /* hTemplateFile */);
            if (hFile != INVALID_HANDLE_VALUE)
            {
                pdir = (shdir *)sh_malloc(shthread_get_shell(), sizeof(*pdir));
                if (pdir)
                {
                    pdir->pfdtab = pfdtab;
                    pdir->native = hFile;
                    pdir->off    = ~(size_t)0;
                }
                else
                    CloseHandle(hFile);
            }
            else
            {
                errno = shfile_dos2errno(GetLastError());
                TRACE2((NULL, "shfile_opendir: CreateFileA(%s) -> %d/%d\n", abspath, GetLastError(), errno));
            }
        }
    }
    else
        errno = ENOSYS;
    return pdir;
#else
    TRACE2((NULL, "shfile_opendir: dir='%s'\n", dir));
    return (shdir *)opendir(dir);
#endif
}

shdirent *shfile_readdir(struct shdir *pdir)
{
#if defined(SHFILE_IN_USE) && K_OS == K_OS_WINDOWS
    if (pdir)
    {
        NTSTATUS rcNt;

        if (   pdir->off == ~(size_t)0
            || pdir->off + sizeof(MY_FILE_NAMES_INFORMATION) >= pdir->cb)
        {
            MY_IO_STATUS_BLOCK Ios;

            memset(&Ios, 0, sizeof(Ios));
            rcNt = g_pfnNtQueryDirectoryFile(pdir->native,
                                             NULL /*Event*/,
                                             NULL /*ApcRoutine*/,
                                             NULL /*ApcContext*/,
                                             &Ios,
                                             &pdir->buf[0],
                                             sizeof(pdir->buf),
                                             MY_FileNamesInformation,
                                             FALSE /*ReturnSingleEntry*/,
                                             NULL /*FileName*/,
                                             pdir->off == ~(size_t)0 /*RestartScan*/);
            if (rcNt >= 0 && rcNt != STATUS_PENDING)
            {
                pdir->cb  = Ios.Information;
                pdir->off = 0;
            }
            else if (rcNt == STATUS_NO_MORE_FILES)
                errno = 0; /* wrong? */
            else
                shfile_nt2errno(rcNt);
        }

        if (   pdir->off != ~(size_t)0
            && pdir->off + sizeof(MY_FILE_NAMES_INFORMATION) <= pdir->cb)
        {
            PMY_FILE_NAMES_INFORMATION  pcur = (PMY_FILE_NAMES_INFORMATION)&pdir->buf[pdir->off];
            ANSI_STRING                 astr;
            UNICODE_STRING              ustr;

            astr.Length = astr.MaximumLength = sizeof(pdir->ent.name);
            astr.Buffer = &pdir->ent.name[0];

            ustr.Length = ustr.MaximumLength = pcur->FileNameLength < ~(USHORT)0 ? (USHORT)pcur->FileNameLength : ~(USHORT)0;
            ustr.Buffer = &pcur->FileName[0];

            rcNt = g_pfnRtlUnicodeStringToAnsiString(&astr, &ustr, 0/*AllocateDestinationString*/);
            if (rcNt < 0)
                sprintf(pdir->ent.name, "conversion-failed-%08x-rcNt=%08x-len=%u",
                        pcur->FileIndex, rcNt, pcur->FileNameLength);
            if (pcur->NextEntryOffset)
                pdir->off += pcur->NextEntryOffset;
            else
                pdir->off = pdir->cb;
            return &pdir->ent;
        }
    }
    else
        errno = EINVAL;
    return NULL;
#else
    struct dirent *pde = readdir((DIR *)pdir);
    return pde ? (shdirent *)&pde->d_name[0] : NULL;
#endif
}

void shfile_closedir(struct shdir *pdir)
{
#if defined(SHFILE_IN_USE) && K_OS == K_OS_WINDOWS
    if (pdir)
    {
        CloseHandle(pdir->native);
        pdir->pfdtab = NULL;
        pdir->native = INVALID_HANDLE_VALUE;
        sh_free(shthread_get_shell(), pdir);
    }
    else
        errno = EINVAL;
#else
    closedir((DIR *)pdir);
#endif
}