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