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