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 "gtest/gtest.h"
24 #include "gmock/gmock.h"
25 
26 #ifdef _WIN32
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/Support/Chrono.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   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, TempDirectory) {
350   SmallString<32> TempDir;
351   path::system_temp_directory(false, TempDir);
352   EXPECT_TRUE(!TempDir.empty());
353   TempDir.clear();
354   path::system_temp_directory(true, TempDir);
355   EXPECT_TRUE(!TempDir.empty());
356 }
357 
358 #ifdef _WIN32
359 static std::string path2regex(std::string Path) {
360   size_t Pos = 0;
361   while ((Pos = Path.find('\\', Pos)) != std::string::npos) {
362     Path.replace(Pos, 1, "\\\\");
363     Pos += 2;
364   }
365   return Path;
366 }
367 
368 /// Helper for running temp dir test in separated process. See below.
369 #define EXPECT_TEMP_DIR(prepare, expected)                                     \
370   EXPECT_EXIT(                                                                 \
371       {                                                                        \
372         prepare;                                                               \
373         SmallString<300> TempDir;                                              \
374         path::system_temp_directory(true, TempDir);                            \
375         raw_os_ostream(std::cerr) << TempDir;                                  \
376         std::exit(0);                                                          \
377       },                                                                       \
378       ::testing::ExitedWithCode(0), path2regex(expected))
379 
380 TEST(SupportDeathTest, TempDirectoryOnWindows) {
381   // In this test we want to check how system_temp_directory responds to
382   // different values of specific env vars. To prevent corrupting env vars of
383   // the current process all checks are done in separated processes.
384   EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"C:\\OtherFolder"), "C:\\OtherFolder");
385   EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"C:/Unix/Path/Seperators"),
386                   "C:\\Unix\\Path\\Seperators");
387   EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"Local Path"), ".+\\Local Path$");
388   EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"F:\\TrailingSep\\"), "F:\\TrailingSep");
389   EXPECT_TEMP_DIR(
390       _wputenv_s(L"TMP", L"C:\\2\x03C0r-\x00B5\x00B3\\\x2135\x2080"),
391       "C:\\2\xCF\x80r-\xC2\xB5\xC2\xB3\\\xE2\x84\xB5\xE2\x82\x80");
392 
393   // Test $TMP empty, $TEMP set.
394   EXPECT_TEMP_DIR(
395       {
396         _wputenv_s(L"TMP", L"");
397         _wputenv_s(L"TEMP", L"C:\\Valid\\Path");
398       },
399       "C:\\Valid\\Path");
400 
401   // All related env vars empty
402   EXPECT_TEMP_DIR(
403   {
404     _wputenv_s(L"TMP", L"");
405     _wputenv_s(L"TEMP", L"");
406     _wputenv_s(L"USERPROFILE", L"");
407   },
408     "C:\\Temp");
409 
410   // Test evn var / path with 260 chars.
411   SmallString<270> Expected{"C:\\Temp\\AB\\123456789"};
412   while (Expected.size() < 260)
413     Expected.append("\\DirNameWith19Charss");
414   ASSERT_EQ(260U, Expected.size());
415   EXPECT_TEMP_DIR(_putenv_s("TMP", Expected.c_str()), Expected.c_str());
416 }
417 #endif
418 
419 class FileSystemTest : public testing::Test {
420 protected:
421   /// Unique temporary directory in which all created filesystem entities must
422   /// be placed. It is removed at the end of each test (must be empty).
423   SmallString<128> TestDirectory;
424   SmallString<128> NonExistantFile;
425 
426   void SetUp() override {
427     ASSERT_NO_ERROR(
428         fs::createUniqueDirectory("file-system-test", TestDirectory));
429     // We don't care about this specific file.
430     errs() << "Test Directory: " << TestDirectory << '\n';
431     errs().flush();
432     NonExistantFile = TestDirectory;
433 
434     // Even though this value is hardcoded, is a 128-bit GUID, so we should be
435     // guaranteed that this file will never exist.
436     sys::path::append(NonExistantFile, "1B28B495C16344CB9822E588CD4C3EF0");
437   }
438 
439   void TearDown() override { ASSERT_NO_ERROR(fs::remove(TestDirectory.str())); }
440 };
441 
442 TEST_F(FileSystemTest, Unique) {
443   // Create a temp file.
444   int FileDescriptor;
445   SmallString<64> TempPath;
446   ASSERT_NO_ERROR(
447       fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
448 
449   // The same file should return an identical unique id.
450   fs::UniqueID F1, F2;
451   ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F1));
452   ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F2));
453   ASSERT_EQ(F1, F2);
454 
455   // Different files should return different unique ids.
456   int FileDescriptor2;
457   SmallString<64> TempPath2;
458   ASSERT_NO_ERROR(
459       fs::createTemporaryFile("prefix", "temp", FileDescriptor2, TempPath2));
460 
461   fs::UniqueID D;
462   ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D));
463   ASSERT_NE(D, F1);
464   ::close(FileDescriptor2);
465 
466   ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
467 
468   // Two paths representing the same file on disk should still provide the
469   // same unique id.  We can test this by making a hard link.
470   ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2)));
471   fs::UniqueID D2;
472   ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D2));
473   ASSERT_EQ(D2, F1);
474 
475   ::close(FileDescriptor);
476 
477   SmallString<128> Dir1;
478   ASSERT_NO_ERROR(
479      fs::createUniqueDirectory("dir1", Dir1));
480   ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F1));
481   ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F2));
482   ASSERT_EQ(F1, F2);
483 
484   SmallString<128> Dir2;
485   ASSERT_NO_ERROR(
486      fs::createUniqueDirectory("dir2", Dir2));
487   ASSERT_NO_ERROR(fs::getUniqueID(Dir2.c_str(), F2));
488   ASSERT_NE(F1, F2);
489   ASSERT_NO_ERROR(fs::remove(Dir1));
490   ASSERT_NO_ERROR(fs::remove(Dir2));
491   ASSERT_NO_ERROR(fs::remove(TempPath2));
492   ASSERT_NO_ERROR(fs::remove(TempPath));
493 }
494 
495 TEST_F(FileSystemTest, RealPath) {
496   ASSERT_NO_ERROR(
497       fs::create_directories(Twine(TestDirectory) + "/test1/test2/test3"));
498   ASSERT_TRUE(fs::exists(Twine(TestDirectory) + "/test1/test2/test3"));
499 
500   SmallString<64> RealBase;
501   SmallString<64> Expected;
502   SmallString<64> Actual;
503 
504   // TestDirectory itself might be under a symlink or have been specified with
505   // a different case than the existing temp directory.  In such cases real_path
506   // on the concatenated path will differ in the TestDirectory portion from
507   // how we specified it.  Make sure to compare against the real_path of the
508   // TestDirectory, and not just the value of TestDirectory.
509   ASSERT_NO_ERROR(fs::real_path(TestDirectory, RealBase));
510   path::native(Twine(RealBase) + "/test1/test2", Expected);
511 
512   ASSERT_NO_ERROR(fs::real_path(
513       Twine(TestDirectory) + "/././test1/../test1/test2/./test3/..", Actual));
514 
515   EXPECT_EQ(Expected, Actual);
516 
517   SmallString<64> HomeDir;
518 
519   // This can fail if $HOME is not set and getpwuid fails.
520   bool Result = llvm::sys::path::home_directory(HomeDir);
521   if (Result) {
522     ASSERT_NO_ERROR(fs::real_path(HomeDir, Expected));
523     ASSERT_NO_ERROR(fs::real_path("~", Actual, true));
524     EXPECT_EQ(Expected, Actual);
525     ASSERT_NO_ERROR(fs::real_path("~/", Actual, true));
526     EXPECT_EQ(Expected, Actual);
527   }
528 
529   ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/test1"));
530 }
531 
532 TEST_F(FileSystemTest, ExpandTilde) {
533   SmallString<64> Expected;
534   SmallString<64> Actual;
535   SmallString<64> HomeDir;
536 
537   // This can fail if $HOME is not set and getpwuid fails.
538   bool Result = llvm::sys::path::home_directory(HomeDir);
539   if (Result) {
540     fs::expand_tilde(HomeDir, Expected);
541 
542     fs::expand_tilde("~", Actual);
543     EXPECT_EQ(Expected, Actual);
544 
545 #ifdef _WIN32
546     Expected += "\\foo";
547     fs::expand_tilde("~\\foo", Actual);
548 #else
549     Expected += "/foo";
550     fs::expand_tilde("~/foo", Actual);
551 #endif
552 
553     EXPECT_EQ(Expected, Actual);
554   }
555 }
556 
557 #ifdef LLVM_ON_UNIX
558 TEST_F(FileSystemTest, RealPathNoReadPerm) {
559   SmallString<64> Expanded;
560 
561   ASSERT_NO_ERROR(
562     fs::create_directories(Twine(TestDirectory) + "/noreadperm"));
563   ASSERT_TRUE(fs::exists(Twine(TestDirectory) + "/noreadperm"));
564 
565   fs::setPermissions(Twine(TestDirectory) + "/noreadperm", fs::no_perms);
566   fs::setPermissions(Twine(TestDirectory) + "/noreadperm", fs::all_exe);
567 
568   ASSERT_NO_ERROR(fs::real_path(Twine(TestDirectory) + "/noreadperm", Expanded,
569                                 false));
570 
571   ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/noreadperm"));
572 }
573 #endif
574 
575 
576 TEST_F(FileSystemTest, TempFileKeepDiscard) {
577   // We can keep then discard.
578   auto TempFileOrError = fs::TempFile::create(TestDirectory + "/test-%%%%");
579   ASSERT_TRUE((bool)TempFileOrError);
580   fs::TempFile File = std::move(*TempFileOrError);
581   ASSERT_EQ(-1, TempFileOrError->FD);
582   ASSERT_FALSE((bool)File.keep(TestDirectory + "/keep"));
583   ASSERT_FALSE((bool)File.discard());
584   ASSERT_TRUE(fs::exists(TestDirectory + "/keep"));
585   ASSERT_NO_ERROR(fs::remove(TestDirectory + "/keep"));
586 }
587 
588 TEST_F(FileSystemTest, TempFileDiscardDiscard) {
589   // We can discard twice.
590   auto TempFileOrError = fs::TempFile::create(TestDirectory + "/test-%%%%");
591   ASSERT_TRUE((bool)TempFileOrError);
592   fs::TempFile File = std::move(*TempFileOrError);
593   ASSERT_EQ(-1, TempFileOrError->FD);
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, TempFileCollisions) {
684   SmallString<128> TestDirectory;
685   ASSERT_NO_ERROR(
686       fs::createUniqueDirectory("CreateUniqueFileTest", TestDirectory));
687   FileRemover Cleanup(TestDirectory);
688   SmallString<128> Model = TestDirectory;
689   path::append(Model, "%.tmp");
690   SmallString<128> Path;
691   std::vector<fs::TempFile> TempFiles;
692 
693   auto TryCreateTempFile = [&]() {
694     Expected<fs::TempFile> T = fs::TempFile::create(Model);
695     if (T) {
696       TempFiles.push_back(std::move(*T));
697       return true;
698     } else {
699       logAllUnhandledErrors(T.takeError(), errs(),
700                             "Failed to create temporary file: ");
701       return false;
702     }
703   };
704 
705   // Our single-character template allows for 16 unique names. Check that
706   // calling TryCreateTempFile repeatedly results in 16 successes.
707   // Because the test depends on random numbers, it could theoretically fail.
708   // However, the probability of this happening is tiny: with 32 calls, each
709   // of which will retry up to 128 times, to not get a given digit we would
710   // have to fail at least 15 + 17 * 128 = 2191 attempts. The probability of
711   // 2191 attempts not producing a given hexadecimal digit is
712   // (1 - 1/16) ** 2191 or 3.88e-62.
713   int Successes = 0;
714   for (int i = 0; i < 32; ++i)
715     if (TryCreateTempFile()) ++Successes;
716   EXPECT_EQ(Successes, 16);
717 
718   for (fs::TempFile &T : TempFiles)
719     cantFail(T.discard());
720 }
721 
722 TEST_F(FileSystemTest, CreateDir) {
723   ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
724   ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
725   ASSERT_EQ(fs::create_directory(Twine(TestDirectory) + "foo", false),
726             errc::file_exists);
727   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "foo"));
728 
729 #ifdef LLVM_ON_UNIX
730   // Set a 0000 umask so that we can test our directory permissions.
731   mode_t OldUmask = ::umask(0000);
732 
733   fs::file_status Status;
734   ASSERT_NO_ERROR(
735       fs::create_directory(Twine(TestDirectory) + "baz500", false,
736                            fs::perms::owner_read | fs::perms::owner_exe));
737   ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz500", Status));
738   ASSERT_EQ(Status.permissions() & fs::perms::all_all,
739             fs::perms::owner_read | fs::perms::owner_exe);
740   ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "baz777", false,
741                                        fs::perms::all_all));
742   ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz777", Status));
743   ASSERT_EQ(Status.permissions() & fs::perms::all_all, fs::perms::all_all);
744 
745   // Restore umask to be safe.
746   ::umask(OldUmask);
747 #endif
748 
749 #ifdef _WIN32
750   // Prove that create_directories() can handle a pathname > 248 characters,
751   // which is the documented limit for CreateDirectory().
752   // (248 is MAX_PATH subtracting room for an 8.3 filename.)
753   // Generate a directory path guaranteed to fall into that range.
754   size_t TmpLen = TestDirectory.size();
755   const char *OneDir = "\\123456789";
756   size_t OneDirLen = strlen(OneDir);
757   ASSERT_LT(OneDirLen, 12U);
758   size_t NLevels = ((248 - TmpLen) / OneDirLen) + 1;
759   SmallString<260> LongDir(TestDirectory);
760   for (size_t I = 0; I < NLevels; ++I)
761     LongDir.append(OneDir);
762   ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir)));
763   ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir)));
764   ASSERT_EQ(fs::create_directories(Twine(LongDir), false),
765             errc::file_exists);
766   // Tidy up, "recursively" removing the directories.
767   StringRef ThisDir(LongDir);
768   for (size_t J = 0; J < NLevels; ++J) {
769     ASSERT_NO_ERROR(fs::remove(ThisDir));
770     ThisDir = path::parent_path(ThisDir);
771   }
772 
773   // Also verify that paths with Unix separators are handled correctly.
774   std::string LongPathWithUnixSeparators(TestDirectory.str());
775   // Add at least one subdirectory to TestDirectory, and replace slashes with
776   // backslashes
777   do {
778     LongPathWithUnixSeparators.append("/DirNameWith19Charss");
779   } while (LongPathWithUnixSeparators.size() < 260);
780   std::replace(LongPathWithUnixSeparators.begin(),
781                LongPathWithUnixSeparators.end(),
782                '\\', '/');
783   ASSERT_NO_ERROR(fs::create_directories(Twine(LongPathWithUnixSeparators)));
784   // cleanup
785   ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) +
786                                          "/DirNameWith19Charss"));
787 
788   // Similarly for a relative pathname.  Need to set the current directory to
789   // TestDirectory so that the one we create ends up in the right place.
790   char PreviousDir[260];
791   size_t PreviousDirLen = ::GetCurrentDirectoryA(260, PreviousDir);
792   ASSERT_GT(PreviousDirLen, 0U);
793   ASSERT_LT(PreviousDirLen, 260U);
794   ASSERT_NE(::SetCurrentDirectoryA(TestDirectory.c_str()), 0);
795   LongDir.clear();
796   // Generate a relative directory name with absolute length > 248.
797   size_t LongDirLen = 249 - TestDirectory.size();
798   LongDir.assign(LongDirLen, 'a');
799   ASSERT_NO_ERROR(fs::create_directory(Twine(LongDir)));
800   // While we're here, prove that .. and . handling works in these long paths.
801   const char *DotDotDirs = "\\..\\.\\b";
802   LongDir.append(DotDotDirs);
803   ASSERT_NO_ERROR(fs::create_directory("b"));
804   ASSERT_EQ(fs::create_directory(Twine(LongDir), false), errc::file_exists);
805   // And clean up.
806   ASSERT_NO_ERROR(fs::remove("b"));
807   ASSERT_NO_ERROR(fs::remove(
808     Twine(LongDir.substr(0, LongDir.size() - strlen(DotDotDirs)))));
809   ASSERT_NE(::SetCurrentDirectoryA(PreviousDir), 0);
810 #endif
811 }
812 
813 TEST_F(FileSystemTest, DirectoryIteration) {
814   std::error_code ec;
815   for (fs::directory_iterator i(".", ec), e; i != e; i.increment(ec))
816     ASSERT_NO_ERROR(ec);
817 
818   // Create a known hierarchy to recurse over.
819   ASSERT_NO_ERROR(
820       fs::create_directories(Twine(TestDirectory) + "/recursive/a0/aa1"));
821   ASSERT_NO_ERROR(
822       fs::create_directories(Twine(TestDirectory) + "/recursive/a0/ab1"));
823   ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) +
824                                          "/recursive/dontlookhere/da1"));
825   ASSERT_NO_ERROR(
826       fs::create_directories(Twine(TestDirectory) + "/recursive/z0/za1"));
827   ASSERT_NO_ERROR(
828       fs::create_directories(Twine(TestDirectory) + "/recursive/pop/p1"));
829   typedef std::vector<std::string> v_t;
830   v_t visited;
831   for (fs::recursive_directory_iterator i(Twine(TestDirectory)
832          + "/recursive", ec), e; i != e; i.increment(ec)){
833     ASSERT_NO_ERROR(ec);
834     if (path::filename(i->path()) == "p1") {
835       i.pop();
836       // FIXME: recursive_directory_iterator should be more robust.
837       if (i == e) break;
838     }
839     if (path::filename(i->path()) == "dontlookhere")
840       i.no_push();
841     visited.push_back(path::filename(i->path()));
842   }
843   v_t::const_iterator a0 = find(visited, "a0");
844   v_t::const_iterator aa1 = find(visited, "aa1");
845   v_t::const_iterator ab1 = find(visited, "ab1");
846   v_t::const_iterator dontlookhere = find(visited, "dontlookhere");
847   v_t::const_iterator da1 = find(visited, "da1");
848   v_t::const_iterator z0 = find(visited, "z0");
849   v_t::const_iterator za1 = find(visited, "za1");
850   v_t::const_iterator pop = find(visited, "pop");
851   v_t::const_iterator p1 = find(visited, "p1");
852 
853   // Make sure that each path was visited correctly.
854   ASSERT_NE(a0, visited.end());
855   ASSERT_NE(aa1, visited.end());
856   ASSERT_NE(ab1, visited.end());
857   ASSERT_NE(dontlookhere, visited.end());
858   ASSERT_EQ(da1, visited.end()); // Not visited.
859   ASSERT_NE(z0, visited.end());
860   ASSERT_NE(za1, visited.end());
861   ASSERT_NE(pop, visited.end());
862   ASSERT_EQ(p1, visited.end()); // Not visited.
863 
864   // Make sure that parents were visited before children. No other ordering
865   // guarantees can be made across siblings.
866   ASSERT_LT(a0, aa1);
867   ASSERT_LT(a0, ab1);
868   ASSERT_LT(z0, za1);
869 
870   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/aa1"));
871   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/ab1"));
872   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0"));
873   ASSERT_NO_ERROR(
874       fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere/da1"));
875   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere"));
876   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop/p1"));
877   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop"));
878   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0/za1"));
879   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0"));
880   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive"));
881 
882   // Test recursive_directory_iterator level()
883   ASSERT_NO_ERROR(
884       fs::create_directories(Twine(TestDirectory) + "/reclevel/a/b/c"));
885   fs::recursive_directory_iterator I(Twine(TestDirectory) + "/reclevel", ec), E;
886   for (int l = 0; I != E; I.increment(ec), ++l) {
887     ASSERT_NO_ERROR(ec);
888     EXPECT_EQ(I.level(), l);
889   }
890   EXPECT_EQ(I, E);
891   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a/b/c"));
892   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a/b"));
893   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a"));
894   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel"));
895 }
896 
897 #ifdef LLVM_ON_UNIX
898 TEST_F(FileSystemTest, BrokenSymlinkDirectoryIteration) {
899   // Create a known hierarchy to recurse over.
900   ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) + "/symlink"));
901   ASSERT_NO_ERROR(
902       fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/a"));
903   ASSERT_NO_ERROR(
904       fs::create_directories(Twine(TestDirectory) + "/symlink/b/bb"));
905   ASSERT_NO_ERROR(
906       fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/b/ba"));
907   ASSERT_NO_ERROR(
908       fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/b/bc"));
909   ASSERT_NO_ERROR(
910       fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/c"));
911   ASSERT_NO_ERROR(
912       fs::create_directories(Twine(TestDirectory) + "/symlink/d/dd/ddd"));
913   ASSERT_NO_ERROR(fs::create_link(Twine(TestDirectory) + "/symlink/d/dd",
914                                   Twine(TestDirectory) + "/symlink/d/da"));
915   ASSERT_NO_ERROR(
916       fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/e"));
917 
918   typedef std::vector<std::string> v_t;
919   v_t VisitedNonBrokenSymlinks;
920   v_t VisitedBrokenSymlinks;
921   std::error_code ec;
922   using testing::UnorderedElementsAre;
923   using testing::UnorderedElementsAreArray;
924 
925   // Broken symbol links are expected to throw an error.
926   for (fs::directory_iterator i(Twine(TestDirectory) + "/symlink", ec), e;
927        i != e; i.increment(ec)) {
928     ASSERT_NO_ERROR(ec);
929     if (i->status().getError() ==
930         std::make_error_code(std::errc::no_such_file_or_directory)) {
931       VisitedBrokenSymlinks.push_back(path::filename(i->path()));
932       continue;
933     }
934     VisitedNonBrokenSymlinks.push_back(path::filename(i->path()));
935   }
936   EXPECT_THAT(VisitedNonBrokenSymlinks, UnorderedElementsAre("b", "d"));
937   VisitedNonBrokenSymlinks.clear();
938 
939   EXPECT_THAT(VisitedBrokenSymlinks, UnorderedElementsAre("a", "c", "e"));
940   VisitedBrokenSymlinks.clear();
941 
942   // Broken symbol links are expected to throw an error.
943   for (fs::recursive_directory_iterator i(
944       Twine(TestDirectory) + "/symlink", ec), e; i != e; i.increment(ec)) {
945     ASSERT_NO_ERROR(ec);
946     if (i->status().getError() ==
947         std::make_error_code(std::errc::no_such_file_or_directory)) {
948       VisitedBrokenSymlinks.push_back(path::filename(i->path()));
949       continue;
950     }
951     VisitedNonBrokenSymlinks.push_back(path::filename(i->path()));
952   }
953   EXPECT_THAT(VisitedNonBrokenSymlinks,
954               UnorderedElementsAre("b", "bb", "d", "da", "dd", "ddd", "ddd"));
955   VisitedNonBrokenSymlinks.clear();
956 
957   EXPECT_THAT(VisitedBrokenSymlinks,
958               UnorderedElementsAre("a", "ba", "bc", "c", "e"));
959   VisitedBrokenSymlinks.clear();
960 
961   for (fs::recursive_directory_iterator i(
962       Twine(TestDirectory) + "/symlink", ec, /*follow_symlinks=*/false), e;
963        i != e; i.increment(ec)) {
964     ASSERT_NO_ERROR(ec);
965     if (i->status().getError() ==
966         std::make_error_code(std::errc::no_such_file_or_directory)) {
967       VisitedBrokenSymlinks.push_back(path::filename(i->path()));
968       continue;
969     }
970     VisitedNonBrokenSymlinks.push_back(path::filename(i->path()));
971   }
972   EXPECT_THAT(VisitedNonBrokenSymlinks,
973               UnorderedElementsAreArray({"a", "b", "ba", "bb", "bc", "c", "d",
974                                          "da", "dd", "ddd", "e"}));
975   VisitedNonBrokenSymlinks.clear();
976 
977   EXPECT_THAT(VisitedBrokenSymlinks, UnorderedElementsAre());
978   VisitedBrokenSymlinks.clear();
979 
980   ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/symlink"));
981 }
982 #endif
983 
984 TEST_F(FileSystemTest, Remove) {
985   SmallString<64> BaseDir;
986   SmallString<64> Paths[4];
987   int fds[4];
988   ASSERT_NO_ERROR(fs::createUniqueDirectory("fs_remove", BaseDir));
989 
990   ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir) + "/foo/bar/baz"));
991   ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir) + "/foo/bar/buzz"));
992   ASSERT_NO_ERROR(fs::createUniqueFile(
993       Twine(BaseDir) + "/foo/bar/baz/%%%%%%.tmp", fds[0], Paths[0]));
994   ASSERT_NO_ERROR(fs::createUniqueFile(
995       Twine(BaseDir) + "/foo/bar/baz/%%%%%%.tmp", fds[1], Paths[1]));
996   ASSERT_NO_ERROR(fs::createUniqueFile(
997       Twine(BaseDir) + "/foo/bar/buzz/%%%%%%.tmp", fds[2], Paths[2]));
998   ASSERT_NO_ERROR(fs::createUniqueFile(
999       Twine(BaseDir) + "/foo/bar/buzz/%%%%%%.tmp", fds[3], Paths[3]));
1000 
1001   for (int fd : fds)
1002     ::close(fd);
1003 
1004   EXPECT_TRUE(fs::exists(Twine(BaseDir) + "/foo/bar/baz"));
1005   EXPECT_TRUE(fs::exists(Twine(BaseDir) + "/foo/bar/buzz"));
1006   EXPECT_TRUE(fs::exists(Paths[0]));
1007   EXPECT_TRUE(fs::exists(Paths[1]));
1008   EXPECT_TRUE(fs::exists(Paths[2]));
1009   EXPECT_TRUE(fs::exists(Paths[3]));
1010 
1011   ASSERT_NO_ERROR(fs::remove_directories("D:/footest"));
1012 
1013   ASSERT_NO_ERROR(fs::remove_directories(BaseDir));
1014   ASSERT_FALSE(fs::exists(BaseDir));
1015 }
1016 
1017 #ifdef _WIN32
1018 TEST_F(FileSystemTest, CarriageReturn) {
1019   SmallString<128> FilePathname(TestDirectory);
1020   std::error_code EC;
1021   path::append(FilePathname, "test");
1022 
1023   {
1024     raw_fd_ostream File(FilePathname, EC, sys::fs::F_Text);
1025     ASSERT_NO_ERROR(EC);
1026     File << '\n';
1027   }
1028   {
1029     auto Buf = MemoryBuffer::getFile(FilePathname.str());
1030     EXPECT_TRUE((bool)Buf);
1031     EXPECT_EQ(Buf.get()->getBuffer(), "\r\n");
1032   }
1033 
1034   {
1035     raw_fd_ostream File(FilePathname, EC, sys::fs::F_None);
1036     ASSERT_NO_ERROR(EC);
1037     File << '\n';
1038   }
1039   {
1040     auto Buf = MemoryBuffer::getFile(FilePathname.str());
1041     EXPECT_TRUE((bool)Buf);
1042     EXPECT_EQ(Buf.get()->getBuffer(), "\n");
1043   }
1044   ASSERT_NO_ERROR(fs::remove(Twine(FilePathname)));
1045 }
1046 #endif
1047 
1048 TEST_F(FileSystemTest, Resize) {
1049   int FD;
1050   SmallString<64> TempPath;
1051   ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1052   ASSERT_NO_ERROR(fs::resize_file(FD, 123));
1053   fs::file_status Status;
1054   ASSERT_NO_ERROR(fs::status(FD, Status));
1055   ASSERT_EQ(Status.getSize(), 123U);
1056   ::close(FD);
1057   ASSERT_NO_ERROR(fs::remove(TempPath));
1058 }
1059 
1060 TEST_F(FileSystemTest, MD5) {
1061   int FD;
1062   SmallString<64> TempPath;
1063   ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1064   StringRef Data("abcdefghijklmnopqrstuvwxyz");
1065   ASSERT_EQ(write(FD, Data.data(), Data.size()), static_cast<ssize_t>(Data.size()));
1066   lseek(FD, 0, SEEK_SET);
1067   auto Hash = fs::md5_contents(FD);
1068   ::close(FD);
1069   ASSERT_NO_ERROR(Hash.getError());
1070 
1071   EXPECT_STREQ("c3fcd3d76192e4007dfb496cca67e13b", Hash->digest().c_str());
1072 }
1073 
1074 TEST_F(FileSystemTest, FileMapping) {
1075   // Create a temp file.
1076   int FileDescriptor;
1077   SmallString<64> TempPath;
1078   ASSERT_NO_ERROR(
1079       fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
1080   unsigned Size = 4096;
1081   ASSERT_NO_ERROR(fs::resize_file(FileDescriptor, Size));
1082 
1083   // Map in temp file and add some content
1084   std::error_code EC;
1085   StringRef Val("hello there");
1086   {
1087     fs::mapped_file_region mfr(FileDescriptor,
1088                                fs::mapped_file_region::readwrite, Size, 0, EC);
1089     ASSERT_NO_ERROR(EC);
1090     std::copy(Val.begin(), Val.end(), mfr.data());
1091     // Explicitly add a 0.
1092     mfr.data()[Val.size()] = 0;
1093     // Unmap temp file
1094   }
1095   ASSERT_EQ(close(FileDescriptor), 0);
1096 
1097   // Map it back in read-only
1098   {
1099     int FD;
1100     EC = fs::openFileForRead(Twine(TempPath), FD);
1101     ASSERT_NO_ERROR(EC);
1102     fs::mapped_file_region mfr(FD, fs::mapped_file_region::readonly, Size, 0, EC);
1103     ASSERT_NO_ERROR(EC);
1104 
1105     // Verify content
1106     EXPECT_EQ(StringRef(mfr.const_data()), Val);
1107 
1108     // Unmap temp file
1109     fs::mapped_file_region m(FD, fs::mapped_file_region::readonly, Size, 0, EC);
1110     ASSERT_NO_ERROR(EC);
1111     ASSERT_EQ(close(FD), 0);
1112   }
1113   ASSERT_NO_ERROR(fs::remove(TempPath));
1114 }
1115 
1116 TEST(Support, NormalizePath) {
1117   using TestTuple = std::tuple<const char *, const char *, const char *>;
1118   std::vector<TestTuple> Tests;
1119   Tests.emplace_back("a", "a", "a");
1120   Tests.emplace_back("a/b", "a\\b", "a/b");
1121   Tests.emplace_back("a\\b", "a\\b", "a/b");
1122   Tests.emplace_back("a\\\\b", "a\\\\b", "a\\\\b");
1123   Tests.emplace_back("\\a", "\\a", "/a");
1124   Tests.emplace_back("a\\", "a\\", "a/");
1125 
1126   for (auto &T : Tests) {
1127     SmallString<64> Win(std::get<0>(T));
1128     SmallString<64> Posix(Win);
1129     path::native(Win, path::Style::windows);
1130     path::native(Posix, path::Style::posix);
1131     EXPECT_EQ(std::get<1>(T), Win);
1132     EXPECT_EQ(std::get<2>(T), Posix);
1133   }
1134 
1135 #if defined(_WIN32)
1136   SmallString<64> PathHome;
1137   path::home_directory(PathHome);
1138 
1139   const char *Path7a = "~/aaa";
1140   SmallString<64> Path7(Path7a);
1141   path::native(Path7);
1142   EXPECT_TRUE(Path7.endswith("\\aaa"));
1143   EXPECT_TRUE(Path7.startswith(PathHome));
1144   EXPECT_EQ(Path7.size(), PathHome.size() + strlen(Path7a + 1));
1145 
1146   const char *Path8a = "~";
1147   SmallString<64> Path8(Path8a);
1148   path::native(Path8);
1149   EXPECT_EQ(Path8, PathHome);
1150 
1151   const char *Path9a = "~aaa";
1152   SmallString<64> Path9(Path9a);
1153   path::native(Path9);
1154   EXPECT_EQ(Path9, "~aaa");
1155 
1156   const char *Path10a = "aaa/~/b";
1157   SmallString<64> Path10(Path10a);
1158   path::native(Path10);
1159   EXPECT_EQ(Path10, "aaa\\~\\b");
1160 #endif
1161 }
1162 
1163 TEST(Support, RemoveLeadingDotSlash) {
1164   StringRef Path1("././/foolz/wat");
1165   StringRef Path2("./////");
1166 
1167   Path1 = path::remove_leading_dotslash(Path1);
1168   EXPECT_EQ(Path1, "foolz/wat");
1169   Path2 = path::remove_leading_dotslash(Path2);
1170   EXPECT_EQ(Path2, "");
1171 }
1172 
1173 static std::string remove_dots(StringRef path, bool remove_dot_dot,
1174                                path::Style style) {
1175   SmallString<256> buffer(path);
1176   path::remove_dots(buffer, remove_dot_dot, style);
1177   return buffer.str();
1178 }
1179 
1180 TEST(Support, RemoveDots) {
1181   EXPECT_EQ("foolz\\wat",
1182             remove_dots(".\\.\\\\foolz\\wat", false, path::Style::windows));
1183   EXPECT_EQ("", remove_dots(".\\\\\\\\\\", false, path::Style::windows));
1184 
1185   EXPECT_EQ("a\\..\\b\\c",
1186             remove_dots(".\\a\\..\\b\\c", false, path::Style::windows));
1187   EXPECT_EQ("b\\c", remove_dots(".\\a\\..\\b\\c", true, path::Style::windows));
1188   EXPECT_EQ("c", remove_dots(".\\.\\c", true, path::Style::windows));
1189   EXPECT_EQ("..\\a\\c",
1190             remove_dots("..\\a\\b\\..\\c", true, path::Style::windows));
1191   EXPECT_EQ("..\\..\\a\\c",
1192             remove_dots("..\\..\\a\\b\\..\\c", true, path::Style::windows));
1193 
1194   SmallString<64> Path1(".\\.\\c");
1195   EXPECT_TRUE(path::remove_dots(Path1, true, path::Style::windows));
1196   EXPECT_EQ("c", Path1);
1197 
1198   EXPECT_EQ("foolz/wat",
1199             remove_dots("././/foolz/wat", false, path::Style::posix));
1200   EXPECT_EQ("", remove_dots("./////", false, path::Style::posix));
1201 
1202   EXPECT_EQ("a/../b/c", remove_dots("./a/../b/c", false, path::Style::posix));
1203   EXPECT_EQ("b/c", remove_dots("./a/../b/c", true, path::Style::posix));
1204   EXPECT_EQ("c", remove_dots("././c", true, path::Style::posix));
1205   EXPECT_EQ("../a/c", remove_dots("../a/b/../c", true, path::Style::posix));
1206   EXPECT_EQ("../../a/c",
1207             remove_dots("../../a/b/../c", true, path::Style::posix));
1208   EXPECT_EQ("/a/c", remove_dots("/../../a/c", true, path::Style::posix));
1209   EXPECT_EQ("/a/c",
1210             remove_dots("/../a/b//../././/c", true, path::Style::posix));
1211 
1212   SmallString<64> Path2("././c");
1213   EXPECT_TRUE(path::remove_dots(Path2, true, path::Style::posix));
1214   EXPECT_EQ("c", Path2);
1215 }
1216 
1217 TEST(Support, ReplacePathPrefix) {
1218   SmallString<64> Path1("/foo");
1219   SmallString<64> Path2("/old/foo");
1220   SmallString<64> OldPrefix("/old");
1221   SmallString<64> NewPrefix("/new");
1222   SmallString<64> NewPrefix2("/longernew");
1223   SmallString<64> EmptyPrefix("");
1224 
1225   SmallString<64> Path = Path1;
1226   path::replace_path_prefix(Path, OldPrefix, NewPrefix);
1227   EXPECT_EQ(Path, "/foo");
1228   Path = Path2;
1229   path::replace_path_prefix(Path, OldPrefix, NewPrefix);
1230   EXPECT_EQ(Path, "/new/foo");
1231   Path = Path2;
1232   path::replace_path_prefix(Path, OldPrefix, NewPrefix2);
1233   EXPECT_EQ(Path, "/longernew/foo");
1234   Path = Path1;
1235   path::replace_path_prefix(Path, EmptyPrefix, NewPrefix);
1236   EXPECT_EQ(Path, "/new/foo");
1237   Path = Path2;
1238   path::replace_path_prefix(Path, OldPrefix, EmptyPrefix);
1239   EXPECT_EQ(Path, "/foo");
1240 }
1241 
1242 TEST_F(FileSystemTest, OpenFileForRead) {
1243   // Create a temp file.
1244   int FileDescriptor;
1245   SmallString<64> TempPath;
1246   ASSERT_NO_ERROR(
1247       fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
1248   FileRemover Cleanup(TempPath);
1249 
1250   // Make sure it exists.
1251   ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
1252 
1253   // Open the file for read
1254   int FileDescriptor2;
1255   SmallString<64> ResultPath;
1256   ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath), FileDescriptor2,
1257                                       fs::OF_None, &ResultPath))
1258 
1259   // If we succeeded, check that the paths are the same (modulo case):
1260   if (!ResultPath.empty()) {
1261     // The paths returned by createTemporaryFile and getPathFromOpenFD
1262     // should reference the same file on disk.
1263     fs::UniqueID D1, D2;
1264     ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), D1));
1265     ASSERT_NO_ERROR(fs::getUniqueID(Twine(ResultPath), D2));
1266     ASSERT_EQ(D1, D2);
1267   }
1268   ::close(FileDescriptor);
1269   ::close(FileDescriptor2);
1270 
1271 #ifdef _WIN32
1272   // Since Windows Vista, file access time is not updated by default.
1273   // This is instead updated manually by openFileForRead.
1274   // https://blogs.technet.microsoft.com/filecab/2006/11/07/disabling-last-access-time-in-windows-vista-to-improve-ntfs-performance/
1275   // This part of the unit test is Windows specific as the updating of
1276   // access times can be disabled on Linux using /etc/fstab.
1277 
1278   // Set access time to UNIX epoch.
1279   ASSERT_NO_ERROR(sys::fs::openFileForWrite(Twine(TempPath), FileDescriptor,
1280                                             fs::CD_OpenExisting));
1281   TimePoint<> Epoch(std::chrono::milliseconds(0));
1282   ASSERT_NO_ERROR(fs::setLastAccessAndModificationTime(FileDescriptor, Epoch));
1283   ::close(FileDescriptor);
1284 
1285   // Open the file and ensure access time is updated, when forced.
1286   ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath), FileDescriptor,
1287                                       fs::OF_UpdateAtime, &ResultPath));
1288 
1289   sys::fs::file_status Status;
1290   ASSERT_NO_ERROR(sys::fs::status(FileDescriptor, Status));
1291   auto FileAccessTime = Status.getLastAccessedTime();
1292 
1293   ASSERT_NE(Epoch, FileAccessTime);
1294   ::close(FileDescriptor);
1295 
1296   // Ideally this test would include a case when ATime is not forced to update,
1297   // however the expected behaviour will differ depending on the configuration
1298   // of the Windows file system.
1299 #endif
1300 }
1301 
1302 static void createFileWithData(const Twine &Path, bool ShouldExistBefore,
1303                                fs::CreationDisposition Disp, StringRef Data) {
1304   int FD;
1305   ASSERT_EQ(ShouldExistBefore, fs::exists(Path));
1306   ASSERT_NO_ERROR(fs::openFileForWrite(Path, FD, Disp));
1307   FileDescriptorCloser Closer(FD);
1308   ASSERT_TRUE(fs::exists(Path));
1309 
1310   ASSERT_EQ(Data.size(), (size_t)write(FD, Data.data(), Data.size()));
1311 }
1312 
1313 static void verifyFileContents(const Twine &Path, StringRef Contents) {
1314   auto Buffer = MemoryBuffer::getFile(Path);
1315   ASSERT_TRUE((bool)Buffer);
1316   StringRef Data = Buffer.get()->getBuffer();
1317   ASSERT_EQ(Data, Contents);
1318 }
1319 
1320 TEST_F(FileSystemTest, CreateNew) {
1321   int FD;
1322   Optional<FileDescriptorCloser> Closer;
1323 
1324   // Succeeds if the file does not exist.
1325   ASSERT_FALSE(fs::exists(NonExistantFile));
1326   ASSERT_NO_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateNew));
1327   ASSERT_TRUE(fs::exists(NonExistantFile));
1328 
1329   FileRemover Cleanup(NonExistantFile);
1330   Closer.emplace(FD);
1331 
1332   // And creates a file of size 0.
1333   sys::fs::file_status Status;
1334   ASSERT_NO_ERROR(sys::fs::status(FD, Status));
1335   EXPECT_EQ(0ULL, Status.getSize());
1336 
1337   // Close this first, before trying to re-open the file.
1338   Closer.reset();
1339 
1340   // But fails if the file does exist.
1341   ASSERT_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateNew));
1342 }
1343 
1344 TEST_F(FileSystemTest, CreateAlways) {
1345   int FD;
1346   Optional<FileDescriptorCloser> Closer;
1347 
1348   // Succeeds if the file does not exist.
1349   ASSERT_FALSE(fs::exists(NonExistantFile));
1350   ASSERT_NO_ERROR(
1351       fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateAlways));
1352 
1353   Closer.emplace(FD);
1354 
1355   ASSERT_TRUE(fs::exists(NonExistantFile));
1356 
1357   FileRemover Cleanup(NonExistantFile);
1358 
1359   // And creates a file of size 0.
1360   uint64_t FileSize;
1361   ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1362   ASSERT_EQ(0ULL, FileSize);
1363 
1364   // If we write some data to it re-create it with CreateAlways, it succeeds and
1365   // truncates to 0 bytes.
1366   ASSERT_EQ(4, write(FD, "Test", 4));
1367 
1368   Closer.reset();
1369 
1370   ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1371   ASSERT_EQ(4ULL, FileSize);
1372 
1373   ASSERT_NO_ERROR(
1374       fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateAlways));
1375   Closer.emplace(FD);
1376   ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1377   ASSERT_EQ(0ULL, FileSize);
1378 }
1379 
1380 TEST_F(FileSystemTest, OpenExisting) {
1381   int FD;
1382 
1383   // Fails if the file does not exist.
1384   ASSERT_FALSE(fs::exists(NonExistantFile));
1385   ASSERT_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_OpenExisting));
1386   ASSERT_FALSE(fs::exists(NonExistantFile));
1387 
1388   // Make a dummy file now so that we can try again when the file does exist.
1389   createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1390   FileRemover Cleanup(NonExistantFile);
1391   uint64_t FileSize;
1392   ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1393   ASSERT_EQ(4ULL, FileSize);
1394 
1395   // If we re-create it with different data, it overwrites rather than
1396   // appending.
1397   createFileWithData(NonExistantFile, true, fs::CD_OpenExisting, "Buzz");
1398   verifyFileContents(NonExistantFile, "Buzz");
1399 }
1400 
1401 TEST_F(FileSystemTest, OpenAlways) {
1402   // Succeeds if the file does not exist.
1403   createFileWithData(NonExistantFile, false, fs::CD_OpenAlways, "Fizz");
1404   FileRemover Cleanup(NonExistantFile);
1405   uint64_t FileSize;
1406   ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1407   ASSERT_EQ(4ULL, FileSize);
1408 
1409   // Now re-open it and write again, verifying the contents get over-written.
1410   createFileWithData(NonExistantFile, true, fs::CD_OpenAlways, "Bu");
1411   verifyFileContents(NonExistantFile, "Buzz");
1412 }
1413 
1414 TEST_F(FileSystemTest, AppendSetsCorrectFileOffset) {
1415   fs::CreationDisposition Disps[] = {fs::CD_CreateAlways, fs::CD_OpenAlways,
1416                                      fs::CD_OpenExisting};
1417 
1418   // Write some data and re-open it with every possible disposition (this is a
1419   // hack that shouldn't work, but is left for compatibility.  F_Append
1420   // overrides
1421   // the specified disposition.
1422   for (fs::CreationDisposition Disp : Disps) {
1423     int FD;
1424     Optional<FileDescriptorCloser> Closer;
1425 
1426     createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1427 
1428     FileRemover Cleanup(NonExistantFile);
1429 
1430     uint64_t FileSize;
1431     ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1432     ASSERT_EQ(4ULL, FileSize);
1433     ASSERT_NO_ERROR(
1434         fs::openFileForWrite(NonExistantFile, FD, Disp, fs::OF_Append));
1435     Closer.emplace(FD);
1436     ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1437     ASSERT_EQ(4ULL, FileSize);
1438 
1439     ASSERT_EQ(4, write(FD, "Buzz", 4));
1440     Closer.reset();
1441 
1442     verifyFileContents(NonExistantFile, "FizzBuzz");
1443   }
1444 }
1445 
1446 static void verifyRead(int FD, StringRef Data, bool ShouldSucceed) {
1447   std::vector<char> Buffer;
1448   Buffer.resize(Data.size());
1449   int Result = ::read(FD, Buffer.data(), Buffer.size());
1450   if (ShouldSucceed) {
1451     ASSERT_EQ((size_t)Result, Data.size());
1452     ASSERT_EQ(Data, StringRef(Buffer.data(), Buffer.size()));
1453   } else {
1454     ASSERT_EQ(-1, Result);
1455     ASSERT_EQ(EBADF, errno);
1456   }
1457 }
1458 
1459 static void verifyWrite(int FD, StringRef Data, bool ShouldSucceed) {
1460   int Result = ::write(FD, Data.data(), Data.size());
1461   if (ShouldSucceed)
1462     ASSERT_EQ((size_t)Result, Data.size());
1463   else {
1464     ASSERT_EQ(-1, Result);
1465     ASSERT_EQ(EBADF, errno);
1466   }
1467 }
1468 
1469 TEST_F(FileSystemTest, ReadOnlyFileCantWrite) {
1470   createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1471   FileRemover Cleanup(NonExistantFile);
1472 
1473   int FD;
1474   ASSERT_NO_ERROR(fs::openFileForRead(NonExistantFile, FD));
1475   FileDescriptorCloser Closer(FD);
1476 
1477   verifyWrite(FD, "Buzz", false);
1478   verifyRead(FD, "Fizz", true);
1479 }
1480 
1481 TEST_F(FileSystemTest, WriteOnlyFileCantRead) {
1482   createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1483   FileRemover Cleanup(NonExistantFile);
1484 
1485   int FD;
1486   ASSERT_NO_ERROR(
1487       fs::openFileForWrite(NonExistantFile, FD, fs::CD_OpenExisting));
1488   FileDescriptorCloser Closer(FD);
1489   verifyRead(FD, "Fizz", false);
1490   verifyWrite(FD, "Buzz", true);
1491 }
1492 
1493 TEST_F(FileSystemTest, ReadWriteFileCanReadOrWrite) {
1494   createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1495   FileRemover Cleanup(NonExistantFile);
1496 
1497   int FD;
1498   ASSERT_NO_ERROR(fs::openFileForReadWrite(NonExistantFile, FD,
1499                                            fs::CD_OpenExisting, fs::OF_None));
1500   FileDescriptorCloser Closer(FD);
1501   verifyRead(FD, "Fizz", true);
1502   verifyWrite(FD, "Buzz", true);
1503 }
1504 
1505 TEST_F(FileSystemTest, is_local) {
1506   bool TestDirectoryIsLocal;
1507   ASSERT_NO_ERROR(fs::is_local(TestDirectory, TestDirectoryIsLocal));
1508   EXPECT_EQ(TestDirectoryIsLocal, fs::is_local(TestDirectory));
1509 
1510   int FD;
1511   SmallString<128> TempPath;
1512   ASSERT_NO_ERROR(
1513       fs::createUniqueFile(Twine(TestDirectory) + "/temp", FD, TempPath));
1514   FileRemover Cleanup(TempPath);
1515 
1516   // Make sure it exists.
1517   ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
1518 
1519   bool TempFileIsLocal;
1520   ASSERT_NO_ERROR(fs::is_local(FD, TempFileIsLocal));
1521   EXPECT_EQ(TempFileIsLocal, fs::is_local(FD));
1522   ::close(FD);
1523 
1524   // Expect that the file and its parent directory are equally local or equally
1525   // remote.
1526   EXPECT_EQ(TestDirectoryIsLocal, TempFileIsLocal);
1527 }
1528 
1529 TEST_F(FileSystemTest, getUmask) {
1530 #ifdef _WIN32
1531   EXPECT_EQ(fs::getUmask(), 0U) << "Should always be 0 on Windows.";
1532 #else
1533   unsigned OldMask = ::umask(0022);
1534   unsigned CurrentMask = fs::getUmask();
1535   EXPECT_EQ(CurrentMask, 0022U)
1536       << "getUmask() didn't return previously set umask()";
1537   EXPECT_EQ(::umask(OldMask), 0022U) << "getUmask() may have changed umask()";
1538 #endif
1539 }
1540 
1541 TEST_F(FileSystemTest, RespectUmask) {
1542 #ifndef _WIN32
1543   unsigned OldMask = ::umask(0022);
1544 
1545   int FD;
1546   SmallString<128> TempPath;
1547   ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1548 
1549   fs::perms AllRWE = static_cast<fs::perms>(0777);
1550 
1551   ASSERT_NO_ERROR(fs::setPermissions(TempPath, AllRWE /*RespectUmask=false*/));
1552 
1553   ErrorOr<fs::perms> Perms = fs::getPermissions(TempPath);
1554   ASSERT_TRUE(!!Perms);
1555   EXPECT_EQ(Perms.get(), AllRWE) << "Should have ignored umask by default";
1556 
1557   ASSERT_NO_ERROR(fs::setPermissions(TempPath, AllRWE, /*RespectUmask=*/false));
1558 
1559   Perms = fs::getPermissions(TempPath);
1560   ASSERT_TRUE(!!Perms);
1561   EXPECT_EQ(Perms.get(), AllRWE) << "Should have ignored umask";
1562 
1563   ASSERT_NO_ERROR(fs::setPermissions(TempPath, AllRWE, /*RespectUmask=*/true));
1564   Perms = fs::getPermissions(TempPath);
1565   ASSERT_TRUE(!!Perms);
1566   EXPECT_EQ(Perms.get(), static_cast<fs::perms>(0755))
1567       << "Did not respect umask";
1568 
1569   (void)::umask(0057);
1570 
1571   ASSERT_NO_ERROR(fs::setPermissions(TempPath, AllRWE, /*RespectUmask=*/true));
1572   Perms = fs::getPermissions(TempPath);
1573   ASSERT_TRUE(!!Perms);
1574   EXPECT_EQ(Perms.get(), static_cast<fs::perms>(0720))
1575       << "Did not respect umask";
1576 
1577   (void)::umask(OldMask);
1578   (void)::close(FD);
1579 #endif
1580 }
1581 
1582 TEST_F(FileSystemTest, set_current_path) {
1583   SmallString<128> path;
1584 
1585   ASSERT_NO_ERROR(fs::current_path(path));
1586   ASSERT_NE(TestDirectory, path);
1587 
1588   struct RestorePath {
1589     SmallString<128> path;
1590     RestorePath(const SmallString<128> &path) : path(path) {}
1591     ~RestorePath() { fs::set_current_path(path); }
1592   } restore_path(path);
1593 
1594   ASSERT_NO_ERROR(fs::set_current_path(TestDirectory));
1595 
1596   ASSERT_NO_ERROR(fs::current_path(path));
1597 
1598   fs::UniqueID D1, D2;
1599   ASSERT_NO_ERROR(fs::getUniqueID(TestDirectory, D1));
1600   ASSERT_NO_ERROR(fs::getUniqueID(path, D2));
1601   ASSERT_EQ(D1, D2) << "D1: " << TestDirectory << "\nD2: " << path;
1602 }
1603 
1604 TEST_F(FileSystemTest, permissions) {
1605   int FD;
1606   SmallString<64> TempPath;
1607   ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1608   FileRemover Cleanup(TempPath);
1609 
1610   // Make sure it exists.
1611   ASSERT_TRUE(fs::exists(Twine(TempPath)));
1612 
1613   auto CheckPermissions = [&](fs::perms Expected) {
1614     ErrorOr<fs::perms> Actual = fs::getPermissions(TempPath);
1615     return Actual && *Actual == Expected;
1616   };
1617 
1618   std::error_code NoError;
1619   EXPECT_EQ(fs::setPermissions(TempPath, fs::all_all), NoError);
1620   EXPECT_TRUE(CheckPermissions(fs::all_all));
1621 
1622   EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read | fs::all_exe), NoError);
1623   EXPECT_TRUE(CheckPermissions(fs::all_read | fs::all_exe));
1624 
1625 #if defined(_WIN32)
1626   fs::perms ReadOnly = fs::all_read | fs::all_exe;
1627   EXPECT_EQ(fs::setPermissions(TempPath, fs::no_perms), NoError);
1628   EXPECT_TRUE(CheckPermissions(ReadOnly));
1629 
1630   EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_read), NoError);
1631   EXPECT_TRUE(CheckPermissions(ReadOnly));
1632 
1633   EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_write), NoError);
1634   EXPECT_TRUE(CheckPermissions(fs::all_all));
1635 
1636   EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_exe), NoError);
1637   EXPECT_TRUE(CheckPermissions(ReadOnly));
1638 
1639   EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_all), NoError);
1640   EXPECT_TRUE(CheckPermissions(fs::all_all));
1641 
1642   EXPECT_EQ(fs::setPermissions(TempPath, fs::group_read), NoError);
1643   EXPECT_TRUE(CheckPermissions(ReadOnly));
1644 
1645   EXPECT_EQ(fs::setPermissions(TempPath, fs::group_write), NoError);
1646   EXPECT_TRUE(CheckPermissions(fs::all_all));
1647 
1648   EXPECT_EQ(fs::setPermissions(TempPath, fs::group_exe), NoError);
1649   EXPECT_TRUE(CheckPermissions(ReadOnly));
1650 
1651   EXPECT_EQ(fs::setPermissions(TempPath, fs::group_all), NoError);
1652   EXPECT_TRUE(CheckPermissions(fs::all_all));
1653 
1654   EXPECT_EQ(fs::setPermissions(TempPath, fs::others_read), NoError);
1655   EXPECT_TRUE(CheckPermissions(ReadOnly));
1656 
1657   EXPECT_EQ(fs::setPermissions(TempPath, fs::others_write), NoError);
1658   EXPECT_TRUE(CheckPermissions(fs::all_all));
1659 
1660   EXPECT_EQ(fs::setPermissions(TempPath, fs::others_exe), NoError);
1661   EXPECT_TRUE(CheckPermissions(ReadOnly));
1662 
1663   EXPECT_EQ(fs::setPermissions(TempPath, fs::others_all), NoError);
1664   EXPECT_TRUE(CheckPermissions(fs::all_all));
1665 
1666   EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read), NoError);
1667   EXPECT_TRUE(CheckPermissions(ReadOnly));
1668 
1669   EXPECT_EQ(fs::setPermissions(TempPath, fs::all_write), NoError);
1670   EXPECT_TRUE(CheckPermissions(fs::all_all));
1671 
1672   EXPECT_EQ(fs::setPermissions(TempPath, fs::all_exe), NoError);
1673   EXPECT_TRUE(CheckPermissions(ReadOnly));
1674 
1675   EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe), NoError);
1676   EXPECT_TRUE(CheckPermissions(ReadOnly));
1677 
1678   EXPECT_EQ(fs::setPermissions(TempPath, fs::set_gid_on_exe), NoError);
1679   EXPECT_TRUE(CheckPermissions(ReadOnly));
1680 
1681   EXPECT_EQ(fs::setPermissions(TempPath, fs::sticky_bit), NoError);
1682   EXPECT_TRUE(CheckPermissions(ReadOnly));
1683 
1684   EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe |
1685                                              fs::set_gid_on_exe |
1686                                              fs::sticky_bit),
1687             NoError);
1688   EXPECT_TRUE(CheckPermissions(ReadOnly));
1689 
1690   EXPECT_EQ(fs::setPermissions(TempPath, ReadOnly | fs::set_uid_on_exe |
1691                                              fs::set_gid_on_exe |
1692                                              fs::sticky_bit),
1693             NoError);
1694   EXPECT_TRUE(CheckPermissions(ReadOnly));
1695 
1696   EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms), NoError);
1697   EXPECT_TRUE(CheckPermissions(fs::all_all));
1698 #else
1699   EXPECT_EQ(fs::setPermissions(TempPath, fs::no_perms), NoError);
1700   EXPECT_TRUE(CheckPermissions(fs::no_perms));
1701 
1702   EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_read), NoError);
1703   EXPECT_TRUE(CheckPermissions(fs::owner_read));
1704 
1705   EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_write), NoError);
1706   EXPECT_TRUE(CheckPermissions(fs::owner_write));
1707 
1708   EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_exe), NoError);
1709   EXPECT_TRUE(CheckPermissions(fs::owner_exe));
1710 
1711   EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_all), NoError);
1712   EXPECT_TRUE(CheckPermissions(fs::owner_all));
1713 
1714   EXPECT_EQ(fs::setPermissions(TempPath, fs::group_read), NoError);
1715   EXPECT_TRUE(CheckPermissions(fs::group_read));
1716 
1717   EXPECT_EQ(fs::setPermissions(TempPath, fs::group_write), NoError);
1718   EXPECT_TRUE(CheckPermissions(fs::group_write));
1719 
1720   EXPECT_EQ(fs::setPermissions(TempPath, fs::group_exe), NoError);
1721   EXPECT_TRUE(CheckPermissions(fs::group_exe));
1722 
1723   EXPECT_EQ(fs::setPermissions(TempPath, fs::group_all), NoError);
1724   EXPECT_TRUE(CheckPermissions(fs::group_all));
1725 
1726   EXPECT_EQ(fs::setPermissions(TempPath, fs::others_read), NoError);
1727   EXPECT_TRUE(CheckPermissions(fs::others_read));
1728 
1729   EXPECT_EQ(fs::setPermissions(TempPath, fs::others_write), NoError);
1730   EXPECT_TRUE(CheckPermissions(fs::others_write));
1731 
1732   EXPECT_EQ(fs::setPermissions(TempPath, fs::others_exe), NoError);
1733   EXPECT_TRUE(CheckPermissions(fs::others_exe));
1734 
1735   EXPECT_EQ(fs::setPermissions(TempPath, fs::others_all), NoError);
1736   EXPECT_TRUE(CheckPermissions(fs::others_all));
1737 
1738   EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read), NoError);
1739   EXPECT_TRUE(CheckPermissions(fs::all_read));
1740 
1741   EXPECT_EQ(fs::setPermissions(TempPath, fs::all_write), NoError);
1742   EXPECT_TRUE(CheckPermissions(fs::all_write));
1743 
1744   EXPECT_EQ(fs::setPermissions(TempPath, fs::all_exe), NoError);
1745   EXPECT_TRUE(CheckPermissions(fs::all_exe));
1746 
1747   EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe), NoError);
1748   EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe));
1749 
1750   EXPECT_EQ(fs::setPermissions(TempPath, fs::set_gid_on_exe), NoError);
1751   EXPECT_TRUE(CheckPermissions(fs::set_gid_on_exe));
1752 
1753   // Modern BSDs require root to set the sticky bit on files.
1754   // AIX and Solaris without root will mask off (i.e., lose) the sticky bit
1755   // on files.
1756 #if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) &&  \
1757     !defined(_AIX) && !(defined(__sun__) && defined(__svr4__))
1758   EXPECT_EQ(fs::setPermissions(TempPath, fs::sticky_bit), NoError);
1759   EXPECT_TRUE(CheckPermissions(fs::sticky_bit));
1760 
1761   EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe |
1762                                              fs::set_gid_on_exe |
1763                                              fs::sticky_bit),
1764             NoError);
1765   EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe | fs::set_gid_on_exe |
1766                                fs::sticky_bit));
1767 
1768   EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read | fs::set_uid_on_exe |
1769                                              fs::set_gid_on_exe |
1770                                              fs::sticky_bit),
1771             NoError);
1772   EXPECT_TRUE(CheckPermissions(fs::all_read | fs::set_uid_on_exe |
1773                                fs::set_gid_on_exe | fs::sticky_bit));
1774 
1775   EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms), NoError);
1776   EXPECT_TRUE(CheckPermissions(fs::all_perms));
1777 #endif // !FreeBSD && !NetBSD && !OpenBSD && !AIX
1778 
1779   EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms & ~fs::sticky_bit),
1780                                NoError);
1781   EXPECT_TRUE(CheckPermissions(fs::all_perms & ~fs::sticky_bit));
1782 #endif
1783 }
1784 
1785 } // anonymous namespace
1786