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