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