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