1 //===- llvm/unittest/Support/Path.cpp - Path tests ------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/Support/Path.h"
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ADT/SmallVector.h"
12 #include "llvm/ADT/Triple.h"
13 #include "llvm/BinaryFormat/Magic.h"
14 #include "llvm/Config/llvm-config.h"
15 #include "llvm/Support/ConvertUTF.h"
16 #include "llvm/Support/Errc.h"
17 #include "llvm/Support/ErrorHandling.h"
18 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/FileUtilities.h"
20 #include "llvm/Support/Host.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Testing/Support/Error.h"
24 #include "gmock/gmock.h"
25 #include "gtest/gtest.h"
26 
27 #ifdef _WIN32
28 #include "llvm/ADT/ArrayRef.h"
29 #include "llvm/Support/Chrono.h"
30 #include <windows.h>
31 #include <winerror.h>
32 #endif
33 
34 #ifdef LLVM_ON_UNIX
35 #include <pwd.h>
36 #include <sys/stat.h>
37 #endif
38 
39 using namespace llvm;
40 using namespace llvm::sys;
41 
42 #define ASSERT_NO_ERROR(x)                                                     \
43   if (std::error_code ASSERT_NO_ERROR_ec = x) {                                \
44     SmallString<128> MessageStorage;                                           \
45     raw_svector_ostream Message(MessageStorage);                               \
46     Message << #x ": did not return errc::success.\n"                          \
47             << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n"          \
48             << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n";      \
49     GTEST_FATAL_FAILURE_(MessageStorage.c_str());                              \
50   } else {                                                                     \
51   }
52 
53 #define ASSERT_ERROR(x)                                                        \
54   if (!x) {                                                                    \
55     SmallString<128> MessageStorage;                                           \
56     raw_svector_ostream Message(MessageStorage);                               \
57     Message << #x ": did not return a failure error code.\n";                  \
58     GTEST_FATAL_FAILURE_(MessageStorage.c_str());                              \
59   }
60 
61 namespace {
62 
63 struct FileDescriptorCloser {
64   explicit FileDescriptorCloser(int FD) : FD(FD) {}
65   ~FileDescriptorCloser() { ::close(FD); }
66   int FD;
67 };
68 
69 TEST(is_separator, Works) {
70   EXPECT_TRUE(path::is_separator('/'));
71   EXPECT_FALSE(path::is_separator('\0'));
72   EXPECT_FALSE(path::is_separator('-'));
73   EXPECT_FALSE(path::is_separator(' '));
74 
75   EXPECT_TRUE(path::is_separator('\\', path::Style::windows));
76   EXPECT_FALSE(path::is_separator('\\', path::Style::posix));
77 
78 #ifdef _WIN32
79   EXPECT_TRUE(path::is_separator('\\'));
80 #else
81   EXPECT_FALSE(path::is_separator('\\'));
82 #endif
83 }
84 
85 TEST(Support, Path) {
86   SmallVector<StringRef, 40> paths;
87   paths.push_back("");
88   paths.push_back(".");
89   paths.push_back("..");
90   paths.push_back("foo");
91   paths.push_back("/");
92   paths.push_back("/foo");
93   paths.push_back("foo/");
94   paths.push_back("/foo/");
95   paths.push_back("foo/bar");
96   paths.push_back("/foo/bar");
97   paths.push_back("//net");
98   paths.push_back("//net/");
99   paths.push_back("//net/foo");
100   paths.push_back("///foo///");
101   paths.push_back("///foo///bar");
102   paths.push_back("/.");
103   paths.push_back("./");
104   paths.push_back("/..");
105   paths.push_back("../");
106   paths.push_back("foo/.");
107   paths.push_back("foo/..");
108   paths.push_back("foo/./");
109   paths.push_back("foo/./bar");
110   paths.push_back("foo/..");
111   paths.push_back("foo/../");
112   paths.push_back("foo/../bar");
113   paths.push_back("c:");
114   paths.push_back("c:/");
115   paths.push_back("c:foo");
116   paths.push_back("c:/foo");
117   paths.push_back("c:foo/");
118   paths.push_back("c:/foo/");
119   paths.push_back("c:/foo/bar");
120   paths.push_back("prn:");
121   paths.push_back("c:\\");
122   paths.push_back("c:foo");
123   paths.push_back("c:\\foo");
124   paths.push_back("c:foo\\");
125   paths.push_back("c:\\foo\\");
126   paths.push_back("c:\\foo/");
127   paths.push_back("c:/foo\\bar");
128 
129   for (SmallVector<StringRef, 40>::const_iterator i = paths.begin(),
130                                                   e = paths.end();
131                                                   i != e;
132                                                   ++i) {
133     SCOPED_TRACE(*i);
134     SmallVector<StringRef, 5> ComponentStack;
135     for (sys::path::const_iterator ci = sys::path::begin(*i),
136                                    ce = sys::path::end(*i);
137                                    ci != ce;
138                                    ++ci) {
139       EXPECT_FALSE(ci->empty());
140       ComponentStack.push_back(*ci);
141     }
142 
143     SmallVector<StringRef, 5> ReverseComponentStack;
144     for (sys::path::reverse_iterator ci = sys::path::rbegin(*i),
145                                      ce = sys::path::rend(*i);
146                                      ci != ce;
147                                      ++ci) {
148       EXPECT_FALSE(ci->empty());
149       ReverseComponentStack.push_back(*ci);
150     }
151     std::reverse(ReverseComponentStack.begin(), ReverseComponentStack.end());
152     EXPECT_THAT(ComponentStack, testing::ContainerEq(ReverseComponentStack));
153 
154     // Crash test most of the API - since we're iterating over all of our paths
155     // here there isn't really anything reasonable to assert on in the results.
156     (void)path::has_root_path(*i);
157     (void)path::root_path(*i);
158     (void)path::has_root_name(*i);
159     (void)path::root_name(*i);
160     (void)path::has_root_directory(*i);
161     (void)path::root_directory(*i);
162     (void)path::has_parent_path(*i);
163     (void)path::parent_path(*i);
164     (void)path::has_filename(*i);
165     (void)path::filename(*i);
166     (void)path::has_stem(*i);
167     (void)path::stem(*i);
168     (void)path::has_extension(*i);
169     (void)path::extension(*i);
170     (void)path::is_absolute(*i);
171     (void)path::is_relative(*i);
172 
173     SmallString<128> temp_store;
174     temp_store = *i;
175     ASSERT_NO_ERROR(fs::make_absolute(temp_store));
176     temp_store = *i;
177     path::remove_filename(temp_store);
178 
179     temp_store = *i;
180     path::replace_extension(temp_store, "ext");
181     StringRef filename(temp_store.begin(), temp_store.size()), stem, ext;
182     stem = path::stem(filename);
183     ext  = path::extension(filename);
184     EXPECT_EQ(*sys::path::rbegin(filename), (stem + ext).str());
185 
186     path::native(*i, temp_store);
187   }
188 
189   {
190     SmallString<32> Relative("foo.cpp");
191     sys::fs::make_absolute("/root", Relative);
192     Relative[5] = '/'; // Fix up windows paths.
193     ASSERT_EQ("/root/foo.cpp", Relative);
194   }
195 
196   {
197     SmallString<32> Relative("foo.cpp");
198     sys::fs::make_absolute("//root", Relative);
199     Relative[6] = '/'; // Fix up windows paths.
200     ASSERT_EQ("//root/foo.cpp", Relative);
201   }
202 }
203 
204 TEST(Support, FilenameParent) {
205   EXPECT_EQ("/", path::filename("/"));
206   EXPECT_EQ("", path::parent_path("/"));
207 
208   EXPECT_EQ("\\", path::filename("c:\\", path::Style::windows));
209   EXPECT_EQ("c:", path::parent_path("c:\\", path::Style::windows));
210 
211   EXPECT_EQ("/", path::filename("///"));
212   EXPECT_EQ("", path::parent_path("///"));
213 
214   EXPECT_EQ("\\", path::filename("c:\\\\", path::Style::windows));
215   EXPECT_EQ("c:", path::parent_path("c:\\\\", path::Style::windows));
216 
217   EXPECT_EQ("bar", path::filename("/foo/bar"));
218   EXPECT_EQ("/foo", path::parent_path("/foo/bar"));
219 
220   EXPECT_EQ("foo", path::filename("/foo"));
221   EXPECT_EQ("/", path::parent_path("/foo"));
222 
223   EXPECT_EQ("foo", path::filename("foo"));
224   EXPECT_EQ("", path::parent_path("foo"));
225 
226   EXPECT_EQ(".", path::filename("foo/"));
227   EXPECT_EQ("foo", path::parent_path("foo/"));
228 
229   EXPECT_EQ("//net", path::filename("//net"));
230   EXPECT_EQ("", path::parent_path("//net"));
231 
232   EXPECT_EQ("/", path::filename("//net/"));
233   EXPECT_EQ("//net", path::parent_path("//net/"));
234 
235   EXPECT_EQ("foo", path::filename("//net/foo"));
236   EXPECT_EQ("//net/", path::parent_path("//net/foo"));
237 
238   // These checks are just to make sure we do something reasonable with the
239   // paths below. They are not meant to prescribe the one true interpretation of
240   // these paths. Other decompositions (e.g. "//" -> "" + "//") are also
241   // possible.
242   EXPECT_EQ("/", path::filename("//"));
243   EXPECT_EQ("", path::parent_path("//"));
244 
245   EXPECT_EQ("\\", path::filename("\\\\", path::Style::windows));
246   EXPECT_EQ("", path::parent_path("\\\\", path::Style::windows));
247 
248   EXPECT_EQ("\\", path::filename("\\\\\\", path::Style::windows));
249   EXPECT_EQ("", path::parent_path("\\\\\\", path::Style::windows));
250 }
251 
252 static std::vector<StringRef>
253 GetComponents(StringRef Path, path::Style S = path::Style::native) {
254   return {path::begin(Path, S), path::end(Path)};
255 }
256 
257 TEST(Support, PathIterator) {
258   EXPECT_THAT(GetComponents("/foo"), testing::ElementsAre("/", "foo"));
259   EXPECT_THAT(GetComponents("/"), testing::ElementsAre("/"));
260   EXPECT_THAT(GetComponents("//"), testing::ElementsAre("/"));
261   EXPECT_THAT(GetComponents("///"), testing::ElementsAre("/"));
262   EXPECT_THAT(GetComponents("c/d/e/foo.txt"),
263               testing::ElementsAre("c", "d", "e", "foo.txt"));
264   EXPECT_THAT(GetComponents(".c/.d/../."),
265               testing::ElementsAre(".c", ".d", "..", "."));
266   EXPECT_THAT(GetComponents("/c/d/e/foo.txt"),
267               testing::ElementsAre("/", "c", "d", "e", "foo.txt"));
268   EXPECT_THAT(GetComponents("/.c/.d/../."),
269               testing::ElementsAre("/", ".c", ".d", "..", "."));
270   EXPECT_THAT(GetComponents("c:\\c\\e\\foo.txt", path::Style::windows),
271               testing::ElementsAre("c:", "\\", "c", "e", "foo.txt"));
272   EXPECT_THAT(GetComponents("//net/"), testing::ElementsAre("//net", "/"));
273   EXPECT_THAT(GetComponents("//net/c/foo.txt"),
274               testing::ElementsAre("//net", "/", "c", "foo.txt"));
275 }
276 
277 TEST(Support, AbsolutePathIteratorEnd) {
278   // Trailing slashes are converted to '.' unless they are part of the root path.
279   SmallVector<std::pair<StringRef, path::Style>, 4> Paths;
280   Paths.emplace_back("/foo/", path::Style::native);
281   Paths.emplace_back("/foo//", path::Style::native);
282   Paths.emplace_back("//net/foo/", path::Style::native);
283   Paths.emplace_back("c:\\foo\\", path::Style::windows);
284 
285   for (auto &Path : Paths) {
286     SCOPED_TRACE(Path.first);
287     StringRef LastComponent = *path::rbegin(Path.first, Path.second);
288     EXPECT_EQ(".", LastComponent);
289   }
290 
291   SmallVector<std::pair<StringRef, path::Style>, 3> RootPaths;
292   RootPaths.emplace_back("/", path::Style::native);
293   RootPaths.emplace_back("//net/", path::Style::native);
294   RootPaths.emplace_back("c:\\", path::Style::windows);
295   RootPaths.emplace_back("//net//", path::Style::native);
296   RootPaths.emplace_back("c:\\\\", path::Style::windows);
297 
298   for (auto &Path : RootPaths) {
299     SCOPED_TRACE(Path.first);
300     StringRef LastComponent = *path::rbegin(Path.first, Path.second);
301     EXPECT_EQ(1u, LastComponent.size());
302     EXPECT_TRUE(path::is_separator(LastComponent[0], Path.second));
303   }
304 }
305 
306 TEST(Support, HomeDirectory) {
307   std::string expected;
308 #ifdef _WIN32
309   if (wchar_t const *path = ::_wgetenv(L"USERPROFILE")) {
310     auto pathLen = ::wcslen(path);
311     ArrayRef<char> ref{reinterpret_cast<char const *>(path),
312                        pathLen * sizeof(wchar_t)};
313     convertUTF16ToUTF8String(ref, expected);
314   }
315 #else
316   if (char const *path = ::getenv("HOME"))
317     expected = path;
318 #endif
319   // Do not try to test it if we don't know what to expect.
320   // On Windows we use something better than env vars.
321   if (!expected.empty()) {
322     SmallString<128> HomeDir;
323     auto status = path::home_directory(HomeDir);
324     EXPECT_TRUE(status);
325     EXPECT_EQ(expected, HomeDir);
326   }
327 }
328 
329 #ifdef LLVM_ON_UNIX
330 TEST(Support, HomeDirectoryWithNoEnv) {
331   std::string OriginalStorage;
332   char const *OriginalEnv = ::getenv("HOME");
333   if (OriginalEnv) {
334     // We're going to unset it, so make a copy and save a pointer to the copy
335     // so that we can reset it at the end of the test.
336     OriginalStorage = OriginalEnv;
337     OriginalEnv = OriginalStorage.c_str();
338   }
339 
340   // Don't run the test if we have nothing to compare against.
341   struct passwd *pw = getpwuid(getuid());
342   if (!pw || !pw->pw_dir) return;
343 
344   ::unsetenv("HOME");
345   EXPECT_EQ(nullptr, ::getenv("HOME"));
346   std::string PwDir = pw->pw_dir;
347 
348   SmallString<128> HomeDir;
349   auto status = path::home_directory(HomeDir);
350   EXPECT_TRUE(status);
351   EXPECT_EQ(PwDir, HomeDir);
352 
353   // Now put the environment back to its original state (meaning that if it was
354   // unset before, we don't reset it).
355   if (OriginalEnv) ::setenv("HOME", OriginalEnv, 1);
356 }
357 #endif
358 
359 TEST(Support, TempDirectory) {
360   SmallString<32> TempDir;
361   path::system_temp_directory(false, TempDir);
362   EXPECT_TRUE(!TempDir.empty());
363   TempDir.clear();
364   path::system_temp_directory(true, TempDir);
365   EXPECT_TRUE(!TempDir.empty());
366 }
367 
368 #ifdef _WIN32
369 static std::string path2regex(std::string Path) {
370   size_t Pos = 0;
371   while ((Pos = Path.find('\\', Pos)) != std::string::npos) {
372     Path.replace(Pos, 1, "\\\\");
373     Pos += 2;
374   }
375   return Path;
376 }
377 
378 /// Helper for running temp dir test in separated process. See below.
379 #define EXPECT_TEMP_DIR(prepare, expected)                                     \
380   EXPECT_EXIT(                                                                 \
381       {                                                                        \
382         prepare;                                                               \
383         SmallString<300> TempDir;                                              \
384         path::system_temp_directory(true, TempDir);                            \
385         raw_os_ostream(std::cerr) << TempDir;                                  \
386         std::exit(0);                                                          \
387       },                                                                       \
388       ::testing::ExitedWithCode(0), path2regex(expected))
389 
390 TEST(SupportDeathTest, TempDirectoryOnWindows) {
391   // In this test we want to check how system_temp_directory responds to
392   // different values of specific env vars. To prevent corrupting env vars of
393   // the current process all checks are done in separated processes.
394   EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"C:\\OtherFolder"), "C:\\OtherFolder");
395   EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"C:/Unix/Path/Seperators"),
396                   "C:\\Unix\\Path\\Seperators");
397   EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"Local Path"), ".+\\Local Path$");
398   EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"F:\\TrailingSep\\"), "F:\\TrailingSep");
399   EXPECT_TEMP_DIR(
400       _wputenv_s(L"TMP", L"C:\\2\x03C0r-\x00B5\x00B3\\\x2135\x2080"),
401       "C:\\2\xCF\x80r-\xC2\xB5\xC2\xB3\\\xE2\x84\xB5\xE2\x82\x80");
402 
403   // Test $TMP empty, $TEMP set.
404   EXPECT_TEMP_DIR(
405       {
406         _wputenv_s(L"TMP", L"");
407         _wputenv_s(L"TEMP", L"C:\\Valid\\Path");
408       },
409       "C:\\Valid\\Path");
410 
411   // All related env vars empty
412   EXPECT_TEMP_DIR(
413   {
414     _wputenv_s(L"TMP", L"");
415     _wputenv_s(L"TEMP", L"");
416     _wputenv_s(L"USERPROFILE", L"");
417   },
418     "C:\\Temp");
419 
420   // Test evn var / path with 260 chars.
421   SmallString<270> Expected{"C:\\Temp\\AB\\123456789"};
422   while (Expected.size() < 260)
423     Expected.append("\\DirNameWith19Charss");
424   ASSERT_EQ(260U, Expected.size());
425   EXPECT_TEMP_DIR(_putenv_s("TMP", Expected.c_str()), Expected.c_str());
426 }
427 #endif
428 
429 class FileSystemTest : public testing::Test {
430 protected:
431   /// Unique temporary directory in which all created filesystem entities must
432   /// be placed. It is removed at the end of each test (must be empty).
433   SmallString<128> TestDirectory;
434   SmallString<128> NonExistantFile;
435 
436   void SetUp() override {
437     ASSERT_NO_ERROR(
438         fs::createUniqueDirectory("file-system-test", TestDirectory));
439     // We don't care about this specific file.
440     errs() << "Test Directory: " << TestDirectory << '\n';
441     errs().flush();
442     NonExistantFile = TestDirectory;
443 
444     // Even though this value is hardcoded, is a 128-bit GUID, so we should be
445     // guaranteed that this file will never exist.
446     sys::path::append(NonExistantFile, "1B28B495C16344CB9822E588CD4C3EF0");
447   }
448 
449   void TearDown() override { ASSERT_NO_ERROR(fs::remove(TestDirectory.str())); }
450 };
451 
452 TEST_F(FileSystemTest, Unique) {
453   // Create a temp file.
454   int FileDescriptor;
455   SmallString<64> TempPath;
456   ASSERT_NO_ERROR(
457       fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
458 
459   // The same file should return an identical unique id.
460   fs::UniqueID F1, F2;
461   ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F1));
462   ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F2));
463   ASSERT_EQ(F1, F2);
464 
465   // Different files should return different unique ids.
466   int FileDescriptor2;
467   SmallString<64> TempPath2;
468   ASSERT_NO_ERROR(
469       fs::createTemporaryFile("prefix", "temp", FileDescriptor2, TempPath2));
470 
471   fs::UniqueID D;
472   ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D));
473   ASSERT_NE(D, F1);
474   ::close(FileDescriptor2);
475 
476   ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
477 
478   // Two paths representing the same file on disk should still provide the
479   // same unique id.  We can test this by making a hard link.
480   ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2)));
481   fs::UniqueID D2;
482   ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D2));
483   ASSERT_EQ(D2, F1);
484 
485   ::close(FileDescriptor);
486 
487   SmallString<128> Dir1;
488   ASSERT_NO_ERROR(
489      fs::createUniqueDirectory("dir1", Dir1));
490   ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F1));
491   ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F2));
492   ASSERT_EQ(F1, F2);
493 
494   SmallString<128> Dir2;
495   ASSERT_NO_ERROR(
496      fs::createUniqueDirectory("dir2", Dir2));
497   ASSERT_NO_ERROR(fs::getUniqueID(Dir2.c_str(), F2));
498   ASSERT_NE(F1, F2);
499   ASSERT_NO_ERROR(fs::remove(Dir1));
500   ASSERT_NO_ERROR(fs::remove(Dir2));
501   ASSERT_NO_ERROR(fs::remove(TempPath2));
502   ASSERT_NO_ERROR(fs::remove(TempPath));
503 }
504 
505 TEST_F(FileSystemTest, RealPath) {
506   ASSERT_NO_ERROR(
507       fs::create_directories(Twine(TestDirectory) + "/test1/test2/test3"));
508   ASSERT_TRUE(fs::exists(Twine(TestDirectory) + "/test1/test2/test3"));
509 
510   SmallString<64> RealBase;
511   SmallString<64> Expected;
512   SmallString<64> Actual;
513 
514   // TestDirectory itself might be under a symlink or have been specified with
515   // a different case than the existing temp directory.  In such cases real_path
516   // on the concatenated path will differ in the TestDirectory portion from
517   // how we specified it.  Make sure to compare against the real_path of the
518   // TestDirectory, and not just the value of TestDirectory.
519   ASSERT_NO_ERROR(fs::real_path(TestDirectory, RealBase));
520   path::native(Twine(RealBase) + "/test1/test2", Expected);
521 
522   ASSERT_NO_ERROR(fs::real_path(
523       Twine(TestDirectory) + "/././test1/../test1/test2/./test3/..", Actual));
524 
525   EXPECT_EQ(Expected, Actual);
526 
527   SmallString<64> HomeDir;
528 
529   // This can fail if $HOME is not set and getpwuid fails.
530   bool Result = llvm::sys::path::home_directory(HomeDir);
531   if (Result) {
532     ASSERT_NO_ERROR(fs::real_path(HomeDir, Expected));
533     ASSERT_NO_ERROR(fs::real_path("~", Actual, true));
534     EXPECT_EQ(Expected, Actual);
535     ASSERT_NO_ERROR(fs::real_path("~/", Actual, true));
536     EXPECT_EQ(Expected, Actual);
537   }
538 
539   ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/test1"));
540 }
541 
542 TEST_F(FileSystemTest, ExpandTilde) {
543   SmallString<64> Expected;
544   SmallString<64> Actual;
545   SmallString<64> HomeDir;
546 
547   // This can fail if $HOME is not set and getpwuid fails.
548   bool Result = llvm::sys::path::home_directory(HomeDir);
549   if (Result) {
550     fs::expand_tilde(HomeDir, Expected);
551 
552     fs::expand_tilde("~", Actual);
553     EXPECT_EQ(Expected, Actual);
554 
555 #ifdef _WIN32
556     Expected += "\\foo";
557     fs::expand_tilde("~\\foo", Actual);
558 #else
559     Expected += "/foo";
560     fs::expand_tilde("~/foo", Actual);
561 #endif
562 
563     EXPECT_EQ(Expected, Actual);
564   }
565 }
566 
567 #ifdef LLVM_ON_UNIX
568 TEST_F(FileSystemTest, RealPathNoReadPerm) {
569   SmallString<64> Expanded;
570 
571   ASSERT_NO_ERROR(
572     fs::create_directories(Twine(TestDirectory) + "/noreadperm"));
573   ASSERT_TRUE(fs::exists(Twine(TestDirectory) + "/noreadperm"));
574 
575   fs::setPermissions(Twine(TestDirectory) + "/noreadperm", fs::no_perms);
576   fs::setPermissions(Twine(TestDirectory) + "/noreadperm", fs::all_exe);
577 
578   ASSERT_NO_ERROR(fs::real_path(Twine(TestDirectory) + "/noreadperm", Expanded,
579                                 false));
580 
581   ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/noreadperm"));
582 }
583 #endif
584 
585 
586 TEST_F(FileSystemTest, TempFileKeepDiscard) {
587   // We can keep then discard.
588   auto TempFileOrError = fs::TempFile::create(TestDirectory + "/test-%%%%");
589   ASSERT_TRUE((bool)TempFileOrError);
590   fs::TempFile File = std::move(*TempFileOrError);
591   ASSERT_EQ(-1, TempFileOrError->FD);
592   ASSERT_FALSE((bool)File.keep(TestDirectory + "/keep"));
593   ASSERT_FALSE((bool)File.discard());
594   ASSERT_TRUE(fs::exists(TestDirectory + "/keep"));
595   ASSERT_NO_ERROR(fs::remove(TestDirectory + "/keep"));
596 }
597 
598 TEST_F(FileSystemTest, TempFileDiscardDiscard) {
599   // We can discard twice.
600   auto TempFileOrError = fs::TempFile::create(TestDirectory + "/test-%%%%");
601   ASSERT_TRUE((bool)TempFileOrError);
602   fs::TempFile File = std::move(*TempFileOrError);
603   ASSERT_EQ(-1, TempFileOrError->FD);
604   ASSERT_FALSE((bool)File.discard());
605   ASSERT_FALSE((bool)File.discard());
606   ASSERT_FALSE(fs::exists(TestDirectory + "/keep"));
607 }
608 
609 TEST_F(FileSystemTest, TempFiles) {
610   // Create a temp file.
611   int FileDescriptor;
612   SmallString<64> TempPath;
613   ASSERT_NO_ERROR(
614       fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
615 
616   // Make sure it exists.
617   ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
618 
619   // Create another temp tile.
620   int FD2;
621   SmallString<64> TempPath2;
622   ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD2, TempPath2));
623   ASSERT_TRUE(TempPath2.endswith(".temp"));
624   ASSERT_NE(TempPath.str(), TempPath2.str());
625 
626   fs::file_status A, B;
627   ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
628   ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
629   EXPECT_FALSE(fs::equivalent(A, B));
630 
631   ::close(FD2);
632 
633   // Remove Temp2.
634   ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
635   ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
636   ASSERT_EQ(fs::remove(Twine(TempPath2), false),
637             errc::no_such_file_or_directory);
638 
639   std::error_code EC = fs::status(TempPath2.c_str(), B);
640   EXPECT_EQ(EC, errc::no_such_file_or_directory);
641   EXPECT_EQ(B.type(), fs::file_type::file_not_found);
642 
643   // Make sure Temp2 doesn't exist.
644   ASSERT_EQ(fs::access(Twine(TempPath2), sys::fs::AccessMode::Exist),
645             errc::no_such_file_or_directory);
646 
647   SmallString<64> TempPath3;
648   ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "", TempPath3));
649   ASSERT_FALSE(TempPath3.endswith("."));
650   FileRemover Cleanup3(TempPath3);
651 
652   // Create a hard link to Temp1.
653   ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2)));
654   bool equal;
655   ASSERT_NO_ERROR(fs::equivalent(Twine(TempPath), Twine(TempPath2), equal));
656   EXPECT_TRUE(equal);
657   ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
658   ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
659   EXPECT_TRUE(fs::equivalent(A, B));
660 
661   // Remove Temp1.
662   ::close(FileDescriptor);
663   ASSERT_NO_ERROR(fs::remove(Twine(TempPath)));
664 
665   // Remove the hard link.
666   ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
667 
668   // Make sure Temp1 doesn't exist.
669   ASSERT_EQ(fs::access(Twine(TempPath), sys::fs::AccessMode::Exist),
670             errc::no_such_file_or_directory);
671 
672 #ifdef _WIN32
673   // Path name > 260 chars should get an error.
674   const char *Path270 =
675     "abcdefghijklmnopqrstuvwxyz9abcdefghijklmnopqrstuvwxyz8"
676     "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
677     "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
678     "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
679     "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
680   EXPECT_EQ(fs::createUniqueFile(Path270, FileDescriptor, TempPath),
681             errc::invalid_argument);
682   // Relative path < 247 chars, no problem.
683   const char *Path216 =
684     "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
685     "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
686     "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
687     "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
688   ASSERT_NO_ERROR(fs::createTemporaryFile(Path216, "", TempPath));
689   ASSERT_NO_ERROR(fs::remove(Twine(TempPath)));
690 #endif
691 }
692 
693 TEST_F(FileSystemTest, TempFileCollisions) {
694   SmallString<128> TestDirectory;
695   ASSERT_NO_ERROR(
696       fs::createUniqueDirectory("CreateUniqueFileTest", TestDirectory));
697   FileRemover Cleanup(TestDirectory);
698   SmallString<128> Model = TestDirectory;
699   path::append(Model, "%.tmp");
700   SmallString<128> Path;
701   std::vector<fs::TempFile> TempFiles;
702 
703   auto TryCreateTempFile = [&]() {
704     Expected<fs::TempFile> T = fs::TempFile::create(Model);
705     if (T) {
706       TempFiles.push_back(std::move(*T));
707       return true;
708     } else {
709       logAllUnhandledErrors(T.takeError(), errs(),
710                             "Failed to create temporary file: ");
711       return false;
712     }
713   };
714 
715   // Our single-character template allows for 16 unique names. Check that
716   // calling TryCreateTempFile repeatedly results in 16 successes.
717   // Because the test depends on random numbers, it could theoretically fail.
718   // However, the probability of this happening is tiny: with 32 calls, each
719   // of which will retry up to 128 times, to not get a given digit we would
720   // have to fail at least 15 + 17 * 128 = 2191 attempts. The probability of
721   // 2191 attempts not producing a given hexadecimal digit is
722   // (1 - 1/16) ** 2191 or 3.88e-62.
723   int Successes = 0;
724   for (int i = 0; i < 32; ++i)
725     if (TryCreateTempFile()) ++Successes;
726   EXPECT_EQ(Successes, 16);
727 
728   for (fs::TempFile &T : TempFiles)
729     cantFail(T.discard());
730 }
731 
732 TEST_F(FileSystemTest, CreateDir) {
733   ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
734   ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
735   ASSERT_EQ(fs::create_directory(Twine(TestDirectory) + "foo", false),
736             errc::file_exists);
737   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "foo"));
738 
739 #ifdef LLVM_ON_UNIX
740   // Set a 0000 umask so that we can test our directory permissions.
741   mode_t OldUmask = ::umask(0000);
742 
743   fs::file_status Status;
744   ASSERT_NO_ERROR(
745       fs::create_directory(Twine(TestDirectory) + "baz500", false,
746                            fs::perms::owner_read | fs::perms::owner_exe));
747   ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz500", Status));
748   ASSERT_EQ(Status.permissions() & fs::perms::all_all,
749             fs::perms::owner_read | fs::perms::owner_exe);
750   ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "baz777", false,
751                                        fs::perms::all_all));
752   ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz777", Status));
753   ASSERT_EQ(Status.permissions() & fs::perms::all_all, fs::perms::all_all);
754 
755   // Restore umask to be safe.
756   ::umask(OldUmask);
757 #endif
758 
759 #ifdef _WIN32
760   // Prove that create_directories() can handle a pathname > 248 characters,
761   // which is the documented limit for CreateDirectory().
762   // (248 is MAX_PATH subtracting room for an 8.3 filename.)
763   // Generate a directory path guaranteed to fall into that range.
764   size_t TmpLen = TestDirectory.size();
765   const char *OneDir = "\\123456789";
766   size_t OneDirLen = strlen(OneDir);
767   ASSERT_LT(OneDirLen, 12U);
768   size_t NLevels = ((248 - TmpLen) / OneDirLen) + 1;
769   SmallString<260> LongDir(TestDirectory);
770   for (size_t I = 0; I < NLevels; ++I)
771     LongDir.append(OneDir);
772   ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir)));
773   ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir)));
774   ASSERT_EQ(fs::create_directories(Twine(LongDir), false),
775             errc::file_exists);
776   // Tidy up, "recursively" removing the directories.
777   StringRef ThisDir(LongDir);
778   for (size_t J = 0; J < NLevels; ++J) {
779     ASSERT_NO_ERROR(fs::remove(ThisDir));
780     ThisDir = path::parent_path(ThisDir);
781   }
782 
783   // Also verify that paths with Unix separators are handled correctly.
784   std::string LongPathWithUnixSeparators(TestDirectory.str());
785   // Add at least one subdirectory to TestDirectory, and replace slashes with
786   // backslashes
787   do {
788     LongPathWithUnixSeparators.append("/DirNameWith19Charss");
789   } while (LongPathWithUnixSeparators.size() < 260);
790   std::replace(LongPathWithUnixSeparators.begin(),
791                LongPathWithUnixSeparators.end(),
792                '\\', '/');
793   ASSERT_NO_ERROR(fs::create_directories(Twine(LongPathWithUnixSeparators)));
794   // cleanup
795   ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) +
796                                          "/DirNameWith19Charss"));
797 
798   // Similarly for a relative pathname.  Need to set the current directory to
799   // TestDirectory so that the one we create ends up in the right place.
800   char PreviousDir[260];
801   size_t PreviousDirLen = ::GetCurrentDirectoryA(260, PreviousDir);
802   ASSERT_GT(PreviousDirLen, 0U);
803   ASSERT_LT(PreviousDirLen, 260U);
804   ASSERT_NE(::SetCurrentDirectoryA(TestDirectory.c_str()), 0);
805   LongDir.clear();
806   // Generate a relative directory name with absolute length > 248.
807   size_t LongDirLen = 249 - TestDirectory.size();
808   LongDir.assign(LongDirLen, 'a');
809   ASSERT_NO_ERROR(fs::create_directory(Twine(LongDir)));
810   // While we're here, prove that .. and . handling works in these long paths.
811   const char *DotDotDirs = "\\..\\.\\b";
812   LongDir.append(DotDotDirs);
813   ASSERT_NO_ERROR(fs::create_directory("b"));
814   ASSERT_EQ(fs::create_directory(Twine(LongDir), false), errc::file_exists);
815   // And clean up.
816   ASSERT_NO_ERROR(fs::remove("b"));
817   ASSERT_NO_ERROR(fs::remove(
818     Twine(LongDir.substr(0, LongDir.size() - strlen(DotDotDirs)))));
819   ASSERT_NE(::SetCurrentDirectoryA(PreviousDir), 0);
820 #endif
821 }
822 
823 TEST_F(FileSystemTest, DirectoryIteration) {
824   std::error_code ec;
825   for (fs::directory_iterator i(".", ec), e; i != e; i.increment(ec))
826     ASSERT_NO_ERROR(ec);
827 
828   // Create a known hierarchy to recurse over.
829   ASSERT_NO_ERROR(
830       fs::create_directories(Twine(TestDirectory) + "/recursive/a0/aa1"));
831   ASSERT_NO_ERROR(
832       fs::create_directories(Twine(TestDirectory) + "/recursive/a0/ab1"));
833   ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) +
834                                          "/recursive/dontlookhere/da1"));
835   ASSERT_NO_ERROR(
836       fs::create_directories(Twine(TestDirectory) + "/recursive/z0/za1"));
837   ASSERT_NO_ERROR(
838       fs::create_directories(Twine(TestDirectory) + "/recursive/pop/p1"));
839   typedef std::vector<std::string> v_t;
840   v_t visited;
841   for (fs::recursive_directory_iterator i(Twine(TestDirectory)
842          + "/recursive", ec), e; i != e; i.increment(ec)){
843     ASSERT_NO_ERROR(ec);
844     if (path::filename(i->path()) == "p1") {
845       i.pop();
846       // FIXME: recursive_directory_iterator should be more robust.
847       if (i == e) break;
848     }
849     if (path::filename(i->path()) == "dontlookhere")
850       i.no_push();
851     visited.push_back(path::filename(i->path()));
852   }
853   v_t::const_iterator a0 = find(visited, "a0");
854   v_t::const_iterator aa1 = find(visited, "aa1");
855   v_t::const_iterator ab1 = find(visited, "ab1");
856   v_t::const_iterator dontlookhere = find(visited, "dontlookhere");
857   v_t::const_iterator da1 = find(visited, "da1");
858   v_t::const_iterator z0 = find(visited, "z0");
859   v_t::const_iterator za1 = find(visited, "za1");
860   v_t::const_iterator pop = find(visited, "pop");
861   v_t::const_iterator p1 = find(visited, "p1");
862 
863   // Make sure that each path was visited correctly.
864   ASSERT_NE(a0, visited.end());
865   ASSERT_NE(aa1, visited.end());
866   ASSERT_NE(ab1, visited.end());
867   ASSERT_NE(dontlookhere, visited.end());
868   ASSERT_EQ(da1, visited.end()); // Not visited.
869   ASSERT_NE(z0, visited.end());
870   ASSERT_NE(za1, visited.end());
871   ASSERT_NE(pop, visited.end());
872   ASSERT_EQ(p1, visited.end()); // Not visited.
873 
874   // Make sure that parents were visited before children. No other ordering
875   // guarantees can be made across siblings.
876   ASSERT_LT(a0, aa1);
877   ASSERT_LT(a0, ab1);
878   ASSERT_LT(z0, za1);
879 
880   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/aa1"));
881   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/ab1"));
882   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0"));
883   ASSERT_NO_ERROR(
884       fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere/da1"));
885   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere"));
886   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop/p1"));
887   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop"));
888   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0/za1"));
889   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0"));
890   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive"));
891 
892   // Test recursive_directory_iterator level()
893   ASSERT_NO_ERROR(
894       fs::create_directories(Twine(TestDirectory) + "/reclevel/a/b/c"));
895   fs::recursive_directory_iterator I(Twine(TestDirectory) + "/reclevel", ec), E;
896   for (int l = 0; I != E; I.increment(ec), ++l) {
897     ASSERT_NO_ERROR(ec);
898     EXPECT_EQ(I.level(), l);
899   }
900   EXPECT_EQ(I, E);
901   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a/b/c"));
902   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a/b"));
903   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a"));
904   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel"));
905 }
906 
907 #ifdef LLVM_ON_UNIX
908 TEST_F(FileSystemTest, BrokenSymlinkDirectoryIteration) {
909   // Create a known hierarchy to recurse over.
910   ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) + "/symlink"));
911   ASSERT_NO_ERROR(
912       fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/a"));
913   ASSERT_NO_ERROR(
914       fs::create_directories(Twine(TestDirectory) + "/symlink/b/bb"));
915   ASSERT_NO_ERROR(
916       fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/b/ba"));
917   ASSERT_NO_ERROR(
918       fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/b/bc"));
919   ASSERT_NO_ERROR(
920       fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/c"));
921   ASSERT_NO_ERROR(
922       fs::create_directories(Twine(TestDirectory) + "/symlink/d/dd/ddd"));
923   ASSERT_NO_ERROR(fs::create_link(Twine(TestDirectory) + "/symlink/d/dd",
924                                   Twine(TestDirectory) + "/symlink/d/da"));
925   ASSERT_NO_ERROR(
926       fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/e"));
927 
928   typedef std::vector<std::string> v_t;
929   v_t VisitedNonBrokenSymlinks;
930   v_t VisitedBrokenSymlinks;
931   std::error_code ec;
932   using testing::UnorderedElementsAre;
933   using testing::UnorderedElementsAreArray;
934 
935   // Broken symbol links are expected to throw an error.
936   for (fs::directory_iterator i(Twine(TestDirectory) + "/symlink", ec), e;
937        i != e; i.increment(ec)) {
938     ASSERT_NO_ERROR(ec);
939     if (i->status().getError() ==
940         std::make_error_code(std::errc::no_such_file_or_directory)) {
941       VisitedBrokenSymlinks.push_back(path::filename(i->path()));
942       continue;
943     }
944     VisitedNonBrokenSymlinks.push_back(path::filename(i->path()));
945   }
946   EXPECT_THAT(VisitedNonBrokenSymlinks, UnorderedElementsAre("b", "d"));
947   VisitedNonBrokenSymlinks.clear();
948 
949   EXPECT_THAT(VisitedBrokenSymlinks, UnorderedElementsAre("a", "c", "e"));
950   VisitedBrokenSymlinks.clear();
951 
952   // Broken symbol links are expected to throw an error.
953   for (fs::recursive_directory_iterator i(
954       Twine(TestDirectory) + "/symlink", ec), e; i != e; i.increment(ec)) {
955     ASSERT_NO_ERROR(ec);
956     if (i->status().getError() ==
957         std::make_error_code(std::errc::no_such_file_or_directory)) {
958       VisitedBrokenSymlinks.push_back(path::filename(i->path()));
959       continue;
960     }
961     VisitedNonBrokenSymlinks.push_back(path::filename(i->path()));
962   }
963   EXPECT_THAT(VisitedNonBrokenSymlinks,
964               UnorderedElementsAre("b", "bb", "d", "da", "dd", "ddd", "ddd"));
965   VisitedNonBrokenSymlinks.clear();
966 
967   EXPECT_THAT(VisitedBrokenSymlinks,
968               UnorderedElementsAre("a", "ba", "bc", "c", "e"));
969   VisitedBrokenSymlinks.clear();
970 
971   for (fs::recursive_directory_iterator i(
972       Twine(TestDirectory) + "/symlink", ec, /*follow_symlinks=*/false), e;
973        i != e; i.increment(ec)) {
974     ASSERT_NO_ERROR(ec);
975     if (i->status().getError() ==
976         std::make_error_code(std::errc::no_such_file_or_directory)) {
977       VisitedBrokenSymlinks.push_back(path::filename(i->path()));
978       continue;
979     }
980     VisitedNonBrokenSymlinks.push_back(path::filename(i->path()));
981   }
982   EXPECT_THAT(VisitedNonBrokenSymlinks,
983               UnorderedElementsAreArray({"a", "b", "ba", "bb", "bc", "c", "d",
984                                          "da", "dd", "ddd", "e"}));
985   VisitedNonBrokenSymlinks.clear();
986 
987   EXPECT_THAT(VisitedBrokenSymlinks, UnorderedElementsAre());
988   VisitedBrokenSymlinks.clear();
989 
990   ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/symlink"));
991 }
992 #endif
993 
994 TEST_F(FileSystemTest, Remove) {
995   SmallString<64> BaseDir;
996   SmallString<64> Paths[4];
997   int fds[4];
998   ASSERT_NO_ERROR(fs::createUniqueDirectory("fs_remove", BaseDir));
999 
1000   ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir) + "/foo/bar/baz"));
1001   ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir) + "/foo/bar/buzz"));
1002   ASSERT_NO_ERROR(fs::createUniqueFile(
1003       Twine(BaseDir) + "/foo/bar/baz/%%%%%%.tmp", fds[0], Paths[0]));
1004   ASSERT_NO_ERROR(fs::createUniqueFile(
1005       Twine(BaseDir) + "/foo/bar/baz/%%%%%%.tmp", fds[1], Paths[1]));
1006   ASSERT_NO_ERROR(fs::createUniqueFile(
1007       Twine(BaseDir) + "/foo/bar/buzz/%%%%%%.tmp", fds[2], Paths[2]));
1008   ASSERT_NO_ERROR(fs::createUniqueFile(
1009       Twine(BaseDir) + "/foo/bar/buzz/%%%%%%.tmp", fds[3], Paths[3]));
1010 
1011   for (int fd : fds)
1012     ::close(fd);
1013 
1014   EXPECT_TRUE(fs::exists(Twine(BaseDir) + "/foo/bar/baz"));
1015   EXPECT_TRUE(fs::exists(Twine(BaseDir) + "/foo/bar/buzz"));
1016   EXPECT_TRUE(fs::exists(Paths[0]));
1017   EXPECT_TRUE(fs::exists(Paths[1]));
1018   EXPECT_TRUE(fs::exists(Paths[2]));
1019   EXPECT_TRUE(fs::exists(Paths[3]));
1020 
1021   ASSERT_NO_ERROR(fs::remove_directories("D:/footest"));
1022 
1023   ASSERT_NO_ERROR(fs::remove_directories(BaseDir));
1024   ASSERT_FALSE(fs::exists(BaseDir));
1025 }
1026 
1027 #ifdef _WIN32
1028 TEST_F(FileSystemTest, CarriageReturn) {
1029   SmallString<128> FilePathname(TestDirectory);
1030   std::error_code EC;
1031   path::append(FilePathname, "test");
1032 
1033   {
1034     raw_fd_ostream File(FilePathname, EC, sys::fs::OF_Text);
1035     ASSERT_NO_ERROR(EC);
1036     File << '\n';
1037   }
1038   {
1039     auto Buf = MemoryBuffer::getFile(FilePathname.str());
1040     EXPECT_TRUE((bool)Buf);
1041     EXPECT_EQ(Buf.get()->getBuffer(), "\r\n");
1042   }
1043 
1044   {
1045     raw_fd_ostream File(FilePathname, EC, sys::fs::OF_None);
1046     ASSERT_NO_ERROR(EC);
1047     File << '\n';
1048   }
1049   {
1050     auto Buf = MemoryBuffer::getFile(FilePathname.str());
1051     EXPECT_TRUE((bool)Buf);
1052     EXPECT_EQ(Buf.get()->getBuffer(), "\n");
1053   }
1054   ASSERT_NO_ERROR(fs::remove(Twine(FilePathname)));
1055 }
1056 #endif
1057 
1058 TEST_F(FileSystemTest, Resize) {
1059   int FD;
1060   SmallString<64> TempPath;
1061   ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1062   ASSERT_NO_ERROR(fs::resize_file(FD, 123));
1063   fs::file_status Status;
1064   ASSERT_NO_ERROR(fs::status(FD, Status));
1065   ASSERT_EQ(Status.getSize(), 123U);
1066   ::close(FD);
1067   ASSERT_NO_ERROR(fs::remove(TempPath));
1068 }
1069 
1070 TEST_F(FileSystemTest, MD5) {
1071   int FD;
1072   SmallString<64> TempPath;
1073   ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1074   StringRef Data("abcdefghijklmnopqrstuvwxyz");
1075   ASSERT_EQ(write(FD, Data.data(), Data.size()), static_cast<ssize_t>(Data.size()));
1076   lseek(FD, 0, SEEK_SET);
1077   auto Hash = fs::md5_contents(FD);
1078   ::close(FD);
1079   ASSERT_NO_ERROR(Hash.getError());
1080 
1081   EXPECT_STREQ("c3fcd3d76192e4007dfb496cca67e13b", Hash->digest().c_str());
1082 }
1083 
1084 TEST_F(FileSystemTest, FileMapping) {
1085   // Create a temp file.
1086   int FileDescriptor;
1087   SmallString<64> TempPath;
1088   ASSERT_NO_ERROR(
1089       fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
1090   unsigned Size = 4096;
1091   ASSERT_NO_ERROR(fs::resize_file(FileDescriptor, Size));
1092 
1093   // Map in temp file and add some content
1094   std::error_code EC;
1095   StringRef Val("hello there");
1096   {
1097     fs::mapped_file_region mfr(fs::convertFDToNativeFile(FileDescriptor),
1098                                fs::mapped_file_region::readwrite, Size, 0, EC);
1099     ASSERT_NO_ERROR(EC);
1100     std::copy(Val.begin(), Val.end(), mfr.data());
1101     // Explicitly add a 0.
1102     mfr.data()[Val.size()] = 0;
1103     // Unmap temp file
1104   }
1105   ASSERT_EQ(close(FileDescriptor), 0);
1106 
1107   // Map it back in read-only
1108   {
1109     int FD;
1110     EC = fs::openFileForRead(Twine(TempPath), FD);
1111     ASSERT_NO_ERROR(EC);
1112     fs::mapped_file_region mfr(fs::convertFDToNativeFile(FD),
1113                                fs::mapped_file_region::readonly, Size, 0, EC);
1114     ASSERT_NO_ERROR(EC);
1115 
1116     // Verify content
1117     EXPECT_EQ(StringRef(mfr.const_data()), Val);
1118 
1119     // Unmap temp file
1120     fs::mapped_file_region m(fs::convertFDToNativeFile(FD),
1121                              fs::mapped_file_region::readonly, Size, 0, EC);
1122     ASSERT_NO_ERROR(EC);
1123     ASSERT_EQ(close(FD), 0);
1124   }
1125   ASSERT_NO_ERROR(fs::remove(TempPath));
1126 }
1127 
1128 TEST(Support, NormalizePath) {
1129   using TestTuple = std::tuple<const char *, const char *, const char *>;
1130   std::vector<TestTuple> Tests;
1131   Tests.emplace_back("a", "a", "a");
1132   Tests.emplace_back("a/b", "a\\b", "a/b");
1133   Tests.emplace_back("a\\b", "a\\b", "a/b");
1134   Tests.emplace_back("a\\\\b", "a\\\\b", "a\\\\b");
1135   Tests.emplace_back("\\a", "\\a", "/a");
1136   Tests.emplace_back("a\\", "a\\", "a/");
1137 
1138   for (auto &T : Tests) {
1139     SmallString<64> Win(std::get<0>(T));
1140     SmallString<64> Posix(Win);
1141     path::native(Win, path::Style::windows);
1142     path::native(Posix, path::Style::posix);
1143     EXPECT_EQ(std::get<1>(T), Win);
1144     EXPECT_EQ(std::get<2>(T), Posix);
1145   }
1146 
1147 #if defined(_WIN32)
1148   SmallString<64> PathHome;
1149   path::home_directory(PathHome);
1150 
1151   const char *Path7a = "~/aaa";
1152   SmallString<64> Path7(Path7a);
1153   path::native(Path7);
1154   EXPECT_TRUE(Path7.endswith("\\aaa"));
1155   EXPECT_TRUE(Path7.startswith(PathHome));
1156   EXPECT_EQ(Path7.size(), PathHome.size() + strlen(Path7a + 1));
1157 
1158   const char *Path8a = "~";
1159   SmallString<64> Path8(Path8a);
1160   path::native(Path8);
1161   EXPECT_EQ(Path8, PathHome);
1162 
1163   const char *Path9a = "~aaa";
1164   SmallString<64> Path9(Path9a);
1165   path::native(Path9);
1166   EXPECT_EQ(Path9, "~aaa");
1167 
1168   const char *Path10a = "aaa/~/b";
1169   SmallString<64> Path10(Path10a);
1170   path::native(Path10);
1171   EXPECT_EQ(Path10, "aaa\\~\\b");
1172 #endif
1173 }
1174 
1175 TEST(Support, RemoveLeadingDotSlash) {
1176   StringRef Path1("././/foolz/wat");
1177   StringRef Path2("./////");
1178 
1179   Path1 = path::remove_leading_dotslash(Path1);
1180   EXPECT_EQ(Path1, "foolz/wat");
1181   Path2 = path::remove_leading_dotslash(Path2);
1182   EXPECT_EQ(Path2, "");
1183 }
1184 
1185 static std::string remove_dots(StringRef path, bool remove_dot_dot,
1186                                path::Style style) {
1187   SmallString<256> buffer(path);
1188   path::remove_dots(buffer, remove_dot_dot, style);
1189   return buffer.str();
1190 }
1191 
1192 TEST(Support, RemoveDots) {
1193   EXPECT_EQ("foolz\\wat",
1194             remove_dots(".\\.\\\\foolz\\wat", false, path::Style::windows));
1195   EXPECT_EQ("", remove_dots(".\\\\\\\\\\", false, path::Style::windows));
1196 
1197   EXPECT_EQ("a\\..\\b\\c",
1198             remove_dots(".\\a\\..\\b\\c", false, path::Style::windows));
1199   EXPECT_EQ("b\\c", remove_dots(".\\a\\..\\b\\c", true, path::Style::windows));
1200   EXPECT_EQ("c", remove_dots(".\\.\\c", true, path::Style::windows));
1201   EXPECT_EQ("..\\a\\c",
1202             remove_dots("..\\a\\b\\..\\c", true, path::Style::windows));
1203   EXPECT_EQ("..\\..\\a\\c",
1204             remove_dots("..\\..\\a\\b\\..\\c", true, path::Style::windows));
1205 
1206   SmallString<64> Path1(".\\.\\c");
1207   EXPECT_TRUE(path::remove_dots(Path1, true, path::Style::windows));
1208   EXPECT_EQ("c", Path1);
1209 
1210   EXPECT_EQ("foolz/wat",
1211             remove_dots("././/foolz/wat", false, path::Style::posix));
1212   EXPECT_EQ("", remove_dots("./////", false, path::Style::posix));
1213 
1214   EXPECT_EQ("a/../b/c", remove_dots("./a/../b/c", false, path::Style::posix));
1215   EXPECT_EQ("b/c", remove_dots("./a/../b/c", true, path::Style::posix));
1216   EXPECT_EQ("c", remove_dots("././c", true, path::Style::posix));
1217   EXPECT_EQ("../a/c", remove_dots("../a/b/../c", true, path::Style::posix));
1218   EXPECT_EQ("../../a/c",
1219             remove_dots("../../a/b/../c", true, path::Style::posix));
1220   EXPECT_EQ("/a/c", remove_dots("/../../a/c", true, path::Style::posix));
1221   EXPECT_EQ("/a/c",
1222             remove_dots("/../a/b//../././/c", true, path::Style::posix));
1223 
1224   SmallString<64> Path2("././c");
1225   EXPECT_TRUE(path::remove_dots(Path2, true, path::Style::posix));
1226   EXPECT_EQ("c", Path2);
1227 }
1228 
1229 TEST(Support, ReplacePathPrefix) {
1230   SmallString<64> Path1("/foo");
1231   SmallString<64> Path2("/old/foo");
1232   SmallString<64> OldPrefix("/old");
1233   SmallString<64> NewPrefix("/new");
1234   SmallString<64> NewPrefix2("/longernew");
1235   SmallString<64> EmptyPrefix("");
1236 
1237   SmallString<64> Path = Path1;
1238   path::replace_path_prefix(Path, OldPrefix, NewPrefix);
1239   EXPECT_EQ(Path, "/foo");
1240   Path = Path2;
1241   path::replace_path_prefix(Path, OldPrefix, NewPrefix);
1242   EXPECT_EQ(Path, "/new/foo");
1243   Path = Path2;
1244   path::replace_path_prefix(Path, OldPrefix, NewPrefix2);
1245   EXPECT_EQ(Path, "/longernew/foo");
1246   Path = Path1;
1247   path::replace_path_prefix(Path, EmptyPrefix, NewPrefix);
1248   EXPECT_EQ(Path, "/new/foo");
1249   Path = Path2;
1250   path::replace_path_prefix(Path, OldPrefix, EmptyPrefix);
1251   EXPECT_EQ(Path, "/foo");
1252 }
1253 
1254 TEST_F(FileSystemTest, OpenFileForRead) {
1255   // Create a temp file.
1256   int FileDescriptor;
1257   SmallString<64> TempPath;
1258   ASSERT_NO_ERROR(
1259       fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
1260   FileRemover Cleanup(TempPath);
1261 
1262   // Make sure it exists.
1263   ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
1264 
1265   // Open the file for read
1266   int FileDescriptor2;
1267   SmallString<64> ResultPath;
1268   ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath), FileDescriptor2,
1269                                       fs::OF_None, &ResultPath))
1270 
1271   // If we succeeded, check that the paths are the same (modulo case):
1272   if (!ResultPath.empty()) {
1273     // The paths returned by createTemporaryFile and getPathFromOpenFD
1274     // should reference the same file on disk.
1275     fs::UniqueID D1, D2;
1276     ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), D1));
1277     ASSERT_NO_ERROR(fs::getUniqueID(Twine(ResultPath), D2));
1278     ASSERT_EQ(D1, D2);
1279   }
1280   ::close(FileDescriptor);
1281   ::close(FileDescriptor2);
1282 
1283 #ifdef _WIN32
1284   // Since Windows Vista, file access time is not updated by default.
1285   // This is instead updated manually by openFileForRead.
1286   // https://blogs.technet.microsoft.com/filecab/2006/11/07/disabling-last-access-time-in-windows-vista-to-improve-ntfs-performance/
1287   // This part of the unit test is Windows specific as the updating of
1288   // access times can be disabled on Linux using /etc/fstab.
1289 
1290   // Set access time to UNIX epoch.
1291   ASSERT_NO_ERROR(sys::fs::openFileForWrite(Twine(TempPath), FileDescriptor,
1292                                             fs::CD_OpenExisting));
1293   TimePoint<> Epoch(std::chrono::milliseconds(0));
1294   ASSERT_NO_ERROR(fs::setLastAccessAndModificationTime(FileDescriptor, Epoch));
1295   ::close(FileDescriptor);
1296 
1297   // Open the file and ensure access time is updated, when forced.
1298   ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath), FileDescriptor,
1299                                       fs::OF_UpdateAtime, &ResultPath));
1300 
1301   sys::fs::file_status Status;
1302   ASSERT_NO_ERROR(sys::fs::status(FileDescriptor, Status));
1303   auto FileAccessTime = Status.getLastAccessedTime();
1304 
1305   ASSERT_NE(Epoch, FileAccessTime);
1306   ::close(FileDescriptor);
1307 
1308   // Ideally this test would include a case when ATime is not forced to update,
1309   // however the expected behaviour will differ depending on the configuration
1310   // of the Windows file system.
1311 #endif
1312 }
1313 
1314 static void createFileWithData(const Twine &Path, bool ShouldExistBefore,
1315                                fs::CreationDisposition Disp, StringRef Data) {
1316   int FD;
1317   ASSERT_EQ(ShouldExistBefore, fs::exists(Path));
1318   ASSERT_NO_ERROR(fs::openFileForWrite(Path, FD, Disp));
1319   FileDescriptorCloser Closer(FD);
1320   ASSERT_TRUE(fs::exists(Path));
1321 
1322   ASSERT_EQ(Data.size(), (size_t)write(FD, Data.data(), Data.size()));
1323 }
1324 
1325 static void verifyFileContents(const Twine &Path, StringRef Contents) {
1326   auto Buffer = MemoryBuffer::getFile(Path);
1327   ASSERT_TRUE((bool)Buffer);
1328   StringRef Data = Buffer.get()->getBuffer();
1329   ASSERT_EQ(Data, Contents);
1330 }
1331 
1332 TEST_F(FileSystemTest, CreateNew) {
1333   int FD;
1334   Optional<FileDescriptorCloser> Closer;
1335 
1336   // Succeeds if the file does not exist.
1337   ASSERT_FALSE(fs::exists(NonExistantFile));
1338   ASSERT_NO_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateNew));
1339   ASSERT_TRUE(fs::exists(NonExistantFile));
1340 
1341   FileRemover Cleanup(NonExistantFile);
1342   Closer.emplace(FD);
1343 
1344   // And creates a file of size 0.
1345   sys::fs::file_status Status;
1346   ASSERT_NO_ERROR(sys::fs::status(FD, Status));
1347   EXPECT_EQ(0ULL, Status.getSize());
1348 
1349   // Close this first, before trying to re-open the file.
1350   Closer.reset();
1351 
1352   // But fails if the file does exist.
1353   ASSERT_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateNew));
1354 }
1355 
1356 TEST_F(FileSystemTest, CreateAlways) {
1357   int FD;
1358   Optional<FileDescriptorCloser> Closer;
1359 
1360   // Succeeds if the file does not exist.
1361   ASSERT_FALSE(fs::exists(NonExistantFile));
1362   ASSERT_NO_ERROR(
1363       fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateAlways));
1364 
1365   Closer.emplace(FD);
1366 
1367   ASSERT_TRUE(fs::exists(NonExistantFile));
1368 
1369   FileRemover Cleanup(NonExistantFile);
1370 
1371   // And creates a file of size 0.
1372   uint64_t FileSize;
1373   ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1374   ASSERT_EQ(0ULL, FileSize);
1375 
1376   // If we write some data to it re-create it with CreateAlways, it succeeds and
1377   // truncates to 0 bytes.
1378   ASSERT_EQ(4, write(FD, "Test", 4));
1379 
1380   Closer.reset();
1381 
1382   ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1383   ASSERT_EQ(4ULL, FileSize);
1384 
1385   ASSERT_NO_ERROR(
1386       fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateAlways));
1387   Closer.emplace(FD);
1388   ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1389   ASSERT_EQ(0ULL, FileSize);
1390 }
1391 
1392 TEST_F(FileSystemTest, OpenExisting) {
1393   int FD;
1394 
1395   // Fails if the file does not exist.
1396   ASSERT_FALSE(fs::exists(NonExistantFile));
1397   ASSERT_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_OpenExisting));
1398   ASSERT_FALSE(fs::exists(NonExistantFile));
1399 
1400   // Make a dummy file now so that we can try again when the file does exist.
1401   createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1402   FileRemover Cleanup(NonExistantFile);
1403   uint64_t FileSize;
1404   ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1405   ASSERT_EQ(4ULL, FileSize);
1406 
1407   // If we re-create it with different data, it overwrites rather than
1408   // appending.
1409   createFileWithData(NonExistantFile, true, fs::CD_OpenExisting, "Buzz");
1410   verifyFileContents(NonExistantFile, "Buzz");
1411 }
1412 
1413 TEST_F(FileSystemTest, OpenAlways) {
1414   // Succeeds if the file does not exist.
1415   createFileWithData(NonExistantFile, false, fs::CD_OpenAlways, "Fizz");
1416   FileRemover Cleanup(NonExistantFile);
1417   uint64_t FileSize;
1418   ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1419   ASSERT_EQ(4ULL, FileSize);
1420 
1421   // Now re-open it and write again, verifying the contents get over-written.
1422   createFileWithData(NonExistantFile, true, fs::CD_OpenAlways, "Bu");
1423   verifyFileContents(NonExistantFile, "Buzz");
1424 }
1425 
1426 TEST_F(FileSystemTest, AppendSetsCorrectFileOffset) {
1427   fs::CreationDisposition Disps[] = {fs::CD_CreateAlways, fs::CD_OpenAlways,
1428                                      fs::CD_OpenExisting};
1429 
1430   // Write some data and re-open it with every possible disposition (this is a
1431   // hack that shouldn't work, but is left for compatibility.  OF_Append
1432   // overrides
1433   // the specified disposition.
1434   for (fs::CreationDisposition Disp : Disps) {
1435     int FD;
1436     Optional<FileDescriptorCloser> Closer;
1437 
1438     createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1439 
1440     FileRemover Cleanup(NonExistantFile);
1441 
1442     uint64_t FileSize;
1443     ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1444     ASSERT_EQ(4ULL, FileSize);
1445     ASSERT_NO_ERROR(
1446         fs::openFileForWrite(NonExistantFile, FD, Disp, fs::OF_Append));
1447     Closer.emplace(FD);
1448     ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1449     ASSERT_EQ(4ULL, FileSize);
1450 
1451     ASSERT_EQ(4, write(FD, "Buzz", 4));
1452     Closer.reset();
1453 
1454     verifyFileContents(NonExistantFile, "FizzBuzz");
1455   }
1456 }
1457 
1458 static void verifyRead(int FD, StringRef Data, bool ShouldSucceed) {
1459   std::vector<char> Buffer;
1460   Buffer.resize(Data.size());
1461   int Result = ::read(FD, Buffer.data(), Buffer.size());
1462   if (ShouldSucceed) {
1463     ASSERT_EQ((size_t)Result, Data.size());
1464     ASSERT_EQ(Data, StringRef(Buffer.data(), Buffer.size()));
1465   } else {
1466     ASSERT_EQ(-1, Result);
1467     ASSERT_EQ(EBADF, errno);
1468   }
1469 }
1470 
1471 static void verifyWrite(int FD, StringRef Data, bool ShouldSucceed) {
1472   int Result = ::write(FD, Data.data(), Data.size());
1473   if (ShouldSucceed)
1474     ASSERT_EQ((size_t)Result, Data.size());
1475   else {
1476     ASSERT_EQ(-1, Result);
1477     ASSERT_EQ(EBADF, errno);
1478   }
1479 }
1480 
1481 TEST_F(FileSystemTest, ReadOnlyFileCantWrite) {
1482   createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1483   FileRemover Cleanup(NonExistantFile);
1484 
1485   int FD;
1486   ASSERT_NO_ERROR(fs::openFileForRead(NonExistantFile, FD));
1487   FileDescriptorCloser Closer(FD);
1488 
1489   verifyWrite(FD, "Buzz", false);
1490   verifyRead(FD, "Fizz", true);
1491 }
1492 
1493 TEST_F(FileSystemTest, WriteOnlyFileCantRead) {
1494   createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1495   FileRemover Cleanup(NonExistantFile);
1496 
1497   int FD;
1498   ASSERT_NO_ERROR(
1499       fs::openFileForWrite(NonExistantFile, FD, fs::CD_OpenExisting));
1500   FileDescriptorCloser Closer(FD);
1501   verifyRead(FD, "Fizz", false);
1502   verifyWrite(FD, "Buzz", true);
1503 }
1504 
1505 TEST_F(FileSystemTest, ReadWriteFileCanReadOrWrite) {
1506   createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1507   FileRemover Cleanup(NonExistantFile);
1508 
1509   int FD;
1510   ASSERT_NO_ERROR(fs::openFileForReadWrite(NonExistantFile, FD,
1511                                            fs::CD_OpenExisting, fs::OF_None));
1512   FileDescriptorCloser Closer(FD);
1513   verifyRead(FD, "Fizz", true);
1514   verifyWrite(FD, "Buzz", true);
1515 }
1516 
1517 TEST_F(FileSystemTest, readNativeFileSlice) {
1518   char Data[10] = {'0', '1', '2', '3', '4', 0, 0, 0, 0, 0};
1519   createFileWithData(NonExistantFile, false, fs::CD_CreateNew,
1520                      StringRef(Data, 5));
1521   FileRemover Cleanup(NonExistantFile);
1522   Expected<fs::file_t> FD = fs::openNativeFileForRead(NonExistantFile);
1523   ASSERT_THAT_EXPECTED(FD, Succeeded());
1524   char Buf[10];
1525   const auto &Read = [&](size_t Offset,
1526                          size_t ToRead) -> Expected<ArrayRef<char>> {
1527     std::memset(Buf, 0x47, sizeof(Buf));
1528     if (std::error_code EC = fs::readNativeFileSlice(
1529             *FD, makeMutableArrayRef(Buf, ToRead), Offset))
1530       return errorCodeToError(EC);
1531     return makeArrayRef(Buf, ToRead);
1532   };
1533   EXPECT_THAT_EXPECTED(Read(0, 5), HasValue(makeArrayRef(Data + 0, 5)));
1534   EXPECT_THAT_EXPECTED(Read(0, 3), HasValue(makeArrayRef(Data + 0, 3)));
1535   EXPECT_THAT_EXPECTED(Read(2, 3), HasValue(makeArrayRef(Data + 2, 3)));
1536   EXPECT_THAT_EXPECTED(Read(0, 6), HasValue(makeArrayRef(Data + 0, 6)));
1537   EXPECT_THAT_EXPECTED(Read(2, 6), HasValue(makeArrayRef(Data + 2, 6)));
1538   EXPECT_THAT_EXPECTED(Read(5, 5), HasValue(makeArrayRef(Data + 5, 5)));
1539 }
1540 
1541 TEST_F(FileSystemTest, is_local) {
1542   bool TestDirectoryIsLocal;
1543   ASSERT_NO_ERROR(fs::is_local(TestDirectory, TestDirectoryIsLocal));
1544   EXPECT_EQ(TestDirectoryIsLocal, fs::is_local(TestDirectory));
1545 
1546   int FD;
1547   SmallString<128> TempPath;
1548   ASSERT_NO_ERROR(
1549       fs::createUniqueFile(Twine(TestDirectory) + "/temp", FD, TempPath));
1550   FileRemover Cleanup(TempPath);
1551 
1552   // Make sure it exists.
1553   ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
1554 
1555   bool TempFileIsLocal;
1556   ASSERT_NO_ERROR(fs::is_local(FD, TempFileIsLocal));
1557   EXPECT_EQ(TempFileIsLocal, fs::is_local(FD));
1558   ::close(FD);
1559 
1560   // Expect that the file and its parent directory are equally local or equally
1561   // remote.
1562   EXPECT_EQ(TestDirectoryIsLocal, TempFileIsLocal);
1563 }
1564 
1565 TEST_F(FileSystemTest, getUmask) {
1566 #ifdef _WIN32
1567   EXPECT_EQ(fs::getUmask(), 0U) << "Should always be 0 on Windows.";
1568 #else
1569   unsigned OldMask = ::umask(0022);
1570   unsigned CurrentMask = fs::getUmask();
1571   EXPECT_EQ(CurrentMask, 0022U)
1572       << "getUmask() didn't return previously set umask()";
1573   EXPECT_EQ(::umask(OldMask), 0022U) << "getUmask() may have changed umask()";
1574 #endif
1575 }
1576 
1577 TEST_F(FileSystemTest, RespectUmask) {
1578 #ifndef _WIN32
1579   unsigned OldMask = ::umask(0022);
1580 
1581   int FD;
1582   SmallString<128> TempPath;
1583   ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1584 
1585   fs::perms AllRWE = static_cast<fs::perms>(0777);
1586 
1587   ASSERT_NO_ERROR(fs::setPermissions(TempPath, AllRWE));
1588 
1589   ErrorOr<fs::perms> Perms = fs::getPermissions(TempPath);
1590   ASSERT_TRUE(!!Perms);
1591   EXPECT_EQ(Perms.get(), AllRWE) << "Should have ignored umask by default";
1592 
1593   ASSERT_NO_ERROR(fs::setPermissions(TempPath, AllRWE));
1594 
1595   Perms = fs::getPermissions(TempPath);
1596   ASSERT_TRUE(!!Perms);
1597   EXPECT_EQ(Perms.get(), AllRWE) << "Should have ignored umask";
1598 
1599   ASSERT_NO_ERROR(
1600       fs::setPermissions(FD, static_cast<fs::perms>(AllRWE & ~fs::getUmask())));
1601   Perms = fs::getPermissions(TempPath);
1602   ASSERT_TRUE(!!Perms);
1603   EXPECT_EQ(Perms.get(), static_cast<fs::perms>(0755))
1604       << "Did not respect umask";
1605 
1606   (void)::umask(0057);
1607 
1608   ASSERT_NO_ERROR(
1609       fs::setPermissions(FD, static_cast<fs::perms>(AllRWE & ~fs::getUmask())));
1610   Perms = fs::getPermissions(TempPath);
1611   ASSERT_TRUE(!!Perms);
1612   EXPECT_EQ(Perms.get(), static_cast<fs::perms>(0720))
1613       << "Did not respect umask";
1614 
1615   (void)::umask(OldMask);
1616   (void)::close(FD);
1617 #endif
1618 }
1619 
1620 TEST_F(FileSystemTest, set_current_path) {
1621   SmallString<128> path;
1622 
1623   ASSERT_NO_ERROR(fs::current_path(path));
1624   ASSERT_NE(TestDirectory, path);
1625 
1626   struct RestorePath {
1627     SmallString<128> path;
1628     RestorePath(const SmallString<128> &path) : path(path) {}
1629     ~RestorePath() { fs::set_current_path(path); }
1630   } restore_path(path);
1631 
1632   ASSERT_NO_ERROR(fs::set_current_path(TestDirectory));
1633 
1634   ASSERT_NO_ERROR(fs::current_path(path));
1635 
1636   fs::UniqueID D1, D2;
1637   ASSERT_NO_ERROR(fs::getUniqueID(TestDirectory, D1));
1638   ASSERT_NO_ERROR(fs::getUniqueID(path, D2));
1639   ASSERT_EQ(D1, D2) << "D1: " << TestDirectory << "\nD2: " << path;
1640 }
1641 
1642 TEST_F(FileSystemTest, permissions) {
1643   int FD;
1644   SmallString<64> TempPath;
1645   ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1646   FileRemover Cleanup(TempPath);
1647 
1648   // Make sure it exists.
1649   ASSERT_TRUE(fs::exists(Twine(TempPath)));
1650 
1651   auto CheckPermissions = [&](fs::perms Expected) {
1652     ErrorOr<fs::perms> Actual = fs::getPermissions(TempPath);
1653     return Actual && *Actual == Expected;
1654   };
1655 
1656   std::error_code NoError;
1657   EXPECT_EQ(fs::setPermissions(TempPath, fs::all_all), NoError);
1658   EXPECT_TRUE(CheckPermissions(fs::all_all));
1659 
1660   EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read | fs::all_exe), NoError);
1661   EXPECT_TRUE(CheckPermissions(fs::all_read | fs::all_exe));
1662 
1663 #if defined(_WIN32)
1664   fs::perms ReadOnly = fs::all_read | fs::all_exe;
1665   EXPECT_EQ(fs::setPermissions(TempPath, fs::no_perms), NoError);
1666   EXPECT_TRUE(CheckPermissions(ReadOnly));
1667 
1668   EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_read), NoError);
1669   EXPECT_TRUE(CheckPermissions(ReadOnly));
1670 
1671   EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_write), NoError);
1672   EXPECT_TRUE(CheckPermissions(fs::all_all));
1673 
1674   EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_exe), NoError);
1675   EXPECT_TRUE(CheckPermissions(ReadOnly));
1676 
1677   EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_all), NoError);
1678   EXPECT_TRUE(CheckPermissions(fs::all_all));
1679 
1680   EXPECT_EQ(fs::setPermissions(TempPath, fs::group_read), NoError);
1681   EXPECT_TRUE(CheckPermissions(ReadOnly));
1682 
1683   EXPECT_EQ(fs::setPermissions(TempPath, fs::group_write), NoError);
1684   EXPECT_TRUE(CheckPermissions(fs::all_all));
1685 
1686   EXPECT_EQ(fs::setPermissions(TempPath, fs::group_exe), NoError);
1687   EXPECT_TRUE(CheckPermissions(ReadOnly));
1688 
1689   EXPECT_EQ(fs::setPermissions(TempPath, fs::group_all), NoError);
1690   EXPECT_TRUE(CheckPermissions(fs::all_all));
1691 
1692   EXPECT_EQ(fs::setPermissions(TempPath, fs::others_read), NoError);
1693   EXPECT_TRUE(CheckPermissions(ReadOnly));
1694 
1695   EXPECT_EQ(fs::setPermissions(TempPath, fs::others_write), NoError);
1696   EXPECT_TRUE(CheckPermissions(fs::all_all));
1697 
1698   EXPECT_EQ(fs::setPermissions(TempPath, fs::others_exe), NoError);
1699   EXPECT_TRUE(CheckPermissions(ReadOnly));
1700 
1701   EXPECT_EQ(fs::setPermissions(TempPath, fs::others_all), NoError);
1702   EXPECT_TRUE(CheckPermissions(fs::all_all));
1703 
1704   EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read), NoError);
1705   EXPECT_TRUE(CheckPermissions(ReadOnly));
1706 
1707   EXPECT_EQ(fs::setPermissions(TempPath, fs::all_write), NoError);
1708   EXPECT_TRUE(CheckPermissions(fs::all_all));
1709 
1710   EXPECT_EQ(fs::setPermissions(TempPath, fs::all_exe), NoError);
1711   EXPECT_TRUE(CheckPermissions(ReadOnly));
1712 
1713   EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe), NoError);
1714   EXPECT_TRUE(CheckPermissions(ReadOnly));
1715 
1716   EXPECT_EQ(fs::setPermissions(TempPath, fs::set_gid_on_exe), NoError);
1717   EXPECT_TRUE(CheckPermissions(ReadOnly));
1718 
1719   EXPECT_EQ(fs::setPermissions(TempPath, fs::sticky_bit), NoError);
1720   EXPECT_TRUE(CheckPermissions(ReadOnly));
1721 
1722   EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe |
1723                                              fs::set_gid_on_exe |
1724                                              fs::sticky_bit),
1725             NoError);
1726   EXPECT_TRUE(CheckPermissions(ReadOnly));
1727 
1728   EXPECT_EQ(fs::setPermissions(TempPath, ReadOnly | fs::set_uid_on_exe |
1729                                              fs::set_gid_on_exe |
1730                                              fs::sticky_bit),
1731             NoError);
1732   EXPECT_TRUE(CheckPermissions(ReadOnly));
1733 
1734   EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms), NoError);
1735   EXPECT_TRUE(CheckPermissions(fs::all_all));
1736 #else
1737   EXPECT_EQ(fs::setPermissions(TempPath, fs::no_perms), NoError);
1738   EXPECT_TRUE(CheckPermissions(fs::no_perms));
1739 
1740   EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_read), NoError);
1741   EXPECT_TRUE(CheckPermissions(fs::owner_read));
1742 
1743   EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_write), NoError);
1744   EXPECT_TRUE(CheckPermissions(fs::owner_write));
1745 
1746   EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_exe), NoError);
1747   EXPECT_TRUE(CheckPermissions(fs::owner_exe));
1748 
1749   EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_all), NoError);
1750   EXPECT_TRUE(CheckPermissions(fs::owner_all));
1751 
1752   EXPECT_EQ(fs::setPermissions(TempPath, fs::group_read), NoError);
1753   EXPECT_TRUE(CheckPermissions(fs::group_read));
1754 
1755   EXPECT_EQ(fs::setPermissions(TempPath, fs::group_write), NoError);
1756   EXPECT_TRUE(CheckPermissions(fs::group_write));
1757 
1758   EXPECT_EQ(fs::setPermissions(TempPath, fs::group_exe), NoError);
1759   EXPECT_TRUE(CheckPermissions(fs::group_exe));
1760 
1761   EXPECT_EQ(fs::setPermissions(TempPath, fs::group_all), NoError);
1762   EXPECT_TRUE(CheckPermissions(fs::group_all));
1763 
1764   EXPECT_EQ(fs::setPermissions(TempPath, fs::others_read), NoError);
1765   EXPECT_TRUE(CheckPermissions(fs::others_read));
1766 
1767   EXPECT_EQ(fs::setPermissions(TempPath, fs::others_write), NoError);
1768   EXPECT_TRUE(CheckPermissions(fs::others_write));
1769 
1770   EXPECT_EQ(fs::setPermissions(TempPath, fs::others_exe), NoError);
1771   EXPECT_TRUE(CheckPermissions(fs::others_exe));
1772 
1773   EXPECT_EQ(fs::setPermissions(TempPath, fs::others_all), NoError);
1774   EXPECT_TRUE(CheckPermissions(fs::others_all));
1775 
1776   EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read), NoError);
1777   EXPECT_TRUE(CheckPermissions(fs::all_read));
1778 
1779   EXPECT_EQ(fs::setPermissions(TempPath, fs::all_write), NoError);
1780   EXPECT_TRUE(CheckPermissions(fs::all_write));
1781 
1782   EXPECT_EQ(fs::setPermissions(TempPath, fs::all_exe), NoError);
1783   EXPECT_TRUE(CheckPermissions(fs::all_exe));
1784 
1785   EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe), NoError);
1786   EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe));
1787 
1788   EXPECT_EQ(fs::setPermissions(TempPath, fs::set_gid_on_exe), NoError);
1789   EXPECT_TRUE(CheckPermissions(fs::set_gid_on_exe));
1790 
1791   // Modern BSDs require root to set the sticky bit on files.
1792   // AIX and Solaris without root will mask off (i.e., lose) the sticky bit
1793   // on files.
1794 #if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) &&  \
1795     !defined(_AIX) && !(defined(__sun__) && defined(__svr4__))
1796   EXPECT_EQ(fs::setPermissions(TempPath, fs::sticky_bit), NoError);
1797   EXPECT_TRUE(CheckPermissions(fs::sticky_bit));
1798 
1799   EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe |
1800                                              fs::set_gid_on_exe |
1801                                              fs::sticky_bit),
1802             NoError);
1803   EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe | fs::set_gid_on_exe |
1804                                fs::sticky_bit));
1805 
1806   EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read | fs::set_uid_on_exe |
1807                                              fs::set_gid_on_exe |
1808                                              fs::sticky_bit),
1809             NoError);
1810   EXPECT_TRUE(CheckPermissions(fs::all_read | fs::set_uid_on_exe |
1811                                fs::set_gid_on_exe | fs::sticky_bit));
1812 
1813   EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms), NoError);
1814   EXPECT_TRUE(CheckPermissions(fs::all_perms));
1815 #endif // !FreeBSD && !NetBSD && !OpenBSD && !AIX
1816 
1817   EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms & ~fs::sticky_bit),
1818                                NoError);
1819   EXPECT_TRUE(CheckPermissions(fs::all_perms & ~fs::sticky_bit));
1820 #endif
1821 }
1822 
1823 } // anonymous namespace
1824