aboutsummaryrefslogtreecommitdiff
path: root/libbutl/filesystem.cxx
blob: 9769124c30a14bc84947020519f7245d3b8e5be7 (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
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
// file      : libbutl/filesystem.cxx -*- C++ -*-
// copyright : Copyright (c) 2014-2019 Code Synthesis Ltd
// license   : MIT; see accompanying LICENSE file

#ifndef __cpp_modules_ts
#include <libbutl/filesystem.mxx>
#endif

#include <errno.h> // errno, E*

#ifndef _WIN32
#  include <stdio.h>     // rename()
#  include <utime.h>     // utime()
#  include <dirent.h>    // struct dirent, *dir()
#  include <unistd.h>    // symlink(), link(), stat(), rmdir(), unlink()
#  include <sys/time.h>  // utimes()
#  include <sys/types.h> // stat
#  include <sys/stat.h>  // stat(), lstat(), S_I*, mkdir(), chmod()
#else
#  include <libbutl/win32-utility.hxx>

#  include <io.h>        // _find*(), _unlink(), _chmod()
#  include <direct.h>    // _mkdir(), _rmdir()
#  include <winioctl.h>  // FSCTL_SET_REPARSE_POINT
#  include <sys/types.h> // _stat
#  include <sys/stat.h>  // _stat(), S_I*
#  include <sys/utime.h> // _utime()

#  include <cwchar> // mbsrtowcs(), mbstate_t

#  ifdef _MSC_VER // Unlikely to be fixed in newer versions.
#    define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
#    define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
#  endif
#endif

#include <cassert>

#ifndef __cpp_lib_modules_ts
#include <string>
#include <cstddef>
#include <cstdint>
#include <utility>
#include <iterator>
#include <functional>

#include <vector>
#include <memory>       // unique_ptr
#include <algorithm>    // find(), copy()
#include <system_error>
#endif

// Other includes.

#ifdef __cpp_modules_ts
module butl.filesystem;

// Only imports additional to interface.
#ifdef __clang__
#ifdef __cpp_lib_modules_ts
import std.core;
#endif
import butl.path;
import butl.timestamp;
#endif

import butl.utility;      // throw_generic_error(), lcase()[_WIN32]
import butl.fdstream;
import butl.small_vector;
#else
#include <libbutl/path.mxx>
#include <libbutl/utility.mxx>
#include <libbutl/fdstream.mxx>
#include <libbutl/small-vector.mxx>
#endif

using namespace std;

namespace butl
{
  bool
  file_exists (const char* p, bool fl, bool ie)
  {
    auto pe (path_entry (p, fl, ie));
    return pe.first && (pe.second.type == entry_type::regular ||
                        (!fl && pe.second.type == entry_type::symlink));
  }

  bool
  entry_exists (const char* p, bool fl, bool ie)
  {
    return path_entry (p, fl, ie).first;
  }

  bool
  dir_exists (const char* p, bool ie)
  {
    auto pe (path_entry (p, true, ie));
    return pe.first && pe.second.type == entry_type::directory;
  }

#ifndef _WIN32

  pair<bool, entry_stat>
  path_entry (const char* p, bool fl, bool ie)
  {
    struct stat s;
    if ((fl ? stat (p, &s) : lstat (p, &s)) != 0)
    {
      if (errno == ENOENT || errno == ENOTDIR || ie)
        return make_pair (false, entry_stat {entry_type::unknown, 0});
      else
        throw_generic_error (errno);
    }

    auto m (s.st_mode);
    entry_type t (entry_type::unknown);

    if (S_ISREG (m))
      t = entry_type::regular;
    else if (S_ISDIR (m))
      t = entry_type::directory;
    else if (S_ISLNK (m))
      t = entry_type::symlink;
    else if (S_ISBLK (m) || S_ISCHR (m) || S_ISFIFO (m) || S_ISSOCK (m))
      t = entry_type::other;

    return make_pair (true, entry_stat {t, static_cast<uint64_t> (s.st_size)});
  }

#else

  static inline bool
  error_file_not_found (DWORD ec) noexcept
  {
    return ec == ERROR_FILE_NOT_FOUND ||
           ec == ERROR_PATH_NOT_FOUND ||
           ec == ERROR_INVALID_NAME   ||
           ec == ERROR_INVALID_DRIVE  ||
           ec == ERROR_BAD_PATHNAME   ||
           ec == ERROR_BAD_NETPATH;
  }

  static inline bool
  junction (DWORD a) noexcept
  {
    return a != INVALID_FILE_ATTRIBUTES            &&
           (a & FILE_ATTRIBUTE_REPARSE_POINT) != 0 &&
           (a & FILE_ATTRIBUTE_DIRECTORY) != 0;
  }

  static inline bool
  junction (const path& p) noexcept
  {
    return junction (GetFileAttributesA (p.string ().c_str ()));
  }

  // Return true if the junction exists and is referencing an existing
  // directory. Assume that the path references a junction. Underlying OS
  // errors are reported by throwing std::system_error, unless ignore_error
  // is true.
  //
  static bool
  junction_target_exists (const char* p, bool ignore_error)
  {
    HANDLE h (CreateFile (p,
                          FILE_READ_ATTRIBUTES,
                          FILE_SHARE_READ | FILE_SHARE_WRITE,
                          NULL,
                          OPEN_EXISTING,
                          FILE_FLAG_BACKUP_SEMANTICS,
                          NULL));

    if (h == INVALID_HANDLE_VALUE)
    {
      DWORD ec;

      if (ignore_error || error_file_not_found (ec = GetLastError ()))
        return false;

      throw_system_error (ec);
    }

    CloseHandle (h);
    return true;
  }

  static inline bool
  junction_target_exists (const path& p, bool ignore_error)
  {
    return junction_target_exists (p.string ().c_str (), ignore_error);
  }

  pair<bool, entry_stat>
  path_entry (const char* p, bool fl, bool ie)
  {
    // A path like 'C:', while being a root path in our terminology, is not as
    // such for Windows, that maintains current directory for each drive, and
    // so C: means the current directory on the drive C. This is not what we
    // mean here, so need to append the trailing directory separator in such a
    // case.
    //
    string d;
    if (path::traits_type::root (p))
    {
      d = p;
      d += path::traits_type::directory_separator;
      p = d.c_str ();
    }

    // Note that VC's implementations of _stat64() follows junctions and fails
    // for dangling ones. MinGW GCC's implementation returns the information
    // about the junction itself. That's why we handle junctions specially,
    // not relying on _stat64().
    //
    DWORD a (GetFileAttributesA (p));
    if (a == INVALID_FILE_ATTRIBUTES) // Presumably not exists.
      return make_pair (false, entry_stat {entry_type::unknown, 0});

    if (junction (a))
    {
      if (!fl)
        return make_pair (true, entry_stat {entry_type::symlink, 0});

      return junction_target_exists (p, ie)
        ? make_pair (true,  entry_stat {entry_type::directory, 0})
        : make_pair (false, entry_stat {entry_type::unknown, 0});
    }

    entry_type et (entry_type::unknown);
    struct __stat64 s; // For 64-bit size.

    if (_stat64 (p, &s) != 0)
    {
      if (errno == ENOENT || errno == ENOTDIR || ie)
        return make_pair (false, entry_stat {et, 0});
      else
        throw_generic_error (errno);
    }

    // Note that we currently support only directory symlinks (see mksymlink()
    // for details).
    //
    if (S_ISREG (s.st_mode))
      et = entry_type::regular;
    else if (S_ISDIR (s.st_mode))
      et = entry_type::directory;
    //
    //else if (S_ISLNK (s.st_mode))
    //  et = entry_type::symlink;

    return make_pair (true,
                      entry_stat {et, static_cast<uint64_t> (s.st_size)});
  }

#endif

  bool
  touch_file (const path& p, bool create)
  {
    if (file_exists (p))
    {
      // Note that on Windows there are two times: the precise time (which is
      // what we get with system_clock::now()) and what we will call the
      // "filesystem time", which can lag the precise time by as much as a
      // couple of milliseconds. To get the filesystem time use
      // GetSystemTimeAsFileTime(). This is just a heads-up in case we decide
      // to change this code at some point.
      //
#ifndef _WIN32
      if (utime (p.string ().c_str (), nullptr) == -1)
#else
      if (_utime (p.string ().c_str (), nullptr) == -1)
#endif
        throw_generic_error (errno);

      return false;
    }

    if (create && !entry_exists (p))
    {
      // Assuming the file access and modification times are set to the
      // current time automatically.
      //
      fdopen (p, fdopen_mode::out | fdopen_mode::create);
      return true;
    }

    throw_generic_error (ENOENT); // Does not exist or not a file.
  }

  mkdir_status
#ifndef _WIN32
  try_mkdir (const dir_path& p, mode_t m)
  {
    if (mkdir (p.string ().c_str (), m) != 0)
#else
  try_mkdir (const dir_path& p, mode_t)
  {
    if (_mkdir (p.string ().c_str ()) != 0)
#endif
    {
      int e (errno);

      // EEXIST means the path already exists but not necessarily as a
      // directory.
      //
      if (e == EEXIST && dir_exists (p))
        return mkdir_status::already_exists;
      else
        throw_generic_error (e);
    }

    return mkdir_status::success;
  }

  mkdir_status
  try_mkdir_p (const dir_path& p, mode_t m)
  {
    if (!p.root ())
    {
      dir_path d (p.directory ());

      if (!d.empty () && !dir_exists (d))
        try_mkdir_p (d, m);
    }

    return try_mkdir (p, m);
  }

  rmdir_status
  try_rmdir (const dir_path& p, bool ignore_error)
  {
    rmdir_status r (rmdir_status::success);

#ifndef _WIN32
    if (rmdir (p.string ().c_str ()) != 0)
#else
    if (_rmdir (p.string ().c_str ()) != 0)
#endif
    {
      if (errno == ENOENT)
        r = rmdir_status::not_exist;
      else if (errno == ENOTEMPTY || errno == EEXIST)
        r = rmdir_status::not_empty;
      else if (!ignore_error)
        throw_generic_error (errno);
    }

    return r;
  }

  void
  rmdir_r (const dir_path& p, bool dir, bool ignore_error)
  {
    // An nftw()-based implementation (for platforms that support it)
    // might be a faster way.
    //
    // @@ Get rid of these try/catch clauses when ignore_error flag is
    //    implemented for dir_iterator() constructor.
    //
    try
    {
      for (const dir_entry& de: dir_iterator (p, false /* ignore_dangling */))
      {
        path ep (p / de.path ()); //@@ Would be good to reuse the buffer.

        if (de.ltype () == entry_type::directory)
          rmdir_r (path_cast<dir_path> (move (ep)), true, ignore_error);
        else
          try_rmfile (ep, ignore_error);
      }
    }
    catch (const system_error&)
    {
      if (!ignore_error)
        throw;
    }

    if (dir)
    {
      rmdir_status r (try_rmdir (p, ignore_error));

      if (r != rmdir_status::success && !ignore_error)
        throw_generic_error (r == rmdir_status::not_empty
                             ? ENOTEMPTY
                             : ENOENT);
    }
  }

  rmfile_status
  try_rmfile (const path& p, bool ignore_error)
  {
    rmfile_status r (rmfile_status::success);
    const char* f (p.string ().c_str ());

#ifndef _WIN32
    int ur (unlink (f));
#else
    int ur;

    // On Windows a file with the read-only attribute can not be deleted. This
    // can be the reason if the deletion fails with the 'permission denied'
    // error code. In such a case we just reset the attribute and repeat the
    // attempt. If the attempt fails, then we try to restore the attribute.
    //
    // Yet another reason for the 'permission denied' failure can be a
    // directory symlink.
    //
    // And also there are some unknown reasons for the 'permission denied'
    // failure (see mventry() for details). If that's the case, we will keep
    // trying to move the file for a second.
    //
    for (size_t i (0); i < 11; ++i)
    {
      // Sleep 100 milliseconds before the removal retry.
      //
      if (i != 0)
        Sleep (100);

      ur = _unlink (f);

      if (ur != 0 && errno == EACCES)
      {
        DWORD a (GetFileAttributesA (f));
        if (a != INVALID_FILE_ATTRIBUTES)
        {
          bool readonly ((a & FILE_ATTRIBUTE_READONLY) != 0);

          // Note that we support only directory symlinks on Windows.
          //
          bool symlink (junction (a));

          if (readonly || symlink)
          {
            bool restore (readonly &&
                          SetFileAttributes (f, a & ~FILE_ATTRIBUTE_READONLY));

            ur = symlink ? _rmdir (f) : _unlink (f);

            // Restoring the attribute is unlikely to fail since we managed to
            // reset it earlier.
            //
            if (ur != 0 && restore)
              SetFileAttributes (f, a);
          }
        }
      }

      if (ur == 0 || errno != EACCES)
        break;
    }
#endif

    if (ur != 0)
    {
      // Strangely on Linux unlink() removes a dangling symlink but returns
      // ENOENT.
      //
      if (errno == ENOENT || errno == ENOTDIR)
        r = rmfile_status::not_exist;
      else if (!ignore_error)
        throw_generic_error (errno);
    }

    return r;
  }

#ifndef _WIN32

  void
  mksymlink (const path& target, const path& link, bool)
  {
    if (symlink (target.string ().c_str (), link.string ().c_str ()) == -1)
      throw_generic_error (errno);
  }

  rmfile_status
  try_rmsymlink (const path& link, bool, bool ie)
  {
    return try_rmfile (link, ie);
  }

  void
  mkhardlink (const path& target, const path& link, bool)
  {
    if (::link (target.string ().c_str (), link.string ().c_str ()) == -1)
      throw_generic_error (errno);
  }

#else

  void
  mksymlink (const path& target, const path& link, bool dir)
  {
    if (!dir)
      throw_generic_error (ENOSYS, "file symlinks not supported");

    dir_path ld (path_cast<dir_path> (link));

    mkdir_status rs (try_mkdir (ld));

    if (rs == mkdir_status::already_exists)
      throw_generic_error (EEXIST);

    assert (rs == mkdir_status::success);

    // We need to be careful with the directory auto-removal since it is
    // recursive. So we must cancel it right after the reparse point target
    // is setup for the directory path.
    //
    auto_rmdir rm (ld);

    HANDLE h (CreateFile (link.string ().c_str (),
                          GENERIC_WRITE,
                          0,
                          NULL,
                          OPEN_EXISTING,
                          FILE_FLAG_BACKUP_SEMANTICS |
                          FILE_FLAG_OPEN_REPARSE_POINT,
                          NULL));

    if (h == INVALID_HANDLE_VALUE)
      throw_system_error (GetLastError ());

    unique_ptr<HANDLE, void (*)(HANDLE*)> deleter (
      &h,
      [] (HANDLE* h)
      {
        bool r (CloseHandle (*h));

        // The valid file handle that has no IO operations being performed on
        // it should close successfully, unless something is severely damaged.
        //
        assert (r);
      });

    // We will fill the uninitialized members later.
    //
    struct
    {
      // Header.
      //
      DWORD   reparse_tag            = IO_REPARSE_TAG_MOUNT_POINT;
      WORD    reparse_data_length;
      WORD    reserved               = 0;

      // Mount point reparse buffer.
      //
      WORD    substitute_name_offset = 0;
      WORD    substitute_name_length;
      WORD    print_name_offset;
      WORD    print_name_length      = 0;

      // Reserve space for two NULL characters (for the names above).
      //
      wchar_t path_buffer[MAX_PATH + 2];
    } rb;

    // Make the target path absolute, decorate it and convert to a
    // wide-character string.
    //
    path atd (target);

    if (atd.relative ())
      atd.complete ();

    try
    {
      atd.normalize ();
    }
    catch (const invalid_path&)
    {
      throw_generic_error (EINVAL);
    }

    string td ("\\??\\" + atd.string () + "\\");
    const char* s (td.c_str ());

    // Zero-initialize the conversion state (and disambiguate with the
    // function declaration).
    //
    mbstate_t state ((mbstate_t ()));
    size_t n (mbsrtowcs (rb.path_buffer, &s, MAX_PATH + 1, &state));

    if (n == static_cast<size_t> (-1))
      throw_generic_error (errno);

    if (s != NULL) // Not enough space in the destination buffer.
      throw_generic_error (ENAMETOOLONG);

    // Fill the rest of the structure and setup the reparse point.
    //
    // The path length not including NULL character, in bytes.
    //
    WORD nb (static_cast<WORD> (n) * sizeof (wchar_t));
    rb.substitute_name_length = nb;

    // The print name offset, in bytes.
    //
    rb.print_name_offset  = nb + sizeof (wchar_t);
    rb.path_buffer[n + 1] = L'\0'; // Terminate the (empty) print name.

    // The mount point reparse buffer size.
    //
    rb.reparse_data_length =
      4 * sizeof (WORD)     + // Size of *_name_* fields.
      nb + sizeof (wchar_t) + // Path length, in bytes.
      sizeof (wchar_t);       // Print (empty) name length, in bytes.

    DWORD r;
    if (!DeviceIoControl (
          h,
          FSCTL_SET_REPARSE_POINT,
          &rb,
          sizeof (DWORD) + 2 * sizeof (WORD) + // Size of the header.
          rb.reparse_data_length,              // Size of the mount point
          NULL,                                // reparse buffer.
          0,
          &r,
          NULL))
      throw_system_error (GetLastError ());

    rm.cancel ();
  }

  rmfile_status
  try_rmsymlink (const path& link, bool dir, bool ie)
  {
    if (!dir)
      throw_generic_error (ENOSYS, "file symlinks not supported");

    return try_rmfile (link, ie);
  }

  void
  mkhardlink (const path& target, const path& link, bool dir)
  {
    if (!dir)
    {
      if (!CreateHardLinkA (link.string ().c_str (),
                            target.string ().c_str (),
                            nullptr))
      {
        // If creation fails because hardlinks are not supported for the
        // specified target/link paths combination, then throw system_error of
        // the generic category with an approximate POSIX errno code. This way
        // the caller could recognize such a case and, for example, fallback
        // to the copy operation. For other error codes use the system
        // category.
        //
        DWORD ec (GetLastError ());
        switch (ec)
        {
          // Target and link are on different drives.
          //
        case ERROR_NOT_SAME_DEVICE: throw_generic_error (EXDEV);

          // Target and link are on the same drive, which doesn't support
          // hardlinks.
          //
        case ERROR_ACCESS_DENIED: throw_generic_error (EPERM);

          // Some other failure reason. Fallback to the system category.
          //
        default: throw_system_error (ec);
        }
      }
    }
    else
      throw_generic_error (ENOSYS, "directory hard links not supported");
  }
#endif

  entry_type
  mkanylink (const path& target, const path& link, bool copy, bool rel)
  {
    using error = pair<entry_type, system_error>;

    try
    {
      mksymlink (rel ? target.relative (link.directory ()) : target, link);
      return entry_type::symlink;
    }
    catch (system_error& e)
    {
      // Note that we are not guaranteed (here and below) that the
      // system_error exception is of the generic category.
      //
      if (e.code ().category () == generic_category ())
      {
        int c (e.code ().value ());
        if (c == ENOSYS || // Not implemented.
            c == EPERM)    // Not supported by the filesystem(s).
        {
          try
          {
            mkhardlink (target, link);
            return entry_type::other;
          }
          catch (system_error& e)
          {
            if (copy && e.code ().category () == generic_category ())
            {
              int c (e.code ().value ());
              if (c == ENOSYS || // Not implemented.
                  c == EPERM  || // Not supported by the filesystem(s).
                  c == EXDEV)    // On different filesystems.
              {
                try
                {
                  cpfile (target, link);
                  return entry_type::regular;
                }
                catch (system_error& e)
                {
                  throw error (entry_type::regular, move (e));
                }
              }
            }

            throw error (entry_type::other, move (e));
          }
        }
      }

      throw error (entry_type::symlink, move (e));
    }
  }

  // For I/O operations cpfile() can throw ios_base::failure exception that is
  // not derived from system_error for old versions of g++ (as of 4.9). From
  // the other hand cpfile() must throw system_error only. Let's catch
  // ios_base::failure and rethrow as system_error in such a case.
  //
  template <bool v>
  static inline typename enable_if<v>::type
  cpfile (const path& from, const path& to,
          cpflags fl,
          permissions perm,
          auto_rmfile& rm)
  {
    ifdstream ifs (from, fdopen_mode::binary);

    fdopen_mode om (fdopen_mode::out      |
                    fdopen_mode::truncate |
                    fdopen_mode::create   |
                    fdopen_mode::binary);

    if ((fl & cpflags::overwrite_content) != cpflags::overwrite_content)
      om |= fdopen_mode::exclusive;

    ofdstream ofs (fdopen (to, om, perm));

    rm = auto_rmfile (to);

    // Throws ios::failure on fdbuf read/write failures.
    //
    // Note that the eof check is important: if the stream is at eof (empty
    // file) then this write will fail.
    //
    if (ifs.peek () != ifdstream::traits_type::eof ())
      ofs << ifs.rdbuf ();

    ifs.close (); // Throws ios::failure on failure.
    ofs.close (); // Throws ios::failure on flush/close failure.
  }

  template <bool v>
  static inline typename enable_if<!v>::type
  cpfile (const path& from, const path& to,
          cpflags fl,
          permissions perm,
          auto_rmfile& rm)
  {
    try
    {
      cpfile<true> (from, to, fl, perm, rm);
    }
    catch (const ios_base::failure& e)
    {
      // While we try to preserve the original error information, we can not
      // make the description to be exactly the same, for example
      //
      // Is a directory
      //
      // becomes
      //
      // Is a directory: Input/output error
      //
      // Note that our custom operator<<(ostream, exception) doesn't strip this
      // suffix. This is a temporary code after all.
      //
      throw_generic_error (EIO, e.what ());
    }
  }

  void
  cpfile (const path& from, const path& to, cpflags fl)
  {
    permissions perm (path_permissions (from));
    auto_rmfile rm;

    cpfile<is_base_of<system_error, ios_base::failure>::value> (
      from, to, fl, perm, rm);

    if ((fl & cpflags::overwrite_permissions) ==
        cpflags::overwrite_permissions)
      path_permissions (to, perm);

    if ((fl & cpflags::copy_timestamps) == cpflags::copy_timestamps)
      file_time (to, file_time (from));

    rm.cancel ();
  }

  // Figuring out whether we have the nanoseconds in struct stat. Some
  // platforms (e.g., FreeBSD), may provide some "compatibility" #define's,
  // so use the second argument to not end up with the same signatures.
  //
  template <typename S>
  static inline constexpr auto
  mnsec (const S* s, bool) -> decltype(s->st_mtim.tv_nsec)
  {
    return s->st_mtim.tv_nsec; // POSIX (GNU/Linux, Solaris).
  }

  template <typename S>
  static inline constexpr auto
  mnsec (const S* s, int) -> decltype(s->st_mtimespec.tv_nsec)
  {
    return s->st_mtimespec.tv_nsec; // *BSD, MacOS.
  }

  template <typename S>
  static inline constexpr auto
  mnsec (const S* s, float) -> decltype(s->st_mtime_n)
  {
    return s->st_mtime_n; // AIX 5.2 and later.
  }

  // Things are not going to end up well with only seconds resolution so
  // let's make it a compile error.
  //
  // template <typename S>
  // static inline constexpr int
  // mnsec (...) {return 0;}

  template <typename S>
  static inline constexpr auto
  ansec (const S* s, bool) -> decltype(s->st_atim.tv_nsec)
  {
    return s->st_atim.tv_nsec; // POSIX (GNU/Linux, Solaris).
  }

  template <typename S>
  static inline constexpr auto
  ansec (const S* s, int) -> decltype(s->st_atimespec.tv_nsec)
  {
    return s->st_atimespec.tv_nsec; // *BSD, MacOS.
  }

  template <typename S>
  static inline constexpr auto
  ansec (const S* s, float) -> decltype(s->st_atime_n)
  {
    return s->st_atime_n; // AIX 5.2 and later.
  }

  // template <typename S>
  // static inline constexpr int
  // ansec (...) {return 0;}

  void
  mventry (const path& from, const path& to, cpflags fl)
  {
    assert ((fl & cpflags::overwrite_permissions) ==
            cpflags::overwrite_permissions);

    bool ovr ((fl & cpflags::overwrite_content) == cpflags::overwrite_content);

    const char* f (from.string ().c_str ());
    const char* t (to.string ().c_str ());

#ifndef _WIN32

    if (!ovr && path_entry (to).first)
      throw_generic_error (EEXIST);

    if (::rename (f, t) == 0) // POSIX implementation.
      return;

    // If source and destination paths are on different file systems we need to
    // move the file ourselves.
    //
    if (errno != EXDEV)
      throw_generic_error (errno);

    // Note that cpfile() follows symlinks, so we need to remove destination if
    // exists.
    //
    try_rmfile (to);

    // Note that permissions are copied unconditionally to a new file.
    //
    cpfile (from, to, cpflags::none);

    // Copy file access and modification times.
    //
    file_time (t, file_time (f));

    // Finally, remove the source file.
    //
    try_rmfile (from);

#else

    // While ::rename() is present on Windows, it is not POSIX but ISO C
    // implementation, that doesn't fit our needs well.
    //
    auto te (path_entry (to));

    if (!ovr && te.first)
      throw_generic_error (EEXIST);

    bool td (te.first && te.second.type == entry_type::directory);

    auto fe (path_entry (from));
    bool fd (fe.first && fe.second.type == entry_type::directory);

    // If source and destination filesystem entries exist, they both must be
    // either directories or not directories.
    //
    if (fe.first && te.first && fd != td)
      throw_generic_error (ENOTDIR);

    DWORD mfl (fd ? 0 : (MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING));

    // For reasons unknown an attempt to move a file sometimes ends up with
    // the 'file is being used by another process' error. If that's the case,
    // we will keep trying to move the file for a second.
    //
    // The thinking is that there can be some Windows process analyzing newly
    // created files and so preventing their move or removal.
    //
    DWORD ec;
    for (size_t i (0); i < 11; ++i)
    {
      // Sleep 100 milliseconds before the move retry.
      //
      if (i != 0)
        Sleep (100);

      if (MoveFileExA (f, t, mfl))
        return;

      ec = GetLastError ();

      // If the destination already exists, then MoveFileExA() succeeds only
      // if it is a regular file or a symlink. Lets also support an empty
      // directory special case to comply with POSIX. If the destination is an
      // empty directory we will just remove it and retry the move operation.
      //
      // Note that under Wine we endup with ERROR_ACCESS_DENIED error code in
      // that case, and with ERROR_ALREADY_EXISTS when run natively.
      //
      if ((ec == ERROR_ALREADY_EXISTS || ec == ERROR_ACCESS_DENIED) && td &&
          try_rmdir (path_cast<dir_path> (to)) != rmdir_status::not_empty)
      {
        if (MoveFileExA (f, t, mfl))
          return;

        ec = GetLastError ();
      }

      if (ec != ERROR_SHARING_VIOLATION)
        break;
    }

    throw_system_error (ec);

#endif
  }

  // Return the modification and access times of a regular file or directory.
  //
  static entry_time
  entry_tm (const char* p, bool dir)
  {
#ifndef _WIN32

    struct stat s;
    if (stat (p, &s) != 0)
    {
      if (errno == ENOENT || errno == ENOTDIR)
        return {timestamp_nonexistent, timestamp_nonexistent};
      else
        throw_generic_error (errno);
    }

    if (dir ? !S_ISDIR (s.st_mode) : !S_ISREG (s.st_mode))
      return {timestamp_nonexistent, timestamp_nonexistent};

    auto tm = [] (time_t sec, auto nsec) -> timestamp
    {
      return system_clock::from_time_t (sec) +
        chrono::duration_cast<duration> (chrono::nanoseconds (nsec));
    };

    return {tm (s.st_mtime, mnsec<struct stat> (&s, true)),
            tm (s.st_atime, ansec<struct stat> (&s, true))};

#else

    WIN32_FILE_ATTRIBUTE_DATA s;

    if (!GetFileAttributesExA (p, GetFileExInfoStandard, &s))
    {
      DWORD ec (GetLastError ());

      if (error_file_not_found (ec))
        return {timestamp_nonexistent, timestamp_nonexistent};

      throw_system_error (ec);
    }

    if ((s.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) !=
        (dir ? FILE_ATTRIBUTE_DIRECTORY : 0))
      return {timestamp_nonexistent, timestamp_nonexistent};

    auto tm = [] (const FILETIME& t) -> timestamp
    {
      // Time in FILETIME is in 100 nanosecond "ticks" since "Windows epoch"
      // (1601-01-01T00:00:00Z). To convert it to "UNIX epoch"
      // (1970-01-01T00:00:00Z) we need to subtract 11644473600 seconds.
      //
      uint64_t nsec ((static_cast<uint64_t> (t.dwHighDateTime) << 32) |
                     t.dwLowDateTime);

      nsec -= 11644473600ULL * 10000000; // Now in UNIX epoch.
      nsec *= 100;                       // Now in nanoseconds.

      return timestamp (
        chrono::duration_cast<duration> (chrono::nanoseconds (nsec)));
    };

    return {tm (s.ftLastWriteTime), tm (s.ftLastAccessTime)};

#endif
  }

  entry_time
  file_time (const char* p)
  {
    return entry_tm (p, false);
  }

  entry_time
  dir_time (const char* p)
  {
    return entry_tm (p, true);
  }

  // Set the modification and access times for a regular file or directory.
  //
  static void
  entry_tm (const char* p, const entry_time& t, bool dir)
  {
#ifndef _WIN32

    struct stat s;
    if (stat (p, &s) != 0)
      throw_generic_error (errno);

    // If the entry is of the wrong type, then let's pretend that it doesn't
    // exists. In other words, the entry of the required type doesn't exist.
    //
    if (dir ? !S_ISDIR (s.st_mode) : !S_ISREG (s.st_mode))
      return throw_generic_error (ENOENT);

    // Note: timeval has the microsecond resolution.
    //
    auto tm = [] (timestamp t, time_t sec, auto nsec) -> timeval
    {
      using usec_type = decltype (timeval::tv_usec);

      if (t == timestamp_nonexistent)
        return {sec, static_cast<usec_type> (nsec / 1000)};

      uint64_t usec (chrono::duration_cast<chrono::microseconds> (
                       t.time_since_epoch ()).count ());

      return {static_cast<time_t> (usec / 1000000),     // Seconds.
              static_cast<usec_type> (usec % 1000000)}; // Microseconds.
    };

    timeval times[2];
    times[0] = tm (t.access, s.st_atime, ansec<struct stat> (&s, true));
    times[1] = tm (t.modification, s.st_mtime, mnsec<struct stat> (&s, true));

    if (utimes (p, times) != 0)
      throw_generic_error (errno);

#else

    DWORD attr (GetFileAttributesA (p));

    if (attr == INVALID_FILE_ATTRIBUTES)
      throw_system_error (GetLastError ());

    // If the entry is of the wrong type, then let's pretend that it doesn't
    // exists.
    //
    if ((attr & FILE_ATTRIBUTE_DIRECTORY) !=
        (dir ? FILE_ATTRIBUTE_DIRECTORY : 0))
      return throw_generic_error (ENOENT);

    HANDLE h (CreateFile (p,
                          FILE_WRITE_ATTRIBUTES,
                          FILE_SHARE_READ | FILE_SHARE_WRITE,
                          NULL,
                          OPEN_EXISTING,
                          dir ? FILE_FLAG_BACKUP_SEMANTICS : 0,
                          NULL));

    if (h == INVALID_HANDLE_VALUE)
      throw_system_error (GetLastError ());

    unique_ptr<HANDLE, void (*)(HANDLE*)> deleter (
      &h, [] (HANDLE* h)
      {
        bool r (CloseHandle (*h));

        // The valid file handle that has no IO operations being performed on
        // it should close successfully, unless something is severely damaged.
        //
        assert (r);
      });

    auto tm = [] (timestamp t, FILETIME& ft) -> const FILETIME*
    {
      if (t == timestamp_nonexistent)
        return NULL;

      // Time in FILETIME is in 100 nanosecond "ticks" since "Windows epoch"
      // (1601-01-01T00:00:00Z). To convert "UNIX epoch"
      // (1970-01-01T00:00:00Z) to it we need to add 11644473600 seconds.
      //
      uint64_t ticks (chrono::duration_cast<chrono::nanoseconds> (
                        t.time_since_epoch ()).count ());

      ticks /= 100;                       // Now in 100 nanosecond "ticks".
      ticks += 11644473600ULL * 10000000; // Now in "Windows epoch".

      ft.dwHighDateTime = (ticks >> 32) & 0xFFFFFFFF;
      ft.dwLowDateTime = ticks & 0xFFFFFFFF;
      return &ft;
    };

    FILETIME at;
    FILETIME mt;
    if (!SetFileTime (h, NULL, tm (t.access, at), tm (t.modification, mt)))
      throw_system_error (GetLastError ());

#endif
  }

  void
  file_time (const char* p, const entry_time& t)
  {
    entry_tm (p, t, false);
  }

  void
  dir_time (const char* p, const entry_time& t)
  {
    entry_tm (p, t, true);
  }

  permissions
  path_permissions (const path& p)
  {
#ifndef _WIN32
    struct stat s;
    if (stat (p.string ().c_str (), &s) != 0)
#else
    struct _stat s;
    if (_stat (p.string ().c_str (), &s) != 0)
#endif
      throw_generic_error (errno);

    // VC++ has no S_IRWXU defined. MINGW GCC <= 4.9 has no S_IRWXG, S_IRWXO
    // defined.
    //
    // We could extrapolate user permissions to group/other permissions if
    // S_IRWXG/S_IRWXO are undefined. That is, we could consider their absence
    // as meaning that the platform does not distinguish between permissions
    // for different kinds of users. Let's wait for a use-case first.
    //
    mode_t f (S_IREAD | S_IWRITE | S_IEXEC);

#ifdef S_IRWXG
    f |= S_IRWXG;
#endif

#ifdef S_IRWXO
    f |= S_IRWXO;
#endif

    return static_cast<permissions> (s.st_mode & f);
  }

  void
  path_permissions (const path& p, permissions f)
  {
    mode_t m (S_IREAD | S_IWRITE | S_IEXEC);

#ifdef S_IRWXG
    m |= S_IRWXG;
#endif

#ifdef S_IRWXO
    m |= S_IRWXO;
#endif

    m &= static_cast<mode_t> (f);

#ifndef _WIN32
    if (chmod (p.string ().c_str (), m) == -1)
#else
    if (_chmod (p.string ().c_str (), m) == -1)
#endif
      throw_generic_error (errno);
  }

  // dir_{entry,iterator}
  //
#ifndef _WIN32

  // dir_entry
  //
  dir_iterator::
  ~dir_iterator ()
  {
    if (h_ != nullptr)
      closedir (h_); // Ignore any errors.
  }

  dir_iterator& dir_iterator::
  operator= (dir_iterator&& x)
  {
    if (this != &x)
    {
      e_ = move (x.e_);

      if (h_ != nullptr && closedir (h_) == -1)
        throw_generic_error (errno);

      h_ = x.h_;
      x.h_ = nullptr;

      ignore_dangling_ = x.ignore_dangling_;
    }
    return *this;
  }

  static inline entry_type
  type (const struct stat& s) noexcept
  {
    if (S_ISREG (s.st_mode))
      return entry_type::regular;
    else if (S_ISDIR (s.st_mode))
      return entry_type::directory;
    else if (S_ISLNK (s.st_mode))
      return entry_type::symlink;
    else
      return entry_type::other;
  }

  entry_type dir_entry::
  type (bool link) const
  {
    path_type p (b_ / p_);
    struct stat s;
    if ((link
         ? stat (p.string ().c_str (), &s)
         : lstat (p.string ().c_str (), &s)) != 0)
      throw_generic_error (errno);

    return butl::type (s);
  }

  // dir_iterator
  //
  struct dir_deleter
  {
    void operator() (DIR* p) const {if (p != nullptr) closedir (p);}
  };

  dir_iterator::
  dir_iterator (const dir_path& d, bool ignore_dangling)
    : ignore_dangling_ (ignore_dangling)
  {
    unique_ptr<DIR, dir_deleter> h (opendir (d.string ().c_str ()));
    h_ = h.get ();

    if (h_ == nullptr)
      throw_generic_error (errno);

    e_.b_ = d; // Used by next() to detect dangling symlinks.

    next ();

    h.release ();
  }

  template <typename D>
  static inline /*constexpr*/ entry_type
  d_type (const D* d, decltype(d->d_type)*)
  {
    switch (d->d_type)
    {
#ifdef DT_DIR
    case DT_DIR: return entry_type::directory;
#endif
#ifdef DT_REG
    case DT_REG: return entry_type::regular;
#endif
#ifdef DT_LNK
    case DT_LNK: return entry_type::symlink;
#endif
#ifdef DT_BLK
    case DT_BLK:
#endif
#ifdef DT_CHR
    case DT_CHR:
#endif
#ifdef DT_FIFO
    case DT_FIFO:
#endif
#ifdef DT_SOCK
    case DT_SOCK:
#endif
      return entry_type::other;

    default: return entry_type::unknown;
    }
  }

  template <typename D>
  static inline constexpr entry_type
  d_type (...) {return entry_type::unknown;}

  void dir_iterator::
  next ()
  {
    for (;;)
    {
      errno = 0;
      if (struct dirent* de = readdir (h_))
      {
        // We can accept some overhead for '.' and '..' (relying on short
        // string optimization) in favor of a more compact code.
        //
        path p (de->d_name);

        // Skip '.' and '..'.
        //
        if (p.current () || p.parent ())
          continue;

        e_.p_ = move (p);
        e_.t_ = d_type<struct dirent> (de, nullptr);
        e_.lt_ = entry_type::unknown;

        // If requested, we ignore dangling symlinks, skipping ones with
        // non-existing or inaccessible targets.
        //
        // Note that ltype () can potentially lstat() (see d_type() for
        // details) and so throw.
        //
        if (ignore_dangling_ && e_.ltype () == entry_type::symlink)
        {
          struct stat s;
          path pe (e_.base () / e_.path ());

          if (stat (pe.string ().c_str (), &s) != 0)
          {
            if (errno == ENOENT || errno == ENOTDIR || errno == EACCES)
              continue;

            throw_generic_error (errno);
          }

          e_.lt_ = type (s); // While at it, set the target type.
        }
      }
      else if (errno == 0)
      {
        // End of stream.
        //
        closedir (h_);
        h_ = nullptr;
      }
      else
        throw_generic_error (errno);

      break;
    }
  }

#else

  // dir_entry
  //
  dir_iterator::
  ~dir_iterator ()
  {
    if (h_ != -1)
      _findclose (h_); // Ignore any errors.
  }

  dir_iterator& dir_iterator::
  operator= (dir_iterator&& x)
  {
    if (this != &x)
    {
      e_ = move (x.e_);

      if (h_ != -1 && _findclose (h_) == -1)
        throw_generic_error (errno);

      h_ = x.h_;
      x.h_ = -1;

      ignore_dangling_ = x.ignore_dangling_;
    }
    return *this;
  }

  entry_type dir_entry::
  type (bool link) const
  {
    path_type p (base () / path ());
    pair<bool, entry_stat> e (path_entry (p, link));

    if (!e.first)
      throw_generic_error (ENOENT);

    return e.second.type;
  }

  // dir_iterator
  //
  struct auto_dir
  {
    explicit
    auto_dir (intptr_t& h): h_ (&h) {}

    auto_dir (const auto_dir&) = delete;
    auto_dir& operator= (const auto_dir&) = delete;

    ~auto_dir ()
    {
      if (h_ != nullptr && *h_ != -1)
        _findclose (*h_);
    }

    void release () {h_ = nullptr;}

  private:
    intptr_t* h_;
  };

  dir_iterator::
  dir_iterator (const dir_path& d, bool ignore_dangling)
    : ignore_dangling_ (ignore_dangling)
  {
    auto_dir h (h_);
    e_.b_ = d; // Used by next().

    next ();
    h.release ();
  }

  void dir_iterator::
  next ()
  {
    for (;;)
    {
      bool r;
      _finddata_t fi;

      if (h_ == -1)
      {
        // The call is made from the constructor. Any other call with h_ == -1
        // is illegal.
        //

        // Check to distinguish non-existent vs empty directories.
        //
        if (!dir_exists (e_.base ()))
          throw_generic_error (ENOENT);

        h_ = _findfirst ((e_.base () / path ("*")).string ().c_str (), &fi);
        r = h_ != -1;
      }
      else
        r = _findnext (h_, &fi) == 0;

      if (r)
      {
        // We can accept some overhead for '.' and '..' (relying on short
        // string optimization) in favor of a more compact code.
        //
        path p (fi.name);

        // Skip '.' and '..'.
        //
        if (p.current () || p.parent ())
          continue;

        e_.p_ = move (p);

        // An entry with the _A_SUBDIR attribute can also be a junction.
        //
        e_.t_ = (fi.attrib & _A_SUBDIR) == 0       ? entry_type::regular :
                junction (e_.base () / e_.path ()) ? entry_type::symlink :
                entry_type::directory;

        e_.lt_ = entry_type::unknown;

        // If requested, we ignore dangling symlinks, skipping ones with
        // non-existing or inaccessible targets.
        //
        if (ignore_dangling_                   &&
            e_.ltype () == entry_type::symlink &&
            !junction_target_exists (e_.base () / e_.path (),
                                     true /* ignore_error */))
          continue;
      }
      else if (errno == ENOENT)
      {
        // End of stream.
        //
        if (h_ != -1)
        {
          _findclose (h_);
          h_ = -1;
        }
      }
      else
        throw_generic_error (errno);

      break;
    }
  }
#endif

  // patterns
  //
  static inline bool
  match (char c, char pc)
  {
#ifndef _WIN32
    return c == pc;
#else
    return lcase (c) == lcase (pc);
#endif
  }

  bool
  match_bracket (char c, const path_pattern_term& pt)
  {
    using iterator = string::const_iterator;

    assert (pt.bracket ());

    iterator i (pt.begin + 1); // Position after '['.
    iterator e (pt.end   - 1); // Position at ']'.

    bool invert (*i == '!');
    if (invert)
      ++i;

    bool r (false);
    for (iterator b (i); i != e && !r; ++i)
    {
      char bc (*i);

      // If '-' is a first or last character in the bracket expression then
      // match it literally and match the range otherwise.
      //
      if (bc == '-' && i != b && i + 1 != e) // Match the range?
      {
        // Note that we have already matched the range left endpoint character
        // unsuccessfully (otherwise we wouldn't be here), so now we test if
        // the character belongs to the (min-char, max-char] range.
        //
        // Also note that on Windows we match case insensitively and so can't
        // just compare the character with the range endpoints. Thus, we
        // fallback to matching each range character individually.
        //
#ifndef _WIN32
        r = c > *(i - 1) && c <= *(i + 1);
#else
        for (char bc (*(i - 1) + 1), mx (*(i + 1)); bc <= mx && !r; ++bc)
          r = match (c, bc);
#endif

        ++i; // Position to the range max character.
      }
      else // Match against the expression character literally.
        r = match (c, bc);
    }

    return r != invert;
  }

  // Match the name [ni, ne) to the pattern [pi, pe) that may not contain
  // bracket expressions. Ranges can be empty.
  //
  static bool
  match_no_brackets (string::const_iterator pi, string::const_iterator pe,
                     string::const_iterator ni, string::const_iterator ne)
  {
    using reverse_iterator = std::reverse_iterator<string::const_iterator>;

    reverse_iterator rpi (pe);
    reverse_iterator rpe (pi);

    reverse_iterator rni (ne);
    reverse_iterator rne (ni);

    // Match the pattern suffix (follows the last *) to the name trailing
    // characters.
    //
    char pc ('\0');
    for (; rpi != rpe && (pc = *rpi) != '*' && rni != rne; ++rpi, ++rni)
    {
      if (!match (*rni, pc) && pc != '?')
        return false;
    }

    // If we got to the (reversed) end of the pattern (no * is encountered)
    // than we are done. The success depends on if we got to the (reversed) end
    // of the name as well.
    //
    if (rpi == rpe)
      return rni == rne;

    // If we didn't reach * in the pattern then we reached the (reversed) end
    // of the name. That means we have unmatched non-star terms in the
    // pattern, and so match failed.
    //
    if (pc != '*')
    {
      assert (rni == rne);
      return false;
    }

    // Match the pattern prefix (ends with the first *) to the name leading
    // characters. If they mismatch we failed. Otherwise if this is an only *
    // in the pattern (matches whatever is left in the name) then we succeed,
    // otherwise we perform backtracking (recursively).
    //
    pe = rpi.base ();
    ne = rni.base ();

    // Compare the pattern and the name term by char until the name suffix or
    // * is encountered in the pattern (whichever happens first). Fail if a
    // char mismatches.
    //
    for (; (pc = *pi) != '*' && ni != ne; ++pi, ++ni)
    {
      if (!match (*ni, pc) && pc != '?')
        return false;
    }

    // If we didn't get to * in the pattern then we got to the name suffix.
    // That means that the pattern has unmatched non-star terms, and so match
    // failed.
    //
    if (pc != '*')
    {
      assert (ni == ne);
      return false;
    }

    // If * that we have reached is the last one, then it matches whatever is
    // left in the name (including an empty range).
    //
    if (++pi == pe)
      return true;

    // Perform backtracking.
    //
    // From now on, we will call the pattern not-yet-matched part (starting
    // the leftmost * and ending the rightmost one inclusively) as pattern, and
    // the name not-yet-matched part as name.
    //
    // Here we sequentially assume that * that starts the pattern matches the
    // name leading part (staring from an empty one and iterating till the full
    // name). So if, at some iteration, the pattern trailing part (that follows
    // the leftmost *) matches the name trailing part, then the pattern matches
    // the name.
    //
    bool r;
    for (; !(r = match_no_brackets (pi, pe, ni, ne)) && ni != ne; ++ni) ;
    return r;
  }

  // Match a character against the pattern term.
  //
  static inline bool
  match (char c, const path_pattern_term& pt)
  {
    switch (pt.type)
    {
      // Matches any character.
      //
    case path_pattern_term_type::star:
    case path_pattern_term_type::question: return true;

    case path_pattern_term_type::bracket:
      {
        return match_bracket (c, pt);
      }

    case path_pattern_term_type::literal:
      {
        return match (c, get_literal (pt));
      }
    }

    assert (false); // Can't be here.
    return false;
  }

  // Match the name [ni, ne) to the pattern [pi, pe). Ranges can be empty.
  //
  static bool
  match (string::const_iterator pi, string::const_iterator pe,
         string::const_iterator ni, string::const_iterator ne)
  {
    // If the pattern doesn't contain the bracket expressions then reduce to
    // the "clever" approach (see the implementation notes below for details).
    //
    if (find (pi, pe, '[') == pe)
      return match_no_brackets (pi, pe, ni, ne);

    // Match the pattern prefix (precedes the first *) to the name leading
    // characters.
    //
    path_pattern_iterator ppi (pi, pe);
    path_pattern_iterator ppe;
    path_pattern_term pt;

    for (; ppi != ppe && !(pt = *ppi).star () && ni != ne; ++ppi, ++ni)
    {
      if (!match (*ni, pt))
        return false;
    }

    // If we got to the end of the pattern (no * is encountered) than we are
    // done. The success depends on if we got to the end of the name as well.
    //
    if (ppi == ppe)
      return ni == ne;

    // If we didn't reach * in the pattern then we reached the end of the
    // name. That means we have unmatched non-star terms in the pattern, and
    // so match failed.
    //
    if (!pt.star ())
    {
      assert (ni == ne);
      return false;
    }

    // If * that we have reached is the last term, then it matches whatever is
    // left in the name (including an empty range).
    //
    if (++ppi == ppe)
      return true;

    // Switch back to the string iterator and perform backtracking.
    //
    // From now on, we will call the pattern not-yet-matched part (starting
    // the leftmost *) as pattern, and the name not-yet-matched part as name.
    //
    // Here we sequentially assume that * that starts the pattern matches the
    // name leading part (see match_no_brackets() for details).
    //
    bool r;
    for (pi = ppi->begin; !(r = match (pi, pe, ni, ne)) && ni != ne; ++ni) ;
    return r;
  }

  bool
  path_match (const string& pattern, const string& name)
  {
    // Implementation notes:
    //
    // - This has a good potential of becoming hairy quickly so need to strive
    //   for an elegant way to implement this.
    //
    // - Most patterns will contains a single * wildcard with a prefix and/or
    //   suffix (e.g., *.txt, foo*, f*.txt). Something like this is not very
    //   common: *foo*.
    //
    //   So it would be nice to have a clever implementation that first
    //   "anchors" itself with a literal prefix and/or suffix and only then
    //   continue with backtracking. In other words, reduce:
    //
    //   *.txt  vs foo.txt -> * vs foo
    //   foo*   vs foo.txt -> * vs .txt
    //   f*.txt vs foo.txt -> * vs oo
    //
    //   Note that this approach fails if the pattern may contain bracket
    //   expressions. You can't easily recognize a suffix scanning backwards
    //   since * semantics depends on the characters to the left:
    //
    //   f[o*]o - * is not a wildcard
    //    fo*]o - * is a wildcard
    //
    //   That's why we will start with the straightforward left-to-right
    //   matching and reduce to the "clever" approach when the remaining part
    //   of the pattern doesn't contain bracket expressions.

    auto pi (pattern.rbegin ());
    auto pe (pattern.rend ());

    auto ni (name.rbegin ());
    auto ne (name.rend ());

    // The name doesn't match the pattern if it is of a different type than the
    // pattern is.
    //
    bool pd (pi != pe && path::traits_type::is_separator (*pi));
    bool nd (ni != ne && path::traits_type::is_separator (*ni));

    if (pd != nd)
      return false;

    // Skip trailing separators if present.
    //
    if (pd)
    {
      ++pi;
      ++ni;
    }

    return match (pattern.begin (), pi.base (), name.begin (), ni.base ());
  }

  // Search for paths matching the pattern and call the specified function for
  // each matching path. Return false if the underlying func() call returns
  // false. Otherwise the function conforms to the path_search() description.
  //
  // Note that the access to the traversed directory tree (real or virtual) is
  // performed through the provided filesystem object.
  //
  static const string any_dir ("*/");

  template <typename FS>
  static bool
  search (
    path pattern,
    dir_path pattern_dir,
    path_match_flags fl,
    const function<bool (path&&, const string& pattern, bool interm)>& func,
    FS& filesystem)
  {
    bool follow_symlinks ((fl & path_match_flags::follow_symlinks) !=
                          path_match_flags::none);

    // Fast-forward the leftmost pattern non-wildcard components. So, for
    // example, search for foo/f* in /bar/ becomes search for f* in /bar/foo/.
    //
    {
      auto b (pattern.begin ());
      auto e (pattern.end ());
      auto i (b);
      for (; i != e && !path_pattern (*i); ++i) ;

      // If the pattern has no wildcards then we reduce to checking for the
      // filesystem entry existence. It matches if exists and is of the proper
      // type.
      //
      if (i == e)
      {
        path p (pattern_dir / pattern);
        auto pe (filesystem.path_entry (p, follow_symlinks));

        if (pe.first &&
            ((pe.second.type == entry_type::directory) == p.to_directory ()))
          return func (move (p), string (), false);

        return true;
      }
      else if (i != b) // There are non-wildcard components, so fast-forward.
      {
        path p (b, i);
        pattern = pattern.leaf (p);
        pattern_dir /= path_cast<dir_path> (move (p));
      }
    }

    assert (!pattern.empty ());

    // The pattern leftmost component. Will use it to match the start directory
    // sub-entries.
    //
    path pc (pattern.begin (), ++pattern.begin ());
    string pcr (pc.representation ());

    // Note that if the pattern has multiple components (is not a simple path),
    // then the leftmost one has a trailing separator, and so will match
    // sub-directories only.
    //
    bool simple (pattern.simple ());

    // Note that we rely on "small function object" optimization here.
    //
    typename FS::iterator_type i (filesystem.iterator (
      pattern_dir,
      path_pattern_recursive (pcr),
      path_pattern_self_matching (pcr),
      follow_symlinks || !simple,
      [&pattern_dir, &func] (const dir_path& p) -> bool // Preopen.
      {
        return func (pattern_dir / p, any_dir, true);
      }));

    // Canonicalize the pattern component collapsing consecutive stars (used to
    // express that it is recursive) into a single one.
    //
    auto j (pcr.begin ());
    bool prev_star (false);
    for (const path_pattern_term& t: path_pattern_iterator (pcr))
    {
      // Skip the repeated star wildcard.
      //
      if (t.star () && prev_star)
        continue;

      // Note: we only need to copy the pattern term if a star have already
      // been skipped.
      //
      assert (j <= t.begin);

      if (j != t.begin)
        copy (t.begin, t.end, j);

      j += t.size ();

      prev_star = t.star ();
    }

    if (j != pcr.end ())
      pcr.resize (j - pcr.begin ());

    // Note that the callback function can be called for the same directory
    // twice: first time as intermediate match from iterator's preopen() call,
    // and then, if the first call succeed, from the iterating loop (possibly
    // as the final match).
    //
    path p;
    while (i.next (p))
    {
      // Skip sub-entry if its name doesn't match the pattern leftmost
      // component.
      //
      // Matching the directory we are iterating through (as for a pattern
      // component containing ***) is a bit tricky. This directory is
      // represented by the iterator as an empty path, and so we need to
      // compute it (the leaf would actually be enough) for matching. This
      // leaf can be acquired from the pattern_dir (if not empty) or
      // start_dir.  We don't expect the start_dir to be empty, as the
      // filesystem object must replace an empty start directory with the
      // current one. This is the case when we search in the current directory
      // (start_dir is empty) with a pattern that starts with a *** wildcard
      // (for example f***/bar).  Note that this will be the only case per
      // path_search() as the next time pattern_dir will not be empty. Also
      // note that this is never the case for a pattern that is an absolute
      // path, as the first component cannot be a wildcard (is empty for POSIX
      // and is drive for Windows).
      //
      const path& se (!p.empty ()
                      ? p
                      : path_cast<path> (!pattern_dir.empty ()
                                         ? pattern_dir
                                         : filesystem.start_dir ()));

      if (!path_match (pcr, se.leaf ().representation ()))
        continue;

      // If the callback function returns false, then we stop the entire search
      // for the final match, or do not search below the path for the
      // intermediate one.
      //
      if (!func (pattern_dir / p, pcr, !simple))
      {
        if (simple) // Final match.
          return false;
        else
          continue;
      }

      // If the pattern is not a simple one, and it's leftmost component
      // matches the sub-entry, then the sub-entry is a directory (see the note
      // above), and we search in it using the trailing part of the pattern.
      //
      if (!simple && !search (pattern.leaf (pc),
                              pattern_dir / path_cast<dir_path> (move (p)),
                              fl,
                              func,
                              filesystem))
        return false;
    }

    // If requested, also search with the absent-matching pattern path
    // component omitted, unless this is the only pattern component.
    //
    if ((fl & path_match_flags::match_absent) != path_match_flags::none &&
        pc.to_directory ()                                              &&
        (!pattern_dir.empty () || !simple)                              &&
        pc.string ().find_first_not_of ('*') == string::npos            &&
        !search (pattern.leaf (pc), pattern_dir, fl, func, filesystem))
      return false;

    return true;
  }

  // Path search implementations.
  //
  static const dir_path empty_dir;

  using preopen = function<bool (const dir_path&)>;

  // Base for filesystem (see above) implementations.
  //
  // Don't copy start directory. It is expected to exist till the end of the
  // object lifetime.
  //
  class filesystem_base
  {
  protected:
    filesystem_base (const dir_path& start): start_ (start) {}

  public:
    const dir_path&
    start_dir ()
    {
      if (!start_.empty ())
        return start_;

      if (current_.empty ())
        current_ = dir_path::current_directory ();

      return current_;
    }

  protected:
    const dir_path& start_;
    dir_path current_;
  };

  // Search path in the real filesystem.
  //
  // Iterate over directory sub-entries, recursively and including itself if
  // requested. Note that recursive iterating goes depth-first which make
  // sense for the cleanup use cases (@@ maybe this should be controllable
  // since for directory creation it won't make sense).
  //
  // Prior to recursively opening a directory for iterating the preopen
  // callback function is called. If false is returned, then the directory is
  // not traversed but still returned by the next() call.
  //
  // Note that iterating over non-existent directory is not en error. The
  // subsequent next() call returns false for such a directory.
  //
  class recursive_dir_iterator
  {
  public:
    recursive_dir_iterator (dir_path p,
                            bool recursive,
                            bool self,
                            bool fs,
                            preopen po)
        : start_ (move (p)),
          recursive_ (recursive),
          self_ (self),
          follow_symlinks_ (fs),
          preopen_ (move (po))
    {
      open (dir_path (), self_);
    }

    // Move constructible-only, non-assignable type.
    //
    recursive_dir_iterator (const recursive_dir_iterator&) = delete;
    recursive_dir_iterator& operator= (const recursive_dir_iterator&) = delete;
    recursive_dir_iterator (recursive_dir_iterator&&) = default;

    // Return false if no more entries left. Otherwise save the next entry path
    // and return true. The path is relative against the directory being
    // traversed and contains a trailing separator for sub-directories. Throw
    // std::system_error in case of a failure (insufficient permissions,
    // dangling symlink encountered, etc).
    //
    bool
    next (path& p)
    {
      if (iters_.empty ())
        return false;

      auto& i (iters_.back ());

      // If we got to the end of directory sub-entries, then go one level up
      // and return this directory path.
      //
      if (i.first == dir_iterator ())
      {
        path d (move (i.second));
        iters_.pop_back ();

        // Return the path unless it is the last one (the directory we started
        // to iterate from) and the self flag is not set.
        //
        if (iters_.empty () && !self_)
          return false;

        p = move (d);
        return true;
      }

      const dir_entry& de (*i.first);

      // Append separator if a directory. Note that dir_entry::type() can
      // throw.
      //
      entry_type et (follow_symlinks_ ? de.type () : de.ltype ());
      path pe (et == entry_type::directory
               ? path_cast<dir_path> (i.second / de.path ())
               : i.second / de.path ());

      ++i.first;

      if (recursive_ && pe.to_directory ())
      {
        open (path_cast<dir_path> (move (pe)), true);
        return next (p);
      }

      p = move (pe);
      return true;
    }

  private:
    void
    open (dir_path p, bool preopen)
    {
      // We should consider a racing condition here. The directory can be
      // removed before we create an iterator for it. In this case we just do
      // nothing, so the directory is silently skipped.
      //
      try
      {
        // If preopen_() returns false, then the directory will not be
        // traversed (since we leave iterator with end semantics) but still be
        // returned by the next() call as a sub-entry.
        //
        dir_iterator i;
        if (!preopen || preopen_ (p))
        {
          dir_path d (start_ / p);

          // If we follow symlinks, then we ignore the dangling ones.
          //
          i = dir_iterator (!d.empty () ? d : dir_path ("."),
                            follow_symlinks_);
        }

        iters_.emplace_back (move (i), move (p));
      }
      catch (const system_error& e)
      {
        // Ignore non-existent directory (ENOENT or ENOTDIR). Rethrow for any
        // other error. We consider ENOTDIR as a variety of removal, with a
        // new filesystem entry being created afterwards.
        //
        // Make sure that the error denotes errno portable code.
        //
        assert (e.code ().category () == generic_category ());

        int ec (e.code ().value ());
        if (ec != ENOENT && ec != ENOTDIR)
          throw;
      }
    }

  private:
    dir_path start_;
    bool recursive_;
    bool self_;
    bool follow_symlinks_;
    preopen preopen_;
    small_vector<pair<dir_iterator, dir_path>, 1> iters_;
  };

  // Provide an access to the real filesystem.
  //
  class real_filesystem: public filesystem_base
  {
  public:
    using iterator_type = recursive_dir_iterator;

    real_filesystem (const dir_path& start): filesystem_base (start) {}

    pair<bool, entry_stat>
    path_entry (const path& p, bool follow_symlinks) const
    {
      return butl::path_entry (start_ / p, follow_symlinks);
    }

    iterator_type
    iterator (const dir_path& p,
              bool recursive,
              bool self,
              bool follow_symlinks,
              preopen po) const
    {
      return iterator_type (start_ / p,
                            recursive,
                            self,
                            follow_symlinks,
                            move (po));
    }
  };

  void
  path_search (
    const path& pattern,
    const function<bool (path&&, const string& pattern, bool interm)>& func,
    const dir_path& start,
    path_match_flags flags)
  {
    real_filesystem fs (pattern.relative () ? start : empty_dir);
    search (pattern, dir_path (), flags, func, fs);
  }

  // Search path in the directory tree represented by a path.
  //
  // Iterate over path prefixes, as recursive_dir_iterator (see above) would
  // iterate over the real directory tree.
  //
  class path_iterator
  {
  public:
    path_iterator (path p, bool recursive, bool self, preopen po)
        : path_ (move (p)),
          recursive_ (recursive),
          self_ (self),
          preopen_ (move (po)),
          iter_ (path_.begin ())
    {
      open (dir_path (), self_);
    }

    // Behave as recursive_dir_iterator (see above) would do if iterating over
    // non-existent directory. Note that this behavior differs from that for
    // an empty directory (previous ctor being called with an empty path). If
    // self flag is true, then, for the empty directory, the first next() call
    // returns true and saves empty path (self sub-entry). For non-existent
    // directory the first next() call returns false. Also note that
    // recursive_dir_iterator calls the preopen function before it becomes
    // known that the directory doesn't exist, and we emulate such a behavior
    // here as well.
    //
    path_iterator (bool self, preopen po)
        : self_ (false),
          iter_ (path_.begin ())
    {
      if (self)
        po (empty_dir);
    }

    // Move constructible-only, non-assignable type.
    //
    path_iterator (const path_iterator&) = delete;
    path_iterator& operator= (const path_iterator&) = delete;

    // Custom move ctor (properly moves path/iterator pair).
    //
    path_iterator (path_iterator&& pi)
        : path_ (move (pi.path_)),
          recursive_ (pi.recursive_),
          self_ (pi.self_),
          preopen_ (move (pi.preopen_)),
          iter_ (path_, pi.iter_) {}

    // Return false if no more entries left. Otherwise save the next entry path
    // and return true.
    //
    bool
    next (path& p)
    {
      if (iter_ == path_.begin ())
      {
        if (!self_)
          return false;

        p = path ();
        self_ = false; // To bail out the next time.
        return true;
      }

      path pe (path_.begin (), iter_);
      if (recursive_ && pe.to_directory ())
      {
        open (path_cast<dir_path> (move (pe)), true);
        return next (p);
      }

      --iter_; // Return one level up.

      p = move (pe);
      return true;
    }

  private:
    void
    open (const dir_path& p, bool preopen)
    {
      // If preopen_() returns false, then the directory will not be
      // traversed (since we reset the recursive flag) but still be returned
      // by the next() call as a sub-entry.
      //
      if (preopen && !preopen_ (p))
        recursive_ = false;
      else if (iter_ != path_.end ())
        ++iter_;

      // If the rightmost component is reached, then all the directories were
      // traversed, so we reset the recursive flag.
      //
      if (iter_ == path_.end ())
        recursive_ = false;
    }

  private:
    path path_;
    bool recursive_;
    bool self_;
    preopen preopen_;
    path::iterator iter_;
  };

  // Provide an access to a directory tree, that is represented by the path.
  //
  // Note that symlinks are meaningless for this filesystem.
  //
  class path_filesystem: public filesystem_base
  {
  public:
    using iterator_type = path_iterator;

    path_filesystem (const dir_path& start, const path& p)
        : filesystem_base (start),
          path_ (p) {}

    pair<bool, entry_stat>
    path_entry (const path& p, bool /*follow_symlinks*/)
    {
      // If path and sub-path are non-empty, and both are absolute or relative,
      // then no extra effort is required (prior to checking if one is a
      // sub-path or the other). Otherwise we complete the relative paths
      // first.
      //
      auto path_entry = [] (const path& p, const path& pe)
      {
        // Note that paths are not required to be normalized, so we just check
        // that one path is a literal prefix of the other one.
        //
        if (!p.sub (pe))
          return make_pair (false, entry_stat {entry_type::unknown, 0});

        entry_type t (pe == p && !p.to_directory ()
                      ? entry_type::regular
                      : entry_type::directory);

        return make_pair (true, entry_stat {t, 0});
      };

      if (path_.relative () == p.relative () && !path_.empty () && !p.empty ())
        return path_entry (path_, p);

      return path_entry (path_.absolute () ? path_ : complete (path_),
                         p.absolute () ? p : complete (p));
    }

    iterator_type
    iterator (const dir_path& p,
              bool recursive,
              bool self,
              bool /*follow_symlinks*/,
              preopen po)
    {
      // If path and sub-path are non-empty, and both are absolute or relative,
      // then no extra effort is required (prior to checking if one is a
      // sub-path or the other). Otherwise we complete the relative paths
      // first.
      //
      auto iterator = [recursive, self, &po] (const path& p,
                                              const dir_path& pe)
      {
        // If the directory we should iterate belongs to the directory tree,
        // then return the corresponding leaf path iterator. Otherwise return
        // the non-existent directory iterator (returns false on the first
        // next() call).
        //
        return p.sub (pe)
          ? iterator_type (p.leaf (pe), recursive, self, move (po))
          : iterator_type (self, move (po));
      };

      if (path_.relative () == p.relative () && !path_.empty () && !p.empty ())
        return iterator (path_, p);

      return iterator (path_.absolute () ? path_ : complete (path_),
                       p.absolute () ? p : path_cast<dir_path> (complete (p)));
    }

  private:
    // Complete the relative path.
    //
    path
    complete (const path& p)
    {
      assert (p.relative ());

      if (start_.absolute ())
        return start_ / p;

      if (current_.empty ())
        current_ = dir_path::current_directory ();

      return !start_.empty ()
        ? current_ / start_ / p
        : current_ / p;
    }

  private:
    const path& path_;
  };

  void
  path_search (
    const path& pattern,
    const path& entry,
    const function<bool (path&&, const string& pattern, bool interm)>& func,
    const dir_path& start,
    path_match_flags flags)
  {
    path_filesystem fs (start, entry);
    search (pattern, dir_path (), flags, func, fs);
  }

  bool
  path_match (const path& pattern,
              const path& entry,
              const dir_path& start,
              path_match_flags flags)
  {
    bool r (false);

    auto match = [&entry, &r] (path&& p, const string&, bool interim)
    {
      // If we found the entry (possibly through one of the recursive
      // components) no need to search further.
      //
      if (p == entry && !interim)
      {
        r = true;
        return false;
      }

      return true;
    };

    path_search (pattern, entry, match, start, flags);
    return r;
  }

  // path_pattern_iterator
  //
  void path_pattern_iterator::
  next ()
  {
    if (i_ == e_)
    {
      t_ = nullopt; // Convert the object into the end iterator.
      return;
    }

    auto next = [this] (path_pattern_term_type t)
    {
      assert (t != path_pattern_term_type::bracket);

      t_ = path_pattern_term {t, i_, i_ + 1};
      ++i_;
    };

    switch (*i_)
    {
    case '?':
      {
        next (path_pattern_term_type::question);
        break;
      }
    case '*':
      {
        next (path_pattern_term_type::star);
        break;
      }
    case '[':
      {
        // Try to find the bracket expression end.
        //
        // Note that '[' doesn't necessarily starts the bracket expression (no
        // closing bracket, empty, etc). If that's the case, then we end up
        // with the '[' literal terminal.
        //
        bool expr (false);
        for (;;) // Breakout loop.
        {
          string::const_iterator i (i_ + 1); // Position after '['.

          if (i == e_) // Is '[' the pattern last character?
            break;

          bool invert (*i == '!');
          if (invert && ++i == e_) // Is '!' the pattern last character?
            break;

          // Find the bracket expression end.
          //
          // Note that the bracket expression may not be empty and ']' is a
          // literal if it is the first expression character.
          //
          for (++i; i != e_ && *i != ']'; ++i) ;

          if (i == e_) // The closing bracket is not found?
            break;

          expr = true;

          ++i; // Position after ']'.

          t_ = path_pattern_term {path_pattern_term_type::bracket, i_, i};

          i_ = i;
          break;
        }

        // Fallback to '[' literal if it is not a bracket expression.
        //
        if (expr)
          break;
      }
      // Fall through.
    default:
      {
        next (path_pattern_term_type::literal);
      }
    }
  }
}