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