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