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