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