reference, declarationdefinition
definition → references, declarations, derived classes, virtual overrides
reference to multiple definitions → definitions
unreferenced
    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
//===- unittests/Support/VirtualFileSystem.cpp -------------- VFS tests ---===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/VirtualFileSystem.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SourceMgr.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include <map>
#include <string>

using namespace llvm;
using llvm::sys::fs::UniqueID;
using testing::ElementsAre;
using testing::Pair;
using testing::UnorderedElementsAre;

namespace {
struct DummyFile : public vfs::File {
  vfs::Status S;
  explicit DummyFile(vfs::Status S) : S(S) {}
  llvm::ErrorOr<vfs::Status> status() override { return S; }
  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
  getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
            bool IsVolatile) override {
    llvm_unreachable("unimplemented");
  }
  std::error_code close() override { return std::error_code(); }
};

class DummyFileSystem : public vfs::FileSystem {
  int FSID;   // used to produce UniqueIDs
  int FileID; // used to produce UniqueIDs
  std::map<std::string, vfs::Status> FilesAndDirs;

  static int getNextFSID() {
    static int Count = 0;
    return Count++;
  }

public:
  DummyFileSystem() : FSID(getNextFSID()), FileID(0) {}

  ErrorOr<vfs::Status> status(const Twine &Path) override {
    std::map<std::string, vfs::Status>::iterator I =
        FilesAndDirs.find(Path.str());
    if (I == FilesAndDirs.end())
      return make_error_code(llvm::errc::no_such_file_or_directory);
    return I->second;
  }
  ErrorOr<std::unique_ptr<vfs::File>>
  openFileForRead(const Twine &Path) override {
    auto S = status(Path);
    if (S)
      return std::unique_ptr<vfs::File>(new DummyFile{*S});
    return S.getError();
  }
  llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
    return std::string();
  }
  std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
    return std::error_code();
  }
  // Map any symlink to "/symlink".
  std::error_code getRealPath(const Twine &Path,
                              SmallVectorImpl<char> &Output) const override {
    auto I = FilesAndDirs.find(Path.str());
    if (I == FilesAndDirs.end())
      return make_error_code(llvm::errc::no_such_file_or_directory);
    if (I->second.isSymlink()) {
      Output.clear();
      Twine("/symlink").toVector(Output);
      return std::error_code();
    }
    Output.clear();
    Path.toVector(Output);
    return std::error_code();
  }

  struct DirIterImpl : public llvm::vfs::detail::DirIterImpl {
    std::map<std::string, vfs::Status> &FilesAndDirs;
    std::map<std::string, vfs::Status>::iterator I;
    std::string Path;
    bool isInPath(StringRef S) {
      if (Path.size() < S.size() && S.find(Path) == 0) {
        auto LastSep = S.find_last_of('/');
        if (LastSep == Path.size() || LastSep == Path.size() - 1)
          return true;
      }
      return false;
    }
    DirIterImpl(std::map<std::string, vfs::Status> &FilesAndDirs,
                const Twine &_Path)
        : FilesAndDirs(FilesAndDirs), I(FilesAndDirs.begin()),
          Path(_Path.str()) {
      for (; I != FilesAndDirs.end(); ++I) {
        if (isInPath(I->first)) {
          CurrentEntry =
              vfs::directory_entry(I->second.getName(), I->second.getType());
          break;
        }
      }
    }
    std::error_code increment() override {
      ++I;
      for (; I != FilesAndDirs.end(); ++I) {
        if (isInPath(I->first)) {
          CurrentEntry =
              vfs::directory_entry(I->second.getName(), I->second.getType());
          break;
        }
      }
      if (I == FilesAndDirs.end())
        CurrentEntry = vfs::directory_entry();
      return std::error_code();
    }
  };

  vfs::directory_iterator dir_begin(const Twine &Dir,
                                    std::error_code &EC) override {
    return vfs::directory_iterator(
        std::make_shared<DirIterImpl>(FilesAndDirs, Dir));
  }

  void addEntry(StringRef Path, const vfs::Status &Status) {
    FilesAndDirs[Path] = Status;
  }

  void addRegularFile(StringRef Path, sys::fs::perms Perms = sys::fs::all_all) {
    vfs::Status S(Path, UniqueID(FSID, FileID++),
                  std::chrono::system_clock::now(), 0, 0, 1024,
                  sys::fs::file_type::regular_file, Perms);
    addEntry(Path, S);
  }

  void addDirectory(StringRef Path, sys::fs::perms Perms = sys::fs::all_all) {
    vfs::Status S(Path, UniqueID(FSID, FileID++),
                  std::chrono::system_clock::now(), 0, 0, 0,
                  sys::fs::file_type::directory_file, Perms);
    addEntry(Path, S);
  }

  void addSymlink(StringRef Path) {
    vfs::Status S(Path, UniqueID(FSID, FileID++),
                  std::chrono::system_clock::now(), 0, 0, 0,
                  sys::fs::file_type::symlink_file, sys::fs::all_all);
    addEntry(Path, S);
  }
};

/// Replace back-slashes by front-slashes.
std::string getPosixPath(std::string S) {
  SmallString<128> Result;
  llvm::sys::path::native(S, Result, llvm::sys::path::Style::posix);
  return Result.str();
}
} // end anonymous namespace

TEST(VirtualFileSystemTest, StatusQueries) {
  IntrusiveRefCntPtr<DummyFileSystem> D(new DummyFileSystem());
  ErrorOr<vfs::Status> Status((std::error_code()));

  D->addRegularFile("/foo");
  Status = D->status("/foo");
  ASSERT_FALSE(Status.getError());
  EXPECT_TRUE(Status->isStatusKnown());
  EXPECT_FALSE(Status->isDirectory());
  EXPECT_TRUE(Status->isRegularFile());
  EXPECT_FALSE(Status->isSymlink());
  EXPECT_FALSE(Status->isOther());
  EXPECT_TRUE(Status->exists());

  D->addDirectory("/bar");
  Status = D->status("/bar");
  ASSERT_FALSE(Status.getError());
  EXPECT_TRUE(Status->isStatusKnown());
  EXPECT_TRUE(Status->isDirectory());
  EXPECT_FALSE(Status->isRegularFile());
  EXPECT_FALSE(Status->isSymlink());
  EXPECT_FALSE(Status->isOther());
  EXPECT_TRUE(Status->exists());

  D->addSymlink("/baz");
  Status = D->status("/baz");
  ASSERT_FALSE(Status.getError());
  EXPECT_TRUE(Status->isStatusKnown());
  EXPECT_FALSE(Status->isDirectory());
  EXPECT_FALSE(Status->isRegularFile());
  EXPECT_TRUE(Status->isSymlink());
  EXPECT_FALSE(Status->isOther());
  EXPECT_TRUE(Status->exists());

  EXPECT_TRUE(Status->equivalent(*Status));
  ErrorOr<vfs::Status> Status2 = D->status("/foo");
  ASSERT_FALSE(Status2.getError());
  EXPECT_FALSE(Status->equivalent(*Status2));
}

TEST(VirtualFileSystemTest, BaseOnlyOverlay) {
  IntrusiveRefCntPtr<DummyFileSystem> D(new DummyFileSystem());
  ErrorOr<vfs::Status> Status((std::error_code()));
  EXPECT_FALSE(Status = D->status("/foo"));

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(new vfs::OverlayFileSystem(D));
  EXPECT_FALSE(Status = O->status("/foo"));

  D->addRegularFile("/foo");
  Status = D->status("/foo");
  EXPECT_FALSE(Status.getError());

  ErrorOr<vfs::Status> Status2((std::error_code()));
  Status2 = O->status("/foo");
  EXPECT_FALSE(Status2.getError());
  EXPECT_TRUE(Status->equivalent(*Status2));
}

TEST(VirtualFileSystemTest, GetRealPathInOverlay) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("/foo");
  Lower->addSymlink("/lower_link");
  IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(Upper);

  // Regular file.
  SmallString<16> RealPath;
  EXPECT_FALSE(O->getRealPath("/foo", RealPath));
  EXPECT_EQ(RealPath.str(), "/foo");

  // Expect no error getting real path for symlink in lower overlay.
  EXPECT_FALSE(O->getRealPath("/lower_link", RealPath));
  EXPECT_EQ(RealPath.str(), "/symlink");

  // Try a non-existing link.
  EXPECT_EQ(O->getRealPath("/upper_link", RealPath),
            errc::no_such_file_or_directory);

  // Add a new symlink in upper.
  Upper->addSymlink("/upper_link");
  EXPECT_FALSE(O->getRealPath("/upper_link", RealPath));
  EXPECT_EQ(RealPath.str(), "/symlink");
}

TEST(VirtualFileSystemTest, OverlayFiles) {
  IntrusiveRefCntPtr<DummyFileSystem> Base(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Middle(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Top(new DummyFileSystem());
  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Base));
  O->pushOverlay(Middle);
  O->pushOverlay(Top);

  ErrorOr<vfs::Status> Status1((std::error_code())),
      Status2((std::error_code())), Status3((std::error_code())),
      StatusB((std::error_code())), StatusM((std::error_code())),
      StatusT((std::error_code()));

  Base->addRegularFile("/foo");
  StatusB = Base->status("/foo");
  ASSERT_FALSE(StatusB.getError());
  Status1 = O->status("/foo");
  ASSERT_FALSE(Status1.getError());
  Middle->addRegularFile("/foo");
  StatusM = Middle->status("/foo");
  ASSERT_FALSE(StatusM.getError());
  Status2 = O->status("/foo");
  ASSERT_FALSE(Status2.getError());
  Top->addRegularFile("/foo");
  StatusT = Top->status("/foo");
  ASSERT_FALSE(StatusT.getError());
  Status3 = O->status("/foo");
  ASSERT_FALSE(Status3.getError());

  EXPECT_TRUE(Status1->equivalent(*StatusB));
  EXPECT_TRUE(Status2->equivalent(*StatusM));
  EXPECT_TRUE(Status3->equivalent(*StatusT));

  EXPECT_FALSE(Status1->equivalent(*Status2));
  EXPECT_FALSE(Status2->equivalent(*Status3));
  EXPECT_FALSE(Status1->equivalent(*Status3));
}

TEST(VirtualFileSystemTest, OverlayDirsNonMerged) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(Upper);

  Lower->addDirectory("/lower-only");
  Upper->addDirectory("/upper-only");

  // non-merged paths should be the same
  ErrorOr<vfs::Status> Status1 = Lower->status("/lower-only");
  ASSERT_FALSE(Status1.getError());
  ErrorOr<vfs::Status> Status2 = O->status("/lower-only");
  ASSERT_FALSE(Status2.getError());
  EXPECT_TRUE(Status1->equivalent(*Status2));

  Status1 = Upper->status("/upper-only");
  ASSERT_FALSE(Status1.getError());
  Status2 = O->status("/upper-only");
  ASSERT_FALSE(Status2.getError());
  EXPECT_TRUE(Status1->equivalent(*Status2));
}

TEST(VirtualFileSystemTest, MergedDirPermissions) {
  // merged directories get the permissions of the upper dir
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(Upper);

  ErrorOr<vfs::Status> Status((std::error_code()));
  Lower->addDirectory("/both", sys::fs::owner_read);
  Upper->addDirectory("/both", sys::fs::owner_all | sys::fs::group_read);
  Status = O->status("/both");
  ASSERT_FALSE(Status.getError());
  EXPECT_EQ(0740, Status->getPermissions());

  // permissions (as usual) are not recursively applied
  Lower->addRegularFile("/both/foo", sys::fs::owner_read);
  Upper->addRegularFile("/both/bar", sys::fs::owner_write);
  Status = O->status("/both/foo");
  ASSERT_FALSE(Status.getError());
  EXPECT_EQ(0400, Status->getPermissions());
  Status = O->status("/both/bar");
  ASSERT_FALSE(Status.getError());
  EXPECT_EQ(0200, Status->getPermissions());
}

TEST(VirtualFileSystemTest, OverlayIterator) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("/foo");
  IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(Upper);

  ErrorOr<vfs::Status> Status((std::error_code()));
  {
    auto it = O->overlays_begin();
    auto end = O->overlays_end();

    EXPECT_NE(it, end);

    Status = (*it)->status("/foo");
    ASSERT_TRUE(Status.getError());

    it++;
    EXPECT_NE(it, end);

    Status = (*it)->status("/foo");
    ASSERT_FALSE(Status.getError());
    EXPECT_TRUE(Status->exists());

    it++;
    EXPECT_EQ(it, end);
  }

  {
    auto it = O->overlays_rbegin();
    auto end = O->overlays_rend();

    EXPECT_NE(it, end);

    Status = (*it)->status("/foo");
    ASSERT_FALSE(Status.getError());
    EXPECT_TRUE(Status->exists());

    it++;
    EXPECT_NE(it, end);

    Status = (*it)->status("/foo");
    ASSERT_TRUE(Status.getError());

    it++;
    EXPECT_EQ(it, end);
  }
}

namespace {
struct ScopedDir {
  SmallString<128> Path;
  ScopedDir(const Twine &Name, bool Unique = false) {
    std::error_code EC;
    if (Unique) {
      EC = llvm::sys::fs::createUniqueDirectory(Name, Path);
      if (!EC) {
        // Resolve any symlinks in the new directory.
        std::string UnresolvedPath = Path.str();
        EC = llvm::sys::fs::real_path(UnresolvedPath, Path);
      }
    } else {
      Path = Name.str();
      EC = llvm::sys::fs::create_directory(Twine(Path));
    }
    if (EC)
      Path = "";
    EXPECT_FALSE(EC) << EC.message();
  }
  ~ScopedDir() {
    if (Path != "") {
      EXPECT_FALSE(llvm::sys::fs::remove(Path.str()));
    }
  }
  operator StringRef() { return Path.str(); }
};

struct ScopedLink {
  SmallString<128> Path;
  ScopedLink(const Twine &To, const Twine &From) {
    Path = From.str();
    std::error_code EC = sys::fs::create_link(To, From);
    if (EC)
      Path = "";
    EXPECT_FALSE(EC);
  }
  ~ScopedLink() {
    if (Path != "") {
      EXPECT_FALSE(llvm::sys::fs::remove(Path.str()));
    }
  }
  operator StringRef() { return Path.str(); }
};

struct ScopedFile {
  SmallString<128> Path;
  ScopedFile(const Twine &Path, StringRef Contents) {
    Path.toVector(this->Path);
    std::error_code EC;
    raw_fd_ostream OS(this->Path, EC);
    EXPECT_FALSE(EC);
    OS << Contents;
    OS.flush();
    EXPECT_FALSE(OS.error());
    if (EC || OS.error())
      this->Path = "";
  }
  ~ScopedFile() {
    if (Path != "") {
      EXPECT_FALSE(llvm::sys::fs::remove(Path.str()));
    }
  }
};
} // end anonymous namespace

TEST(VirtualFileSystemTest, BasicRealFSIteration) {
  ScopedDir TestDirectory("virtual-file-system-test", /*Unique*/ true);
  IntrusiveRefCntPtr<vfs::FileSystem> FS = vfs::getRealFileSystem();

  std::error_code EC;
  vfs::directory_iterator I = FS->dir_begin(Twine(TestDirectory), EC);
  ASSERT_FALSE(EC);
  EXPECT_EQ(vfs::directory_iterator(), I); // empty directory is empty

  ScopedDir _a(TestDirectory + "/a");
  ScopedDir _ab(TestDirectory + "/a/b");
  ScopedDir _c(TestDirectory + "/c");
  ScopedDir _cd(TestDirectory + "/c/d");

  I = FS->dir_begin(Twine(TestDirectory), EC);
  ASSERT_FALSE(EC);
  ASSERT_NE(vfs::directory_iterator(), I);
  // Check either a or c, since we can't rely on the iteration order.
  EXPECT_TRUE(I->path().endswith("a") || I->path().endswith("c"));
  I.increment(EC);
  ASSERT_FALSE(EC);
  ASSERT_NE(vfs::directory_iterator(), I);
  EXPECT_TRUE(I->path().endswith("a") || I->path().endswith("c"));
  I.increment(EC);
  EXPECT_EQ(vfs::directory_iterator(), I);
}

#ifdef LLVM_ON_UNIX
TEST(VirtualFileSystemTest, MultipleWorkingDirs) {
  // Our root contains a/aa, b/bb, c, where c is a link to a/.
  // Run tests both in root/b/ and root/c/ (to test "normal" and symlink dirs).
  // Interleave operations to show the working directories are independent.
  ScopedDir Root("r", true), ADir(Root.Path + "/a"), BDir(Root.Path + "/b");
  ScopedLink C(ADir.Path, Root.Path + "/c");
  ScopedFile AA(ADir.Path + "/aa", "aaaa"), BB(BDir.Path + "/bb", "bbbb");
  std::unique_ptr<vfs::FileSystem> BFS = vfs::createPhysicalFileSystem(),
                                   CFS = vfs::createPhysicalFileSystem();

  ASSERT_FALSE(BFS->setCurrentWorkingDirectory(BDir.Path));
  ASSERT_FALSE(CFS->setCurrentWorkingDirectory(C.Path));
  EXPECT_EQ(BDir.Path, *BFS->getCurrentWorkingDirectory());
  EXPECT_EQ(C.Path, *CFS->getCurrentWorkingDirectory());

  // openFileForRead(), indirectly.
  auto BBuf = BFS->getBufferForFile("bb");
  ASSERT_TRUE(BBuf);
  EXPECT_EQ("bbbb", (*BBuf)->getBuffer());

  auto ABuf = CFS->getBufferForFile("aa");
  ASSERT_TRUE(ABuf);
  EXPECT_EQ("aaaa", (*ABuf)->getBuffer());

  // status()
  auto BStat = BFS->status("bb");
  ASSERT_TRUE(BStat);
  EXPECT_EQ("bb", BStat->getName());

  auto AStat = CFS->status("aa");
  ASSERT_TRUE(AStat);
  EXPECT_EQ("aa", AStat->getName()); // unresolved name

  // getRealPath()
  SmallString<128> BPath;
  ASSERT_FALSE(BFS->getRealPath("bb", BPath));
  EXPECT_EQ(BB.Path, BPath);

  SmallString<128> APath;
  ASSERT_FALSE(CFS->getRealPath("aa", APath));
  EXPECT_EQ(AA.Path, APath); // Reports resolved name.

  // dir_begin
  std::error_code EC;
  auto BIt = BFS->dir_begin(".", EC);
  ASSERT_FALSE(EC);
  ASSERT_NE(BIt, vfs::directory_iterator());
  EXPECT_EQ((BDir.Path + "/./bb").str(), BIt->path());
  BIt.increment(EC);
  ASSERT_FALSE(EC);
  ASSERT_EQ(BIt, vfs::directory_iterator());

  auto CIt = CFS->dir_begin(".", EC);
  ASSERT_FALSE(EC);
  ASSERT_NE(CIt, vfs::directory_iterator());
  EXPECT_EQ((ADir.Path + "/./aa").str(), CIt->path()); // Partly resolved name!
  CIt.increment(EC); // Because likely to read through this path.
  ASSERT_FALSE(EC);
  ASSERT_EQ(CIt, vfs::directory_iterator());
}

TEST(VirtualFileSystemTest, BrokenSymlinkRealFSIteration) {
  ScopedDir TestDirectory("virtual-file-system-test", /*Unique*/ true);
  IntrusiveRefCntPtr<vfs::FileSystem> FS = vfs::getRealFileSystem();

  ScopedLink _a("no_such_file", TestDirectory + "/a");
  ScopedDir _b(TestDirectory + "/b");
  ScopedLink _c("no_such_file", TestDirectory + "/c");

  // Should get no iteration error, but a stat error for the broken symlinks.
  std::map<std::string, std::error_code> StatResults;
  std::error_code EC;
  for (vfs::directory_iterator I = FS->dir_begin(Twine(TestDirectory), EC), E;
       I != E; I.increment(EC)) {
    EXPECT_FALSE(EC);
    StatResults[sys::path::filename(I->path())] =
        FS->status(I->path()).getError();
  }
  EXPECT_THAT(
      StatResults,
      ElementsAre(
          Pair("a", std::make_error_code(std::errc::no_such_file_or_directory)),
          Pair("b", std::error_code()),
          Pair("c",
               std::make_error_code(std::errc::no_such_file_or_directory))));
}
#endif

TEST(VirtualFileSystemTest, BasicRealFSRecursiveIteration) {
  ScopedDir TestDirectory("virtual-file-system-test", /*Unique*/ true);
  IntrusiveRefCntPtr<vfs::FileSystem> FS = vfs::getRealFileSystem();

  std::error_code EC;
  auto I = vfs::recursive_directory_iterator(*FS, Twine(TestDirectory), EC);
  ASSERT_FALSE(EC);
  EXPECT_EQ(vfs::recursive_directory_iterator(), I); // empty directory is empty

  ScopedDir _a(TestDirectory + "/a");
  ScopedDir _ab(TestDirectory + "/a/b");
  ScopedDir _c(TestDirectory + "/c");
  ScopedDir _cd(TestDirectory + "/c/d");

  I = vfs::recursive_directory_iterator(*FS, Twine(TestDirectory), EC);
  ASSERT_FALSE(EC);
  ASSERT_NE(vfs::recursive_directory_iterator(), I);

  std::vector<std::string> Contents;
  for (auto E = vfs::recursive_directory_iterator(); !EC && I != E;
       I.increment(EC)) {
    Contents.push_back(I->path());
  }

  // Check contents, which may be in any order
  EXPECT_EQ(4U, Contents.size());
  int Counts[4] = {0, 0, 0, 0};
  for (const std::string &Name : Contents) {
    ASSERT_FALSE(Name.empty());
    int Index = Name[Name.size() - 1] - 'a';
    ASSERT_TRUE(Index >= 0 && Index < 4);
    Counts[Index]++;
  }
  EXPECT_EQ(1, Counts[0]); // a
  EXPECT_EQ(1, Counts[1]); // b
  EXPECT_EQ(1, Counts[2]); // c
  EXPECT_EQ(1, Counts[3]); // d
}

TEST(VirtualFileSystemTest, BasicRealFSRecursiveIterationNoPush) {
  ScopedDir TestDirectory("virtual-file-system-test", /*Unique*/ true);

  ScopedDir _a(TestDirectory + "/a");
  ScopedDir _ab(TestDirectory + "/a/b");
  ScopedDir _c(TestDirectory + "/c");
  ScopedDir _cd(TestDirectory + "/c/d");
  ScopedDir _e(TestDirectory + "/e");
  ScopedDir _ef(TestDirectory + "/e/f");
  ScopedDir _g(TestDirectory + "/g");

  IntrusiveRefCntPtr<vfs::FileSystem> FS = vfs::getRealFileSystem();

  // Test that calling no_push on entries without subdirectories has no effect.
  {
    std::error_code EC;
    auto I = vfs::recursive_directory_iterator(*FS, Twine(TestDirectory), EC);
    ASSERT_FALSE(EC);

    std::vector<std::string> Contents;
    for (auto E = vfs::recursive_directory_iterator(); !EC && I != E;
         I.increment(EC)) {
      Contents.push_back(I->path());
      char last = I->path().back();
      switch (last) {
      case 'b':
      case 'd':
      case 'f':
      case 'g':
        I.no_push();
        break;
      default:
        break;
      }
    }
    EXPECT_EQ(7U, Contents.size());
  }

  // Test that calling no_push skips subdirectories.
  {
    std::error_code EC;
    auto I = vfs::recursive_directory_iterator(*FS, Twine(TestDirectory), EC);
    ASSERT_FALSE(EC);

    std::vector<std::string> Contents;
    for (auto E = vfs::recursive_directory_iterator(); !EC && I != E;
         I.increment(EC)) {
      Contents.push_back(I->path());
      char last = I->path().back();
      switch (last) {
      case 'a':
      case 'c':
      case 'e':
        I.no_push();
        break;
      default:
        break;
      }
    }

    // Check contents, which may be in any order
    EXPECT_EQ(4U, Contents.size());
    int Counts[7] = {0, 0, 0, 0, 0, 0, 0};
    for (const std::string &Name : Contents) {
      ASSERT_FALSE(Name.empty());
      int Index = Name[Name.size() - 1] - 'a';
      ASSERT_TRUE(Index >= 0 && Index < 7);
      Counts[Index]++;
    }
    EXPECT_EQ(1, Counts[0]); // a
    EXPECT_EQ(0, Counts[1]); // b
    EXPECT_EQ(1, Counts[2]); // c
    EXPECT_EQ(0, Counts[3]); // d
    EXPECT_EQ(1, Counts[4]); // e
    EXPECT_EQ(0, Counts[5]); // f
    EXPECT_EQ(1, Counts[6]); // g
  }
}

#ifdef LLVM_ON_UNIX
TEST(VirtualFileSystemTest, BrokenSymlinkRealFSRecursiveIteration) {
  ScopedDir TestDirectory("virtual-file-system-test", /*Unique*/ true);
  IntrusiveRefCntPtr<vfs::FileSystem> FS = vfs::getRealFileSystem();

  ScopedLink _a("no_such_file", TestDirectory + "/a");
  ScopedDir _b(TestDirectory + "/b");
  ScopedLink _ba("no_such_file", TestDirectory + "/b/a");
  ScopedDir _bb(TestDirectory + "/b/b");
  ScopedLink _bc("no_such_file", TestDirectory + "/b/c");
  ScopedLink _c("no_such_file", TestDirectory + "/c");
  ScopedDir _d(TestDirectory + "/d");
  ScopedDir _dd(TestDirectory + "/d/d");
  ScopedDir _ddd(TestDirectory + "/d/d/d");
  ScopedLink _e("no_such_file", TestDirectory + "/e");

  std::vector<std::string> VisitedBrokenSymlinks;
  std::vector<std::string> VisitedNonBrokenSymlinks;
  std::error_code EC;
  for (vfs::recursive_directory_iterator I(*FS, Twine(TestDirectory), EC), E;
       I != E; I.increment(EC)) {
    EXPECT_FALSE(EC);
    (FS->status(I->path()) ? VisitedNonBrokenSymlinks : VisitedBrokenSymlinks)
        .push_back(I->path());
  }

  // Check visited file names.
  EXPECT_THAT(VisitedBrokenSymlinks,
              UnorderedElementsAre(StringRef(_a), StringRef(_ba),
                                   StringRef(_bc), StringRef(_c),
                                   StringRef(_e)));
  EXPECT_THAT(VisitedNonBrokenSymlinks,
              UnorderedElementsAre(StringRef(_b), StringRef(_bb), StringRef(_d),
                                   StringRef(_dd), StringRef(_ddd)));
}
#endif

template <typename DirIter>
static void checkContents(DirIter I, ArrayRef<StringRef> ExpectedOut) {
  std::error_code EC;
  SmallVector<StringRef, 4> Expected(ExpectedOut.begin(), ExpectedOut.end());
  SmallVector<std::string, 4> InputToCheck;

  // Do not rely on iteration order to check for contents, sort both
  // content vectors before comparison.
  for (DirIter E; !EC && I != E; I.increment(EC))
    InputToCheck.push_back(I->path());

  llvm::sort(InputToCheck);
  llvm::sort(Expected);
  EXPECT_EQ(InputToCheck.size(), Expected.size());

  unsigned LastElt = std::min(InputToCheck.size(), Expected.size());
  for (unsigned Idx = 0; Idx != LastElt; ++Idx)
    EXPECT_EQ(StringRef(InputToCheck[Idx]), Expected[Idx]);
}

TEST(VirtualFileSystemTest, OverlayIteration) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(Upper);

  std::error_code EC;
  checkContents(O->dir_begin("/", EC), ArrayRef<StringRef>());

  Lower->addRegularFile("/file1");
  checkContents(O->dir_begin("/", EC), ArrayRef<StringRef>("/file1"));

  Upper->addRegularFile("/file2");
  checkContents(O->dir_begin("/", EC), {"/file2", "/file1"});

  Lower->addDirectory("/dir1");
  Lower->addRegularFile("/dir1/foo");
  Upper->addDirectory("/dir2");
  Upper->addRegularFile("/dir2/foo");
  checkContents(O->dir_begin("/dir2", EC), ArrayRef<StringRef>("/dir2/foo"));
  checkContents(O->dir_begin("/", EC), {"/dir2", "/file2", "/dir1", "/file1"});
}

TEST(VirtualFileSystemTest, OverlayRecursiveIteration) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Middle(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(Middle);
  O->pushOverlay(Upper);

  std::error_code EC;
  checkContents(vfs::recursive_directory_iterator(*O, "/", EC),
                ArrayRef<StringRef>());

  Lower->addRegularFile("/file1");
  checkContents(vfs::recursive_directory_iterator(*O, "/", EC),
                ArrayRef<StringRef>("/file1"));

  Upper->addDirectory("/dir");
  Upper->addRegularFile("/dir/file2");
  checkContents(vfs::recursive_directory_iterator(*O, "/", EC),
                {"/dir", "/dir/file2", "/file1"});

  Lower->addDirectory("/dir1");
  Lower->addRegularFile("/dir1/foo");
  Lower->addDirectory("/dir1/a");
  Lower->addRegularFile("/dir1/a/b");
  Middle->addDirectory("/a");
  Middle->addDirectory("/a/b");
  Middle->addDirectory("/a/b/c");
  Middle->addRegularFile("/a/b/c/d");
  Middle->addRegularFile("/hiddenByUp");
  Upper->addDirectory("/dir2");
  Upper->addRegularFile("/dir2/foo");
  Upper->addRegularFile("/hiddenByUp");
  checkContents(vfs::recursive_directory_iterator(*O, "/dir2", EC),
                ArrayRef<StringRef>("/dir2/foo"));
  checkContents(vfs::recursive_directory_iterator(*O, "/", EC),
                {"/dir", "/dir/file2", "/dir2", "/dir2/foo", "/hiddenByUp",
                 "/a", "/a/b", "/a/b/c", "/a/b/c/d", "/dir1", "/dir1/a",
                 "/dir1/a/b", "/dir1/foo", "/file1"});
}

TEST(VirtualFileSystemTest, ThreeLevelIteration) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Middle(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(Middle);
  O->pushOverlay(Upper);

  std::error_code EC;
  checkContents(O->dir_begin("/", EC), ArrayRef<StringRef>());

  Middle->addRegularFile("/file2");
  checkContents(O->dir_begin("/", EC), ArrayRef<StringRef>("/file2"));

  Lower->addRegularFile("/file1");
  Upper->addRegularFile("/file3");
  checkContents(O->dir_begin("/", EC), {"/file3", "/file2", "/file1"});
}

TEST(VirtualFileSystemTest, HiddenInIteration) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Middle(new DummyFileSystem());
  IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(Middle);
  O->pushOverlay(Upper);

  std::error_code EC;
  Lower->addRegularFile("/onlyInLow");
  Lower->addDirectory("/hiddenByMid");
  Lower->addDirectory("/hiddenByUp");
  Middle->addRegularFile("/onlyInMid");
  Middle->addRegularFile("/hiddenByMid");
  Middle->addDirectory("/hiddenByUp");
  Upper->addRegularFile("/onlyInUp");
  Upper->addRegularFile("/hiddenByUp");
  checkContents(
      O->dir_begin("/", EC),
      {"/hiddenByUp", "/onlyInUp", "/hiddenByMid", "/onlyInMid", "/onlyInLow"});

  // Make sure we get the top-most entry
  {
    std::error_code EC;
    vfs::directory_iterator I = O->dir_begin("/", EC), E;
    for (; !EC && I != E; I.increment(EC))
      if (I->path() == "/hiddenByUp")
        break;
    ASSERT_NE(E, I);
    EXPECT_EQ(sys::fs::file_type::regular_file, I->type());
  }
  {
    std::error_code EC;
    vfs::directory_iterator I = O->dir_begin("/", EC), E;
    for (; !EC && I != E; I.increment(EC))
      if (I->path() == "/hiddenByMid")
        break;
    ASSERT_NE(E, I);
    EXPECT_EQ(sys::fs::file_type::regular_file, I->type());
  }
}

TEST(ProxyFileSystemTest, Basic) {
  IntrusiveRefCntPtr<vfs::InMemoryFileSystem> Base(
      new vfs::InMemoryFileSystem());
  vfs::ProxyFileSystem PFS(Base);

  Base->addFile("/a", 0, MemoryBuffer::getMemBuffer("test"));

  auto Stat = PFS.status("/a");
  ASSERT_FALSE(Stat.getError());

  auto File = PFS.openFileForRead("/a");
  ASSERT_FALSE(File.getError());
  EXPECT_EQ("test", (*(*File)->getBuffer("ignored"))->getBuffer());

  std::error_code EC;
  vfs::directory_iterator I = PFS.dir_begin("/", EC);
  ASSERT_FALSE(EC);
  ASSERT_EQ("/a", I->path());
  I.increment(EC);
  ASSERT_FALSE(EC);
  ASSERT_EQ(vfs::directory_iterator(), I);

  ASSERT_FALSE(PFS.setCurrentWorkingDirectory("/"));

  auto PWD = PFS.getCurrentWorkingDirectory();
  ASSERT_FALSE(PWD.getError());
  ASSERT_EQ("/", *PWD);

  SmallString<16> Path;
  ASSERT_FALSE(PFS.getRealPath("a", Path));
  ASSERT_EQ("/a", Path);

  bool Local = true;
  ASSERT_FALSE(PFS.isLocal("/a", Local));
  EXPECT_FALSE(Local);
}

class InMemoryFileSystemTest : public ::testing::Test {
protected:
  llvm::vfs::InMemoryFileSystem FS;
  llvm::vfs::InMemoryFileSystem NormalizedFS;

  InMemoryFileSystemTest()
      : FS(/*UseNormalizedPaths=*/false),
        NormalizedFS(/*UseNormalizedPaths=*/true) {}
};

MATCHER_P2(IsHardLinkTo, FS, Target, "") {
  StringRef From = arg;
  StringRef To = Target;
  auto OpenedFrom = FS->openFileForRead(From);
  auto OpenedTo = FS->openFileForRead(To);
  return !OpenedFrom.getError() && !OpenedTo.getError() &&
         (*OpenedFrom)->status()->getUniqueID() ==
             (*OpenedTo)->status()->getUniqueID();
}

TEST_F(InMemoryFileSystemTest, IsEmpty) {
  auto Stat = FS.status("/a");
  ASSERT_EQ(Stat.getError(), errc::no_such_file_or_directory) << FS.toString();
  Stat = FS.status("/");
  ASSERT_EQ(Stat.getError(), errc::no_such_file_or_directory) << FS.toString();
}

TEST_F(InMemoryFileSystemTest, WindowsPath) {
  FS.addFile("c:/windows/system128/foo.cpp", 0, MemoryBuffer::getMemBuffer(""));
  auto Stat = FS.status("c:");
#if !defined(_WIN32)
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << FS.toString();
#endif
  Stat = FS.status("c:/windows/system128/foo.cpp");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << FS.toString();
  FS.addFile("d:/windows/foo.cpp", 0, MemoryBuffer::getMemBuffer(""));
  Stat = FS.status("d:/windows/foo.cpp");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << FS.toString();
}

TEST_F(InMemoryFileSystemTest, OverlayFile) {
  FS.addFile("/a", 0, MemoryBuffer::getMemBuffer("a"));
  NormalizedFS.addFile("/a", 0, MemoryBuffer::getMemBuffer("a"));
  auto Stat = FS.status("/");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << FS.toString();
  Stat = FS.status("/.");
  ASSERT_FALSE(Stat);
  Stat = NormalizedFS.status("/.");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << FS.toString();
  Stat = FS.status("/a");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_EQ("/a", Stat->getName());
}

TEST_F(InMemoryFileSystemTest, OverlayFileNoOwn) {
  auto Buf = MemoryBuffer::getMemBuffer("a");
  FS.addFileNoOwn("/a", 0, Buf.get());
  auto Stat = FS.status("/a");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_EQ("/a", Stat->getName());
}

TEST_F(InMemoryFileSystemTest, OpenFileForRead) {
  FS.addFile("/a", 0, MemoryBuffer::getMemBuffer("a"));
  FS.addFile("././c", 0, MemoryBuffer::getMemBuffer("c"));
  FS.addFile("./d/../d", 0, MemoryBuffer::getMemBuffer("d"));
  NormalizedFS.addFile("/a", 0, MemoryBuffer::getMemBuffer("a"));
  NormalizedFS.addFile("././c", 0, MemoryBuffer::getMemBuffer("c"));
  NormalizedFS.addFile("./d/../d", 0, MemoryBuffer::getMemBuffer("d"));
  auto File = FS.openFileForRead("/a");
  ASSERT_EQ("a", (*(*File)->getBuffer("ignored"))->getBuffer());
  File = FS.openFileForRead("/a"); // Open again.
  ASSERT_EQ("a", (*(*File)->getBuffer("ignored"))->getBuffer());
  File = NormalizedFS.openFileForRead("/././a"); // Open again.
  ASSERT_EQ("a", (*(*File)->getBuffer("ignored"))->getBuffer());
  File = FS.openFileForRead("/");
  ASSERT_EQ(File.getError(), errc::invalid_argument) << FS.toString();
  File = FS.openFileForRead("/b");
  ASSERT_EQ(File.getError(), errc::no_such_file_or_directory) << FS.toString();
  File = FS.openFileForRead("./c");
  ASSERT_FALSE(File);
  File = FS.openFileForRead("e/../d");
  ASSERT_FALSE(File);
  File = NormalizedFS.openFileForRead("./c");
  ASSERT_EQ("c", (*(*File)->getBuffer("ignored"))->getBuffer());
  File = NormalizedFS.openFileForRead("e/../d");
  ASSERT_EQ("d", (*(*File)->getBuffer("ignored"))->getBuffer());
}

TEST_F(InMemoryFileSystemTest, DuplicatedFile) {
  ASSERT_TRUE(FS.addFile("/a", 0, MemoryBuffer::getMemBuffer("a")));
  ASSERT_FALSE(FS.addFile("/a/b", 0, MemoryBuffer::getMemBuffer("a")));
  ASSERT_TRUE(FS.addFile("/a", 0, MemoryBuffer::getMemBuffer("a")));
  ASSERT_FALSE(FS.addFile("/a", 0, MemoryBuffer::getMemBuffer("b")));
}

TEST_F(InMemoryFileSystemTest, DirectoryIteration) {
  FS.addFile("/a", 0, MemoryBuffer::getMemBuffer(""));
  FS.addFile("/b/c", 0, MemoryBuffer::getMemBuffer(""));

  std::error_code EC;
  vfs::directory_iterator I = FS.dir_begin("/", EC);
  ASSERT_FALSE(EC);
  ASSERT_EQ("/a", I->path());
  I.increment(EC);
  ASSERT_FALSE(EC);
  ASSERT_EQ("/b", I->path());
  I.increment(EC);
  ASSERT_FALSE(EC);
  ASSERT_EQ(vfs::directory_iterator(), I);

  I = FS.dir_begin("/b", EC);
  ASSERT_FALSE(EC);
  // When on Windows, we end up with "/b\\c" as the name.  Convert to Posix
  // path for the sake of the comparison.
  ASSERT_EQ("/b/c", getPosixPath(I->path()));
  I.increment(EC);
  ASSERT_FALSE(EC);
  ASSERT_EQ(vfs::directory_iterator(), I);
}

TEST_F(InMemoryFileSystemTest, WorkingDirectory) {
  FS.setCurrentWorkingDirectory("/b");
  FS.addFile("c", 0, MemoryBuffer::getMemBuffer(""));

  auto Stat = FS.status("/b/c");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_EQ("/b/c", Stat->getName());
  ASSERT_EQ("/b", *FS.getCurrentWorkingDirectory());

  Stat = FS.status("c");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();

  NormalizedFS.setCurrentWorkingDirectory("/b/c");
  NormalizedFS.setCurrentWorkingDirectory(".");
  ASSERT_EQ("/b/c",
            getPosixPath(NormalizedFS.getCurrentWorkingDirectory().get()));
  NormalizedFS.setCurrentWorkingDirectory("..");
  ASSERT_EQ("/b",
            getPosixPath(NormalizedFS.getCurrentWorkingDirectory().get()));
}

TEST_F(InMemoryFileSystemTest, IsLocal) {
  FS.setCurrentWorkingDirectory("/b");
  FS.addFile("c", 0, MemoryBuffer::getMemBuffer(""));

  std::error_code EC;
  bool IsLocal = true;
  EC = FS.isLocal("c", IsLocal);
  ASSERT_FALSE(EC);
  ASSERT_FALSE(IsLocal);
}

#if !defined(_WIN32)
TEST_F(InMemoryFileSystemTest, GetRealPath) {
  SmallString<16> Path;
  EXPECT_EQ(FS.getRealPath("b", Path), errc::operation_not_permitted);

  auto GetRealPath = [this](StringRef P) {
    SmallString<16> Output;
    auto EC = FS.getRealPath(P, Output);
    EXPECT_FALSE(EC);
    return Output.str().str();
  };

  FS.setCurrentWorkingDirectory("a");
  EXPECT_EQ(GetRealPath("b"), "a/b");
  EXPECT_EQ(GetRealPath("../b"), "b");
  EXPECT_EQ(GetRealPath("b/./c"), "a/b/c");

  FS.setCurrentWorkingDirectory("/a");
  EXPECT_EQ(GetRealPath("b"), "/a/b");
  EXPECT_EQ(GetRealPath("../b"), "/b");
  EXPECT_EQ(GetRealPath("b/./c"), "/a/b/c");
}
#endif // _WIN32

TEST_F(InMemoryFileSystemTest, AddFileWithUser) {
  FS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), 0xFEEDFACE);
  auto Stat = FS.status("/a");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  ASSERT_EQ(0xFEEDFACE, Stat->getUser());
  Stat = FS.status("/a/b");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  ASSERT_EQ(0xFEEDFACE, Stat->getUser());
  Stat = FS.status("/a/b/c");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isRegularFile());
  ASSERT_EQ(sys::fs::perms::all_all, Stat->getPermissions());
  ASSERT_EQ(0xFEEDFACE, Stat->getUser());
}

TEST_F(InMemoryFileSystemTest, AddFileWithGroup) {
  FS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), None, 0xDABBAD00);
  auto Stat = FS.status("/a");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  ASSERT_EQ(0xDABBAD00, Stat->getGroup());
  Stat = FS.status("/a/b");
  ASSERT_TRUE(Stat->isDirectory());
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_EQ(0xDABBAD00, Stat->getGroup());
  Stat = FS.status("/a/b/c");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isRegularFile());
  ASSERT_EQ(sys::fs::perms::all_all, Stat->getPermissions());
  ASSERT_EQ(0xDABBAD00, Stat->getGroup());
}

TEST_F(InMemoryFileSystemTest, AddFileWithFileType) {
  FS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), None, None,
             sys::fs::file_type::socket_file);
  auto Stat = FS.status("/a");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  Stat = FS.status("/a/b");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  Stat = FS.status("/a/b/c");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_EQ(sys::fs::file_type::socket_file, Stat->getType());
  ASSERT_EQ(sys::fs::perms::all_all, Stat->getPermissions());
}

TEST_F(InMemoryFileSystemTest, AddFileWithPerms) {
  FS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"), None, None, None,
             sys::fs::perms::owner_read | sys::fs::perms::owner_write);
  auto Stat = FS.status("/a");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  ASSERT_EQ(sys::fs::perms::owner_read | sys::fs::perms::owner_write |
                sys::fs::perms::owner_exe,
            Stat->getPermissions());
  Stat = FS.status("/a/b");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  ASSERT_EQ(sys::fs::perms::owner_read | sys::fs::perms::owner_write |
                sys::fs::perms::owner_exe,
            Stat->getPermissions());
  Stat = FS.status("/a/b/c");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isRegularFile());
  ASSERT_EQ(sys::fs::perms::owner_read | sys::fs::perms::owner_write,
            Stat->getPermissions());
}

TEST_F(InMemoryFileSystemTest, AddDirectoryThenAddChild) {
  FS.addFile("/a", 0, MemoryBuffer::getMemBuffer(""), /*User=*/None,
             /*Group=*/None, sys::fs::file_type::directory_file);
  FS.addFile("/a/b", 0, MemoryBuffer::getMemBuffer("abc"), /*User=*/None,
             /*Group=*/None, sys::fs::file_type::regular_file);
  auto Stat = FS.status("/a");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isDirectory());
  Stat = FS.status("/a/b");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
  ASSERT_TRUE(Stat->isRegularFile());
}

// Test that the name returned by status() is in the same form as the path that
// was requested (to match the behavior of RealFileSystem).
TEST_F(InMemoryFileSystemTest, StatusName) {
  NormalizedFS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"),
                       /*User=*/None,
                       /*Group=*/None, sys::fs::file_type::regular_file);
  NormalizedFS.setCurrentWorkingDirectory("/a/b");

  // Access using InMemoryFileSystem::status.
  auto Stat = NormalizedFS.status("../b/c");
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n"
                                << NormalizedFS.toString();
  ASSERT_TRUE(Stat->isRegularFile());
  ASSERT_EQ("../b/c", Stat->getName());

  // Access using InMemoryFileAdaptor::status.
  auto File = NormalizedFS.openFileForRead("../b/c");
  ASSERT_FALSE(File.getError()) << File.getError() << "\n"
                                << NormalizedFS.toString();
  Stat = (*File)->status();
  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n"
                                << NormalizedFS.toString();
  ASSERT_TRUE(Stat->isRegularFile());
  ASSERT_EQ("../b/c", Stat->getName());

  // Access using a directory iterator.
  std::error_code EC;
  llvm::vfs::directory_iterator It = NormalizedFS.dir_begin("../b", EC);
  // When on Windows, we end up with "../b\\c" as the name.  Convert to Posix
  // path for the sake of the comparison.
  ASSERT_EQ("../b/c", getPosixPath(It->path()));
}

TEST_F(InMemoryFileSystemTest, AddHardLinkToFile) {
  StringRef FromLink = "/path/to/FROM/link";
  StringRef Target = "/path/to/TO/file";
  FS.addFile(Target, 0, MemoryBuffer::getMemBuffer("content of target"));
  EXPECT_TRUE(FS.addHardLink(FromLink, Target));
  EXPECT_THAT(FromLink, IsHardLinkTo(&FS, Target));
  EXPECT_TRUE(FS.status(FromLink)->getSize() == FS.status(Target)->getSize());
  EXPECT_TRUE(FS.getBufferForFile(FromLink)->get()->getBuffer() ==
              FS.getBufferForFile(Target)->get()->getBuffer());
}

TEST_F(InMemoryFileSystemTest, AddHardLinkInChainPattern) {
  StringRef Link0 = "/path/to/0/link";
  StringRef Link1 = "/path/to/1/link";
  StringRef Link2 = "/path/to/2/link";
  StringRef Target = "/path/to/target";
  FS.addFile(Target, 0, MemoryBuffer::getMemBuffer("content of target file"));
  EXPECT_TRUE(FS.addHardLink(Link2, Target));
  EXPECT_TRUE(FS.addHardLink(Link1, Link2));
  EXPECT_TRUE(FS.addHardLink(Link0, Link1));
  EXPECT_THAT(Link0, IsHardLinkTo(&FS, Target));
  EXPECT_THAT(Link1, IsHardLinkTo(&FS, Target));
  EXPECT_THAT(Link2, IsHardLinkTo(&FS, Target));
}

TEST_F(InMemoryFileSystemTest, AddHardLinkToAFileThatWasNotAddedBefore) {
  EXPECT_FALSE(FS.addHardLink("/path/to/link", "/path/to/target"));
}

TEST_F(InMemoryFileSystemTest, AddHardLinkFromAFileThatWasAddedBefore) {
  StringRef Link = "/path/to/link";
  StringRef Target = "/path/to/target";
  FS.addFile(Target, 0, MemoryBuffer::getMemBuffer("content of target"));
  FS.addFile(Link, 0, MemoryBuffer::getMemBuffer("content of link"));
  EXPECT_FALSE(FS.addHardLink(Link, Target));
}

TEST_F(InMemoryFileSystemTest, AddSameHardLinkMoreThanOnce) {
  StringRef Link = "/path/to/link";
  StringRef Target = "/path/to/target";
  FS.addFile(Target, 0, MemoryBuffer::getMemBuffer("content of target"));
  EXPECT_TRUE(FS.addHardLink(Link, Target));
  EXPECT_FALSE(FS.addHardLink(Link, Target));
}

TEST_F(InMemoryFileSystemTest, AddFileInPlaceOfAHardLinkWithSameContent) {
  StringRef Link = "/path/to/link";
  StringRef Target = "/path/to/target";
  StringRef Content = "content of target";
  EXPECT_TRUE(FS.addFile(Target, 0, MemoryBuffer::getMemBuffer(Content)));
  EXPECT_TRUE(FS.addHardLink(Link, Target));
  EXPECT_TRUE(FS.addFile(Link, 0, MemoryBuffer::getMemBuffer(Content)));
}

TEST_F(InMemoryFileSystemTest, AddFileInPlaceOfAHardLinkWithDifferentContent) {
  StringRef Link = "/path/to/link";
  StringRef Target = "/path/to/target";
  StringRef Content = "content of target";
  StringRef LinkContent = "different content of link";
  EXPECT_TRUE(FS.addFile(Target, 0, MemoryBuffer::getMemBuffer(Content)));
  EXPECT_TRUE(FS.addHardLink(Link, Target));
  EXPECT_FALSE(FS.addFile(Link, 0, MemoryBuffer::getMemBuffer(LinkContent)));
}

TEST_F(InMemoryFileSystemTest, AddHardLinkToADirectory) {
  StringRef Dir = "path/to/dummy/dir";
  StringRef Link = "/path/to/link";
  StringRef File = "path/to/dummy/dir/target";
  StringRef Content = "content of target";
  EXPECT_TRUE(FS.addFile(File, 0, MemoryBuffer::getMemBuffer(Content)));
  EXPECT_FALSE(FS.addHardLink(Link, Dir));
}

TEST_F(InMemoryFileSystemTest, AddHardLinkFromADirectory) {
  StringRef Dir = "path/to/dummy/dir";
  StringRef Target = "path/to/dummy/dir/target";
  StringRef Content = "content of target";
  EXPECT_TRUE(FS.addFile(Target, 0, MemoryBuffer::getMemBuffer(Content)));
  EXPECT_FALSE(FS.addHardLink(Dir, Target));
}

TEST_F(InMemoryFileSystemTest, AddHardLinkUnderAFile) {
  StringRef CommonContent = "content string";
  FS.addFile("/a/b", 0, MemoryBuffer::getMemBuffer(CommonContent));
  FS.addFile("/c/d", 0, MemoryBuffer::getMemBuffer(CommonContent));
  EXPECT_FALSE(FS.addHardLink("/c/d/e", "/a/b"));
}

TEST_F(InMemoryFileSystemTest, RecursiveIterationWithHardLink) {
  std::error_code EC;
  FS.addFile("/a/b", 0, MemoryBuffer::getMemBuffer("content string"));
  EXPECT_TRUE(FS.addHardLink("/c/d", "/a/b"));
  auto I = vfs::recursive_directory_iterator(FS, "/", EC);
  ASSERT_FALSE(EC);
  std::vector<std::string> Nodes;
  for (auto E = vfs::recursive_directory_iterator(); !EC && I != E;
       I.increment(EC)) {
    Nodes.push_back(getPosixPath(I->path()));
  }
  EXPECT_THAT(Nodes, testing::UnorderedElementsAre("/a", "/a/b", "/c", "/c/d"));
}

// NOTE: in the tests below, we use '//root/' as our root directory, since it is
// a legal *absolute* path on Windows as well as *nix.
class VFSFromYAMLTest : public ::testing::Test {
public:
  int NumDiagnostics;

  void SetUp() override { NumDiagnostics = 0; }

  static void CountingDiagHandler(const SMDiagnostic &, void *Context) {
    VFSFromYAMLTest *Test = static_cast<VFSFromYAMLTest *>(Context);
    ++Test->NumDiagnostics;
  }

  IntrusiveRefCntPtr<vfs::FileSystem>
  getFromYAMLRawString(StringRef Content,
                       IntrusiveRefCntPtr<vfs::FileSystem> ExternalFS) {
    std::unique_ptr<MemoryBuffer> Buffer = MemoryBuffer::getMemBuffer(Content);
    return getVFSFromYAML(std::move(Buffer), CountingDiagHandler, "", this,
                          ExternalFS);
  }

  IntrusiveRefCntPtr<vfs::FileSystem> getFromYAMLString(
      StringRef Content,
      IntrusiveRefCntPtr<vfs::FileSystem> ExternalFS = new DummyFileSystem()) {
    std::string VersionPlusContent("{\n  'version':0,\n");
    VersionPlusContent += Content.slice(Content.find('{') + 1, StringRef::npos);
    return getFromYAMLRawString(VersionPlusContent, ExternalFS);
  }

  // This is intended as a "XFAIL" for windows hosts.
  bool supportsSameDirMultipleYAMLEntries() {
    Triple Host(Triple::normalize(sys::getProcessTriple()));
    return !Host.isOSWindows();
  }
};

TEST_F(VFSFromYAMLTest, BasicVFSFromYAML) {
  IntrusiveRefCntPtr<vfs::FileSystem> FS;
  FS = getFromYAMLString("");
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString("[]");
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString("'string'");
  EXPECT_EQ(nullptr, FS.get());
  EXPECT_EQ(3, NumDiagnostics);
}

TEST_F(VFSFromYAMLTest, MappedFiles) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("//root/foo/bar/a");
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
      "{ 'roots': [\n"
      "{\n"
      "  'type': 'directory',\n"
      "  'name': '//root/',\n"
      "  'contents': [ {\n"
      "                  'type': 'file',\n"
      "                  'name': 'file1',\n"
      "                  'external-contents': '//root/foo/bar/a'\n"
      "                },\n"
      "                {\n"
      "                  'type': 'file',\n"
      "                  'name': 'file2',\n"
      "                  'external-contents': '//root/foo/b'\n"
      "                }\n"
      "              ]\n"
      "}\n"
      "]\n"
      "}",
      Lower);
  ASSERT_TRUE(FS.get() != nullptr);

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(FS);

  // file
  ErrorOr<vfs::Status> S = O->status("//root/file1");
  ASSERT_FALSE(S.getError());
  EXPECT_EQ("//root/foo/bar/a", S->getName());
  EXPECT_TRUE(S->IsVFSMapped);

  ErrorOr<vfs::Status> SLower = O->status("//root/foo/bar/a");
  EXPECT_EQ("//root/foo/bar/a", SLower->getName());
  EXPECT_TRUE(S->equivalent(*SLower));
  EXPECT_FALSE(SLower->IsVFSMapped);

  // file after opening
  auto OpenedF = O->openFileForRead("//root/file1");
  ASSERT_FALSE(OpenedF.getError());
  auto OpenedS = (*OpenedF)->status();
  ASSERT_FALSE(OpenedS.getError());
  EXPECT_EQ("//root/foo/bar/a", OpenedS->getName());
  EXPECT_TRUE(OpenedS->IsVFSMapped);

  // directory
  S = O->status("//root/");
  ASSERT_FALSE(S.getError());
  EXPECT_TRUE(S->isDirectory());
  EXPECT_TRUE(S->equivalent(*O->status("//root/"))); // non-volatile UniqueID

  // broken mapping
  EXPECT_EQ(O->status("//root/file2").getError(),
            llvm::errc::no_such_file_or_directory);
  EXPECT_EQ(0, NumDiagnostics);
}

TEST_F(VFSFromYAMLTest, CaseInsensitive) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("//root/foo/bar/a");
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
      "{ 'case-sensitive': 'false',\n"
      "  'roots': [\n"
      "{\n"
      "  'type': 'directory',\n"
      "  'name': '//root/',\n"
      "  'contents': [ {\n"
      "                  'type': 'file',\n"
      "                  'name': 'XX',\n"
      "                  'external-contents': '//root/foo/bar/a'\n"
      "                }\n"
      "              ]\n"
      "}]}",
      Lower);
  ASSERT_TRUE(FS.get() != nullptr);

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(FS);

  ErrorOr<vfs::Status> S = O->status("//root/XX");
  ASSERT_FALSE(S.getError());

  ErrorOr<vfs::Status> SS = O->status("//root/xx");
  ASSERT_FALSE(SS.getError());
  EXPECT_TRUE(S->equivalent(*SS));
  SS = O->status("//root/xX");
  EXPECT_TRUE(S->equivalent(*SS));
  SS = O->status("//root/Xx");
  EXPECT_TRUE(S->equivalent(*SS));
  EXPECT_EQ(0, NumDiagnostics);
}

TEST_F(VFSFromYAMLTest, CaseSensitive) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("//root/foo/bar/a");
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
      "{ 'case-sensitive': 'true',\n"
      "  'roots': [\n"
      "{\n"
      "  'type': 'directory',\n"
      "  'name': '//root/',\n"
      "  'contents': [ {\n"
      "                  'type': 'file',\n"
      "                  'name': 'XX',\n"
      "                  'external-contents': '//root/foo/bar/a'\n"
      "                }\n"
      "              ]\n"
      "}]}",
      Lower);
  ASSERT_TRUE(FS.get() != nullptr);

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(FS);

  ErrorOr<vfs::Status> SS = O->status("//root/xx");
  EXPECT_EQ(SS.getError(), llvm::errc::no_such_file_or_directory);
  SS = O->status("//root/xX");
  EXPECT_EQ(SS.getError(), llvm::errc::no_such_file_or_directory);
  SS = O->status("//root/Xx");
  EXPECT_EQ(SS.getError(), llvm::errc::no_such_file_or_directory);
  EXPECT_EQ(0, NumDiagnostics);
}

TEST_F(VFSFromYAMLTest, IllegalVFSFile) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());

  // invalid YAML at top-level
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString("{]", Lower);
  EXPECT_EQ(nullptr, FS.get());
  // invalid YAML in roots
  FS = getFromYAMLString("{ 'roots':[}", Lower);
  // invalid YAML in directory
  FS = getFromYAMLString(
      "{ 'roots':[ { 'name': 'foo', 'type': 'directory', 'contents': [}",
      Lower);
  EXPECT_EQ(nullptr, FS.get());

  // invalid configuration
  FS = getFromYAMLString("{ 'knobular': 'true', 'roots':[] }", Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString("{ 'case-sensitive': 'maybe', 'roots':[] }", Lower);
  EXPECT_EQ(nullptr, FS.get());

  // invalid roots
  FS = getFromYAMLString("{ 'roots':'' }", Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString("{ 'roots':{} }", Lower);
  EXPECT_EQ(nullptr, FS.get());

  // invalid entries
  FS = getFromYAMLString(
      "{ 'roots':[ { 'type': 'other', 'name': 'me', 'contents': '' }", Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString("{ 'roots':[ { 'type': 'file', 'name': [], "
                         "'external-contents': 'other' }",
                         Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString(
      "{ 'roots':[ { 'type': 'file', 'name': 'me', 'external-contents': [] }",
      Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString(
      "{ 'roots':[ { 'type': 'file', 'name': 'me', 'external-contents': {} }",
      Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString(
      "{ 'roots':[ { 'type': 'directory', 'name': 'me', 'contents': {} }",
      Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString(
      "{ 'roots':[ { 'type': 'directory', 'name': 'me', 'contents': '' }",
      Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString(
      "{ 'roots':[ { 'thingy': 'directory', 'name': 'me', 'contents': [] }",
      Lower);
  EXPECT_EQ(nullptr, FS.get());

  // missing mandatory fields
  FS = getFromYAMLString("{ 'roots':[ { 'type': 'file', 'name': 'me' }", Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString(
      "{ 'roots':[ { 'type': 'file', 'external-contents': 'other' }", Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString("{ 'roots':[ { 'name': 'me', 'contents': [] }", Lower);
  EXPECT_EQ(nullptr, FS.get());

  // duplicate keys
  FS = getFromYAMLString("{ 'roots':[], 'roots':[] }", Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLString(
      "{ 'case-sensitive':'true', 'case-sensitive':'true', 'roots':[] }",
      Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS =
      getFromYAMLString("{ 'roots':[{'name':'me', 'name':'you', 'type':'file', "
                        "'external-contents':'blah' } ] }",
                        Lower);
  EXPECT_EQ(nullptr, FS.get());

  // missing version
  FS = getFromYAMLRawString("{ 'roots':[] }", Lower);
  EXPECT_EQ(nullptr, FS.get());

  // bad version number
  FS = getFromYAMLRawString("{ 'version':'foo', 'roots':[] }", Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLRawString("{ 'version':-1, 'roots':[] }", Lower);
  EXPECT_EQ(nullptr, FS.get());
  FS = getFromYAMLRawString("{ 'version':100000, 'roots':[] }", Lower);
  EXPECT_EQ(nullptr, FS.get());
  EXPECT_EQ(24, NumDiagnostics);
}

TEST_F(VFSFromYAMLTest, UseExternalName) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("//root/external/file");

  IntrusiveRefCntPtr<vfs::FileSystem> FS =
      getFromYAMLString("{ 'roots': [\n"
                        "  { 'type': 'file', 'name': '//root/A',\n"
                        "    'external-contents': '//root/external/file'\n"
                        "  },\n"
                        "  { 'type': 'file', 'name': '//root/B',\n"
                        "    'use-external-name': true,\n"
                        "    'external-contents': '//root/external/file'\n"
                        "  },\n"
                        "  { 'type': 'file', 'name': '//root/C',\n"
                        "    'use-external-name': false,\n"
                        "    'external-contents': '//root/external/file'\n"
                        "  }\n"
                        "] }",
                        Lower);
  ASSERT_TRUE(nullptr != FS.get());

  // default true
  EXPECT_EQ("//root/external/file", FS->status("//root/A")->getName());
  // explicit
  EXPECT_EQ("//root/external/file", FS->status("//root/B")->getName());
  EXPECT_EQ("//root/C", FS->status("//root/C")->getName());

  // global configuration
  FS = getFromYAMLString("{ 'use-external-names': false,\n"
                         "  'roots': [\n"
                         "  { 'type': 'file', 'name': '//root/A',\n"
                         "    'external-contents': '//root/external/file'\n"
                         "  },\n"
                         "  { 'type': 'file', 'name': '//root/B',\n"
                         "    'use-external-name': true,\n"
                         "    'external-contents': '//root/external/file'\n"
                         "  },\n"
                         "  { 'type': 'file', 'name': '//root/C',\n"
                         "    'use-external-name': false,\n"
                         "    'external-contents': '//root/external/file'\n"
                         "  }\n"
                         "] }",
                         Lower);
  ASSERT_TRUE(nullptr != FS.get());

  // default
  EXPECT_EQ("//root/A", FS->status("//root/A")->getName());
  // explicit
  EXPECT_EQ("//root/external/file", FS->status("//root/B")->getName());
  EXPECT_EQ("//root/C", FS->status("//root/C")->getName());
}

TEST_F(VFSFromYAMLTest, MultiComponentPath) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("//root/other");

  // file in roots
  IntrusiveRefCntPtr<vfs::FileSystem> FS =
      getFromYAMLString("{ 'roots': [\n"
                        "  { 'type': 'file', 'name': '//root/path/to/file',\n"
                        "    'external-contents': '//root/other' }]\n"
                        "}",
                        Lower);
  ASSERT_TRUE(nullptr != FS.get());
  EXPECT_FALSE(FS->status("//root/path/to/file").getError());
  EXPECT_FALSE(FS->status("//root/path/to").getError());
  EXPECT_FALSE(FS->status("//root/path").getError());
  EXPECT_FALSE(FS->status("//root/").getError());

  // at the start
  FS = getFromYAMLString(
      "{ 'roots': [\n"
      "  { 'type': 'directory', 'name': '//root/path/to',\n"
      "    'contents': [ { 'type': 'file', 'name': 'file',\n"
      "                    'external-contents': '//root/other' }]}]\n"
      "}",
      Lower);
  ASSERT_TRUE(nullptr != FS.get());
  EXPECT_FALSE(FS->status("//root/path/to/file").getError());
  EXPECT_FALSE(FS->status("//root/path/to").getError());
  EXPECT_FALSE(FS->status("//root/path").getError());
  EXPECT_FALSE(FS->status("//root/").getError());

  // at the end
  FS = getFromYAMLString(
      "{ 'roots': [\n"
      "  { 'type': 'directory', 'name': '//root/',\n"
      "    'contents': [ { 'type': 'file', 'name': 'path/to/file',\n"
      "                    'external-contents': '//root/other' }]}]\n"
      "}",
      Lower);
  ASSERT_TRUE(nullptr != FS.get());
  EXPECT_FALSE(FS->status("//root/path/to/file").getError());
  EXPECT_FALSE(FS->status("//root/path/to").getError());
  EXPECT_FALSE(FS->status("//root/path").getError());
  EXPECT_FALSE(FS->status("//root/").getError());
}

TEST_F(VFSFromYAMLTest, TrailingSlashes) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addRegularFile("//root/other");

  // file in roots
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
      "{ 'roots': [\n"
      "  { 'type': 'directory', 'name': '//root/path/to////',\n"
      "    'contents': [ { 'type': 'file', 'name': 'file',\n"
      "                    'external-contents': '//root/other' }]}]\n"
      "}",
      Lower);
  ASSERT_TRUE(nullptr != FS.get());
  EXPECT_FALSE(FS->status("//root/path/to/file").getError());
  EXPECT_FALSE(FS->status("//root/path/to").getError());
  EXPECT_FALSE(FS->status("//root/path").getError());
  EXPECT_FALSE(FS->status("//root/").getError());
}

TEST_F(VFSFromYAMLTest, DirectoryIteration) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addDirectory("//root/");
  Lower->addDirectory("//root/foo");
  Lower->addDirectory("//root/foo/bar");
  Lower->addRegularFile("//root/foo/bar/a");
  Lower->addRegularFile("//root/foo/bar/b");
  Lower->addRegularFile("//root/file3");
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
      "{ 'use-external-names': false,\n"
      "  'roots': [\n"
      "{\n"
      "  'type': 'directory',\n"
      "  'name': '//root/',\n"
      "  'contents': [ {\n"
      "                  'type': 'file',\n"
      "                  'name': 'file1',\n"
      "                  'external-contents': '//root/foo/bar/a'\n"
      "                },\n"
      "                {\n"
      "                  'type': 'file',\n"
      "                  'name': 'file2',\n"
      "                  'external-contents': '//root/foo/bar/b'\n"
      "                }\n"
      "              ]\n"
      "}\n"
      "]\n"
      "}",
      Lower);
  ASSERT_TRUE(FS.get() != nullptr);

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(FS);

  std::error_code EC;
  checkContents(O->dir_begin("//root/", EC),
                {"//root/file1", "//root/file2", "//root/file3", "//root/foo"});

  checkContents(O->dir_begin("//root/foo/bar", EC),
                {"//root/foo/bar/a", "//root/foo/bar/b"});
}

TEST_F(VFSFromYAMLTest, DirectoryIterationSameDirMultipleEntries) {
  // https://llvm.org/bugs/show_bug.cgi?id=27725
  if (!supportsSameDirMultipleYAMLEntries())
    return;

  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addDirectory("//root/zab");
  Lower->addDirectory("//root/baz");
  Lower->addRegularFile("//root/zab/a");
  Lower->addRegularFile("//root/zab/b");
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
      "{ 'use-external-names': false,\n"
      "  'roots': [\n"
      "{\n"
      "  'type': 'directory',\n"
      "  'name': '//root/baz/',\n"
      "  'contents': [ {\n"
      "                  'type': 'file',\n"
      "                  'name': 'x',\n"
      "                  'external-contents': '//root/zab/a'\n"
      "                }\n"
      "              ]\n"
      "},\n"
      "{\n"
      "  'type': 'directory',\n"
      "  'name': '//root/baz/',\n"
      "  'contents': [ {\n"
      "                  'type': 'file',\n"
      "                  'name': 'y',\n"
      "                  'external-contents': '//root/zab/b'\n"
      "                }\n"
      "              ]\n"
      "}\n"
      "]\n"
      "}",
      Lower);
  ASSERT_TRUE(FS.get() != nullptr);

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(FS);

  std::error_code EC;

  checkContents(O->dir_begin("//root/baz/", EC),
                {"//root/baz/x", "//root/baz/y"});
}

TEST_F(VFSFromYAMLTest, RecursiveDirectoryIterationLevel) {

  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addDirectory("//root/a");
  Lower->addDirectory("//root/a/b");
  Lower->addDirectory("//root/a/b/c");
  Lower->addRegularFile("//root/a/b/c/file");
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
      "{ 'use-external-names': false,\n"
      "  'roots': [\n"
      "{\n"
      "  'type': 'directory',\n"
      "  'name': '//root/a/b/c/',\n"
      "  'contents': [ {\n"
      "                  'type': 'file',\n"
      "                  'name': 'file',\n"
      "                  'external-contents': '//root/a/b/c/file'\n"
      "                }\n"
      "              ]\n"
      "},\n"
      "]\n"
      "}",
      Lower);
  ASSERT_TRUE(FS.get() != nullptr);

  IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
      new vfs::OverlayFileSystem(Lower));
  O->pushOverlay(FS);

  std::error_code EC;

  // Test recursive_directory_iterator level()
  vfs::recursive_directory_iterator I = vfs::recursive_directory_iterator(
                                        *O, "//root", EC),
                                    E;
  ASSERT_FALSE(EC);
  for (int l = 0; I != E; I.increment(EC), ++l) {
    ASSERT_FALSE(EC);
    EXPECT_EQ(I.level(), l);
  }
  EXPECT_EQ(I, E);
}

TEST_F(VFSFromYAMLTest, RelativePaths) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  // Filename at root level without a parent directory.
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
      "{ 'roots': [\n"
      "  { 'type': 'file', 'name': 'file-not-in-directory.h',\n"
      "    'external-contents': '//root/external/file'\n"
      "  }\n"
      "] }",
      Lower);
  EXPECT_EQ(nullptr, FS.get());

  // Relative file path.
  FS = getFromYAMLString("{ 'roots': [\n"
                         "  { 'type': 'file', 'name': 'relative/file/path.h',\n"
                         "    'external-contents': '//root/external/file'\n"
                         "  }\n"
                         "] }",
                         Lower);
  EXPECT_EQ(nullptr, FS.get());

  // Relative directory path.
  FS = getFromYAMLString(
      "{ 'roots': [\n"
      "  { 'type': 'directory', 'name': 'relative/directory/path.h',\n"
      "    'contents': []\n"
      "  }\n"
      "] }",
      Lower);
  EXPECT_EQ(nullptr, FS.get());

  EXPECT_EQ(3, NumDiagnostics);
}

TEST_F(VFSFromYAMLTest, NonFallthroughDirectoryIteration) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addDirectory("//root/");
  Lower->addRegularFile("//root/a");
  Lower->addRegularFile("//root/b");
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
      "{ 'use-external-names': false,\n"
      "  'fallthrough': false,\n"
      "  'roots': [\n"
      "{\n"
      "  'type': 'directory',\n"
      "  'name': '//root/',\n"
      "  'contents': [ {\n"
      "                  'type': 'file',\n"
      "                  'name': 'c',\n"
      "                  'external-contents': '//root/a'\n"
      "                }\n"
      "              ]\n"
      "}\n"
      "]\n"
      "}",
      Lower);
  ASSERT_TRUE(FS.get() != nullptr);

  std::error_code EC;
  checkContents(FS->dir_begin("//root/", EC),
                {"//root/c"});
}

TEST_F(VFSFromYAMLTest, DirectoryIterationWithDuplicates) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addDirectory("//root/");
  Lower->addRegularFile("//root/a");
  Lower->addRegularFile("//root/b");
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
      "{ 'use-external-names': false,\n"
      "  'roots': [\n"
      "{\n"
      "  'type': 'directory',\n"
      "  'name': '//root/',\n"
      "  'contents': [ {\n"
      "                  'type': 'file',\n"
      "                  'name': 'a',\n"
      "                  'external-contents': '//root/a'\n"
      "                }\n"
      "              ]\n"
      "}\n"
      "]\n"
      "}",
	  Lower);
  ASSERT_TRUE(FS.get() != nullptr);

  std::error_code EC;
  checkContents(FS->dir_begin("//root/", EC),
                {"//root/a", "//root/b"});
}

TEST_F(VFSFromYAMLTest, DirectoryIterationErrorInVFSLayer) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addDirectory("//root/");
  Lower->addDirectory("//root/foo");
  Lower->addRegularFile("//root/foo/a");
  Lower->addRegularFile("//root/foo/b");
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
      "{ 'use-external-names': false,\n"
      "  'roots': [\n"
      "{\n"
      "  'type': 'directory',\n"
      "  'name': '//root/',\n"
      "  'contents': [ {\n"
      "                  'type': 'file',\n"
      "                  'name': 'bar/a',\n"
      "                  'external-contents': '//root/foo/a'\n"
      "                }\n"
      "              ]\n"
      "}\n"
      "]\n"
      "}",
      Lower);
  ASSERT_TRUE(FS.get() != nullptr);

  std::error_code EC;
  checkContents(FS->dir_begin("//root/foo", EC),
                {"//root/foo/a", "//root/foo/b"});
}

TEST_F(VFSFromYAMLTest, GetRealPath) {
  IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
  Lower->addDirectory("//dir/");
  Lower->addRegularFile("/foo");
  Lower->addSymlink("/link");
  IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
      "{ 'use-external-names': false,\n"
      "  'roots': [\n"
      "{\n"
      "  'type': 'directory',\n"
      "  'name': '//root/',\n"
      "  'contents': [ {\n"
      "                  'type': 'file',\n"
      "                  'name': 'bar',\n"
      "                  'external-contents': '/link'\n"
      "                }\n"
      "              ]\n"
      "},\n"
      "{\n"
      "  'type': 'directory',\n"
      "  'name': '//dir/',\n"
      "  'contents': []\n"
      "}\n"
      "]\n"
      "}",
      Lower);
  ASSERT_TRUE(FS.get() != nullptr);

  // Regular file present in underlying file system.
  SmallString<16> RealPath;
  EXPECT_FALSE(FS->getRealPath("/foo", RealPath));
  EXPECT_EQ(RealPath.str(), "/foo");

  // File present in YAML pointing to symlink in underlying file system.
  EXPECT_FALSE(FS->getRealPath("//root/bar", RealPath));
  EXPECT_EQ(RealPath.str(), "/symlink");

  // Directories should fall back to the underlying file system is possible.
  EXPECT_FALSE(FS->getRealPath("//dir/", RealPath));
  EXPECT_EQ(RealPath.str(), "//dir/");

  // Try a non-existing file.
  EXPECT_EQ(FS->getRealPath("/non_existing", RealPath),
            errc::no_such_file_or_directory);
}