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