1 //===- llvm/unittest/Support/Path.cpp - Path tests ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Support/Path.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/ADT/Triple.h"
14 #include "llvm/BinaryFormat/Magic.h"
15 #include "llvm/Support/ConvertUTF.h"
16 #include "llvm/Support/Errc.h"
17 #include "llvm/Support/ErrorHandling.h"
18 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/FileUtilities.h"
20 #include "llvm/Support/Host.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "gtest/gtest.h"
26 #include "llvm/ADT/ArrayRef.h"
37 using namespace llvm::sys;
39 #define ASSERT_NO_ERROR(x) \
40 if (std::error_code ASSERT_NO_ERROR_ec = x) { \
41 SmallString<128> MessageStorage; \
42 raw_svector_ostream Message(MessageStorage); \
43 Message << #x ": did not return errc::success.\n" \
44 << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n" \
45 << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \
46 GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \
52 TEST(is_separator, Works) {
53 EXPECT_TRUE(path::is_separator('/'));
54 EXPECT_FALSE(path::is_separator('\0'));
55 EXPECT_FALSE(path::is_separator('-'));
56 EXPECT_FALSE(path::is_separator(' '));
58 EXPECT_TRUE(path::is_separator('\\', path::Style::windows));
59 EXPECT_FALSE(path::is_separator('\\', path::Style::posix));
62 EXPECT_TRUE(path::is_separator('\\'));
64 EXPECT_FALSE(path::is_separator('\\'));
69 SmallVector<StringRef, 40> paths;
72 paths.push_back("..");
73 paths.push_back("foo");
75 paths.push_back("/foo");
76 paths.push_back("foo/");
77 paths.push_back("/foo/");
78 paths.push_back("foo/bar");
79 paths.push_back("/foo/bar");
80 paths.push_back("//net");
81 paths.push_back("//net/foo");
82 paths.push_back("///foo///");
83 paths.push_back("///foo///bar");
84 paths.push_back("/.");
85 paths.push_back("./");
86 paths.push_back("/..");
87 paths.push_back("../");
88 paths.push_back("foo/.");
89 paths.push_back("foo/..");
90 paths.push_back("foo/./");
91 paths.push_back("foo/./bar");
92 paths.push_back("foo/..");
93 paths.push_back("foo/../");
94 paths.push_back("foo/../bar");
95 paths.push_back("c:");
96 paths.push_back("c:/");
97 paths.push_back("c:foo");
98 paths.push_back("c:/foo");
99 paths.push_back("c:foo/");
100 paths.push_back("c:/foo/");
101 paths.push_back("c:/foo/bar");
102 paths.push_back("prn:");
103 paths.push_back("c:\\");
104 paths.push_back("c:foo");
105 paths.push_back("c:\\foo");
106 paths.push_back("c:foo\\");
107 paths.push_back("c:\\foo\\");
108 paths.push_back("c:\\foo/");
109 paths.push_back("c:/foo\\bar");
111 SmallVector<StringRef, 5> ComponentStack;
112 for (SmallVector<StringRef, 40>::const_iterator i = paths.begin(),
116 for (sys::path::const_iterator ci = sys::path::begin(*i),
117 ce = sys::path::end(*i);
120 ASSERT_FALSE(ci->empty());
121 ComponentStack.push_back(*ci);
124 for (sys::path::reverse_iterator ci = sys::path::rbegin(*i),
125 ce = sys::path::rend(*i);
128 ASSERT_TRUE(*ci == ComponentStack.back());
129 ComponentStack.pop_back();
131 ASSERT_TRUE(ComponentStack.empty());
133 // Crash test most of the API - since we're iterating over all of our paths
134 // here there isn't really anything reasonable to assert on in the results.
135 (void)path::has_root_path(*i);
136 (void)path::root_path(*i);
137 (void)path::has_root_name(*i);
138 (void)path::root_name(*i);
139 (void)path::has_root_directory(*i);
140 (void)path::root_directory(*i);
141 (void)path::has_parent_path(*i);
142 (void)path::parent_path(*i);
143 (void)path::has_filename(*i);
144 (void)path::filename(*i);
145 (void)path::has_stem(*i);
146 (void)path::stem(*i);
147 (void)path::has_extension(*i);
148 (void)path::extension(*i);
149 (void)path::is_absolute(*i);
150 (void)path::is_relative(*i);
152 SmallString<128> temp_store;
154 ASSERT_NO_ERROR(fs::make_absolute(temp_store));
156 path::remove_filename(temp_store);
159 path::replace_extension(temp_store, "ext");
160 StringRef filename(temp_store.begin(), temp_store.size()), stem, ext;
161 stem = path::stem(filename);
162 ext = path::extension(filename);
163 EXPECT_EQ(*sys::path::rbegin(filename), (stem + ext).str());
165 path::native(*i, temp_store);
168 SmallString<32> Relative("foo.cpp");
169 ASSERT_NO_ERROR(sys::fs::make_absolute("/root", Relative));
170 Relative[5] = '/'; // Fix up windows paths.
171 ASSERT_EQ("/root/foo.cpp", Relative);
174 TEST(Support, RelativePathIterator) {
175 SmallString<64> Path(StringRef("c/d/e/foo.txt"));
176 typedef SmallVector<StringRef, 4> PathComponents;
177 PathComponents ExpectedPathComponents;
178 PathComponents ActualPathComponents;
180 StringRef(Path).split(ExpectedPathComponents, '/');
182 for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
184 ActualPathComponents.push_back(*I);
187 ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
189 for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
190 EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
194 TEST(Support, RelativePathDotIterator) {
195 SmallString<64> Path(StringRef(".c/.d/../."));
196 typedef SmallVector<StringRef, 4> PathComponents;
197 PathComponents ExpectedPathComponents;
198 PathComponents ActualPathComponents;
200 StringRef(Path).split(ExpectedPathComponents, '/');
202 for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
204 ActualPathComponents.push_back(*I);
207 ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
209 for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
210 EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
214 TEST(Support, AbsolutePathIterator) {
215 SmallString<64> Path(StringRef("/c/d/e/foo.txt"));
216 typedef SmallVector<StringRef, 4> PathComponents;
217 PathComponents ExpectedPathComponents;
218 PathComponents ActualPathComponents;
220 StringRef(Path).split(ExpectedPathComponents, '/');
222 // The root path will also be a component when iterating
223 ExpectedPathComponents[0] = "/";
225 for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
227 ActualPathComponents.push_back(*I);
230 ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
232 for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
233 EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
237 TEST(Support, AbsolutePathDotIterator) {
238 SmallString<64> Path(StringRef("/.c/.d/../."));
239 typedef SmallVector<StringRef, 4> PathComponents;
240 PathComponents ExpectedPathComponents;
241 PathComponents ActualPathComponents;
243 StringRef(Path).split(ExpectedPathComponents, '/');
245 // The root path will also be a component when iterating
246 ExpectedPathComponents[0] = "/";
248 for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
250 ActualPathComponents.push_back(*I);
253 ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
255 for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
256 EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
260 TEST(Support, AbsolutePathIteratorWin32) {
261 SmallString<64> Path(StringRef("c:\\c\\e\\foo.txt"));
262 typedef SmallVector<StringRef, 4> PathComponents;
263 PathComponents ExpectedPathComponents;
264 PathComponents ActualPathComponents;
266 StringRef(Path).split(ExpectedPathComponents, "\\");
268 // The root path (which comes after the drive name) will also be a component
270 ExpectedPathComponents.insert(ExpectedPathComponents.begin()+1, "\\");
272 for (path::const_iterator I = path::begin(Path, path::Style::windows),
275 ActualPathComponents.push_back(*I);
278 ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
280 for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
281 EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
285 TEST(Support, AbsolutePathIteratorEnd) {
286 // Trailing slashes are converted to '.' unless they are part of the root path.
287 SmallVector<std::pair<StringRef, path::Style>, 4> Paths;
288 Paths.emplace_back("/foo/", path::Style::native);
289 Paths.emplace_back("/foo//", path::Style::native);
290 Paths.emplace_back("//net//", path::Style::native);
291 Paths.emplace_back("c:\\\\", path::Style::windows);
293 for (auto &Path : Paths) {
294 StringRef LastComponent = *path::rbegin(Path.first, Path.second);
295 EXPECT_EQ(".", LastComponent);
298 SmallVector<std::pair<StringRef, path::Style>, 3> RootPaths;
299 RootPaths.emplace_back("/", path::Style::native);
300 RootPaths.emplace_back("//net/", path::Style::native);
301 RootPaths.emplace_back("c:\\", path::Style::windows);
303 for (auto &Path : RootPaths) {
304 StringRef LastComponent = *path::rbegin(Path.first, Path.second);
305 EXPECT_EQ(1u, LastComponent.size());
306 EXPECT_TRUE(path::is_separator(LastComponent[0], Path.second));
310 TEST(Support, HomeDirectory) {
311 std::string expected;
313 if (wchar_t const *path = ::_wgetenv(L"USERPROFILE")) {
314 auto pathLen = ::wcslen(path);
315 ArrayRef<char> ref{reinterpret_cast<char const *>(path),
316 pathLen * sizeof(wchar_t)};
317 convertUTF16ToUTF8String(ref, expected);
320 if (char const *path = ::getenv("HOME"))
323 // Do not try to test it if we don't know what to expect.
324 // On Windows we use something better than env vars.
325 if (!expected.empty()) {
326 SmallString<128> HomeDir;
327 auto status = path::home_directory(HomeDir);
329 EXPECT_EQ(expected, HomeDir);
334 TEST(Support, HomeDirectoryWithNoEnv) {
335 std::string OriginalStorage;
336 char const *OriginalEnv = ::getenv("HOME");
338 // We're going to unset it, so make a copy and save a pointer to the copy
339 // so that we can reset it at the end of the test.
340 OriginalStorage = OriginalEnv;
341 OriginalEnv = OriginalStorage.c_str();
344 // Don't run the test if we have nothing to compare against.
345 struct passwd *pw = getpwuid(getuid());
346 if (!pw || !pw->pw_dir) return;
349 EXPECT_EQ(nullptr, ::getenv("HOME"));
350 std::string PwDir = pw->pw_dir;
352 SmallString<128> HomeDir;
353 auto status = path::home_directory(HomeDir);
355 EXPECT_EQ(PwDir, HomeDir);
357 // Now put the environment back to its original state (meaning that if it was
358 // unset before, we don't reset it).
359 if (OriginalEnv) ::setenv("HOME", OriginalEnv, 1);
363 TEST(Support, UserCacheDirectory) {
364 SmallString<13> CacheDir;
365 SmallString<20> CacheDir2;
366 auto Status = path::user_cache_directory(CacheDir, "");
367 EXPECT_TRUE(Status ^ CacheDir.empty());
370 EXPECT_TRUE(path::user_cache_directory(CacheDir2, "")); // should succeed
371 EXPECT_EQ(CacheDir, CacheDir2); // and return same paths
373 EXPECT_TRUE(path::user_cache_directory(CacheDir, "A", "B", "file.c"));
374 auto It = path::rbegin(CacheDir);
375 EXPECT_EQ("file.c", *It);
376 EXPECT_EQ("B", *++It);
377 EXPECT_EQ("A", *++It);
378 auto ParentDir = *++It;
380 // Test Unicode: "<user_cache_dir>/(pi)r^2/aleth.0"
381 EXPECT_TRUE(path::user_cache_directory(CacheDir2, "\xCF\x80r\xC2\xB2",
383 auto It2 = path::rbegin(CacheDir2);
384 EXPECT_EQ("\xE2\x84\xB5.0", *It2);
385 EXPECT_EQ("\xCF\x80r\xC2\xB2", *++It2);
386 auto ParentDir2 = *++It2;
388 EXPECT_EQ(ParentDir, ParentDir2);
392 TEST(Support, TempDirectory) {
393 SmallString<32> TempDir;
394 path::system_temp_directory(false, TempDir);
395 EXPECT_TRUE(!TempDir.empty());
397 path::system_temp_directory(true, TempDir);
398 EXPECT_TRUE(!TempDir.empty());
402 static std::string path2regex(std::string Path) {
404 while ((Pos = Path.find('\\', Pos)) != std::string::npos) {
405 Path.replace(Pos, 1, "\\\\");
411 /// Helper for running temp dir test in separated process. See below.
412 #define EXPECT_TEMP_DIR(prepare, expected) \
416 SmallString<300> TempDir; \
417 path::system_temp_directory(true, TempDir); \
418 raw_os_ostream(std::cerr) << TempDir; \
421 ::testing::ExitedWithCode(0), path2regex(expected))
423 TEST(SupportDeathTest, TempDirectoryOnWindows) {
424 // In this test we want to check how system_temp_directory responds to
425 // different values of specific env vars. To prevent corrupting env vars of
426 // the current process all checks are done in separated processes.
427 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"C:\\OtherFolder"), "C:\\OtherFolder");
428 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"C:/Unix/Path/Seperators"),
429 "C:\\Unix\\Path\\Seperators");
430 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"Local Path"), ".+\\Local Path$");
431 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"F:\\TrailingSep\\"), "F:\\TrailingSep");
433 _wputenv_s(L"TMP", L"C:\\2\x03C0r-\x00B5\x00B3\\\x2135\x2080"),
434 "C:\\2\xCF\x80r-\xC2\xB5\xC2\xB3\\\xE2\x84\xB5\xE2\x82\x80");
436 // Test $TMP empty, $TEMP set.
439 _wputenv_s(L"TMP", L"");
440 _wputenv_s(L"TEMP", L"C:\\Valid\\Path");
444 // All related env vars empty
447 _wputenv_s(L"TMP", L"");
448 _wputenv_s(L"TEMP", L"");
449 _wputenv_s(L"USERPROFILE", L"");
453 // Test evn var / path with 260 chars.
454 SmallString<270> Expected{"C:\\Temp\\AB\\123456789"};
455 while (Expected.size() < 260)
456 Expected.append("\\DirNameWith19Charss");
457 ASSERT_EQ(260U, Expected.size());
458 EXPECT_TEMP_DIR(_putenv_s("TMP", Expected.c_str()), Expected.c_str());
462 class FileSystemTest : public testing::Test {
464 /// Unique temporary directory in which all created filesystem entities must
465 /// be placed. It is removed at the end of each test (must be empty).
466 SmallString<128> TestDirectory;
468 void SetUp() override {
470 fs::createUniqueDirectory("file-system-test", TestDirectory));
471 // We don't care about this specific file.
472 errs() << "Test Directory: " << TestDirectory << '\n';
476 void TearDown() override { ASSERT_NO_ERROR(fs::remove(TestDirectory.str())); }
479 TEST_F(FileSystemTest, Unique) {
480 // Create a temp file.
482 SmallString<64> TempPath;
484 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
486 // The same file should return an identical unique id.
488 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F1));
489 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F2));
492 // Different files should return different unique ids.
494 SmallString<64> TempPath2;
496 fs::createTemporaryFile("prefix", "temp", FileDescriptor2, TempPath2));
499 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D));
501 ::close(FileDescriptor2);
503 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
505 // Two paths representing the same file on disk should still provide the
506 // same unique id. We can test this by making a hard link.
507 ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2)));
509 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D2));
512 ::close(FileDescriptor);
514 SmallString<128> Dir1;
516 fs::createUniqueDirectory("dir1", Dir1));
517 ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F1));
518 ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F2));
521 SmallString<128> Dir2;
523 fs::createUniqueDirectory("dir2", Dir2));
524 ASSERT_NO_ERROR(fs::getUniqueID(Dir2.c_str(), F2));
526 ASSERT_NO_ERROR(fs::remove(Dir1));
527 ASSERT_NO_ERROR(fs::remove(Dir2));
528 ASSERT_NO_ERROR(fs::remove(TempPath2));
529 ASSERT_NO_ERROR(fs::remove(TempPath));
532 TEST_F(FileSystemTest, RealPath) {
534 fs::create_directories(Twine(TestDirectory) + "/test1/test2/test3"));
535 ASSERT_TRUE(fs::exists(Twine(TestDirectory) + "/test1/test2/test3"));
537 SmallString<64> RealBase;
538 SmallString<64> Expected;
539 SmallString<64> Actual;
541 // TestDirectory itself might be under a symlink or have been specified with
542 // a different case than the existing temp directory. In such cases real_path
543 // on the concatenated path will differ in the TestDirectory portion from
544 // how we specified it. Make sure to compare against the real_path of the
545 // TestDirectory, and not just the value of TestDirectory.
546 ASSERT_NO_ERROR(fs::real_path(TestDirectory, RealBase));
547 path::native(Twine(RealBase) + "/test1/test2", Expected);
549 ASSERT_NO_ERROR(fs::real_path(
550 Twine(TestDirectory) + "/././test1/../test1/test2/./test3/..", Actual));
552 EXPECT_EQ(Expected, Actual);
554 SmallString<64> HomeDir;
555 bool Result = llvm::sys::path::home_directory(HomeDir);
557 ASSERT_NO_ERROR(fs::real_path(HomeDir, Expected));
558 ASSERT_NO_ERROR(fs::real_path("~", Actual, true));
559 EXPECT_EQ(Expected, Actual);
560 ASSERT_NO_ERROR(fs::real_path("~/", Actual, true));
561 EXPECT_EQ(Expected, Actual);
564 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/test1"));
568 TEST_F(FileSystemTest, RealPathNoReadPerm) {
569 SmallString<64> Expanded;
572 fs::create_directories(Twine(TestDirectory) + "/noreadperm"));
573 ASSERT_TRUE(fs::exists(Twine(TestDirectory) + "/noreadperm"));
575 fs::setPermissions(Twine(TestDirectory) + "/noreadperm", fs::no_perms);
576 fs::setPermissions(Twine(TestDirectory) + "/noreadperm", fs::all_exe);
578 ASSERT_NO_ERROR(fs::real_path(Twine(TestDirectory) + "/noreadperm", Expanded,
581 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/noreadperm"));
586 TEST_F(FileSystemTest, TempFileKeepDiscard) {
587 // We can keep then discard.
588 auto TempFileOrError = fs::TempFile::create(TestDirectory + "/test-%%%%");
589 ASSERT_TRUE((bool)TempFileOrError);
590 fs::TempFile File = std::move(*TempFileOrError);
591 ASSERT_FALSE((bool)File.keep(TestDirectory + "/keep"));
592 ASSERT_FALSE((bool)File.discard());
593 ASSERT_TRUE(fs::exists(TestDirectory + "/keep"));
594 ASSERT_NO_ERROR(fs::remove(TestDirectory + "/keep"));
597 TEST_F(FileSystemTest, TempFileDiscardDiscard) {
598 // We can discard twice.
599 auto TempFileOrError = fs::TempFile::create(TestDirectory + "/test-%%%%");
600 ASSERT_TRUE((bool)TempFileOrError);
601 fs::TempFile File = std::move(*TempFileOrError);
602 ASSERT_FALSE((bool)File.discard());
603 ASSERT_FALSE((bool)File.discard());
604 ASSERT_FALSE(fs::exists(TestDirectory + "/keep"));
607 TEST_F(FileSystemTest, TempFiles) {
608 // Create a temp file.
610 SmallString<64> TempPath;
612 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
614 // Make sure it exists.
615 ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
617 // Create another temp tile.
619 SmallString<64> TempPath2;
620 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD2, TempPath2));
621 ASSERT_TRUE(TempPath2.endswith(".temp"));
622 ASSERT_NE(TempPath.str(), TempPath2.str());
624 fs::file_status A, B;
625 ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
626 ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
627 EXPECT_FALSE(fs::equivalent(A, B));
632 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
633 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
634 ASSERT_EQ(fs::remove(Twine(TempPath2), false),
635 errc::no_such_file_or_directory);
637 std::error_code EC = fs::status(TempPath2.c_str(), B);
638 EXPECT_EQ(EC, errc::no_such_file_or_directory);
639 EXPECT_EQ(B.type(), fs::file_type::file_not_found);
641 // Make sure Temp2 doesn't exist.
642 ASSERT_EQ(fs::access(Twine(TempPath2), sys::fs::AccessMode::Exist),
643 errc::no_such_file_or_directory);
645 SmallString<64> TempPath3;
646 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "", TempPath3));
647 ASSERT_FALSE(TempPath3.endswith("."));
648 FileRemover Cleanup3(TempPath3);
650 // Create a hard link to Temp1.
651 ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2)));
653 ASSERT_NO_ERROR(fs::equivalent(Twine(TempPath), Twine(TempPath2), equal));
655 ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
656 ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
657 EXPECT_TRUE(fs::equivalent(A, B));
660 ::close(FileDescriptor);
661 ASSERT_NO_ERROR(fs::remove(Twine(TempPath)));
663 // Remove the hard link.
664 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
666 // Make sure Temp1 doesn't exist.
667 ASSERT_EQ(fs::access(Twine(TempPath), sys::fs::AccessMode::Exist),
668 errc::no_such_file_or_directory);
671 // Path name > 260 chars should get an error.
672 const char *Path270 =
673 "abcdefghijklmnopqrstuvwxyz9abcdefghijklmnopqrstuvwxyz8"
674 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
675 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
676 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
677 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
678 EXPECT_EQ(fs::createUniqueFile(Path270, FileDescriptor, TempPath),
679 errc::invalid_argument);
680 // Relative path < 247 chars, no problem.
681 const char *Path216 =
682 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
683 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
684 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
685 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
686 ASSERT_NO_ERROR(fs::createTemporaryFile(Path216, "", TempPath));
687 ASSERT_NO_ERROR(fs::remove(Twine(TempPath)));
691 TEST_F(FileSystemTest, CreateDir) {
692 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
693 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
694 ASSERT_EQ(fs::create_directory(Twine(TestDirectory) + "foo", false),
696 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "foo"));
699 // Set a 0000 umask so that we can test our directory permissions.
700 mode_t OldUmask = ::umask(0000);
702 fs::file_status Status;
704 fs::create_directory(Twine(TestDirectory) + "baz500", false,
705 fs::perms::owner_read | fs::perms::owner_exe));
706 ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz500", Status));
707 ASSERT_EQ(Status.permissions() & fs::perms::all_all,
708 fs::perms::owner_read | fs::perms::owner_exe);
709 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "baz777", false,
710 fs::perms::all_all));
711 ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz777", Status));
712 ASSERT_EQ(Status.permissions() & fs::perms::all_all, fs::perms::all_all);
714 // Restore umask to be safe.
719 // Prove that create_directories() can handle a pathname > 248 characters,
720 // which is the documented limit for CreateDirectory().
721 // (248 is MAX_PATH subtracting room for an 8.3 filename.)
722 // Generate a directory path guaranteed to fall into that range.
723 size_t TmpLen = TestDirectory.size();
724 const char *OneDir = "\\123456789";
725 size_t OneDirLen = strlen(OneDir);
726 ASSERT_LT(OneDirLen, 12U);
727 size_t NLevels = ((248 - TmpLen) / OneDirLen) + 1;
728 SmallString<260> LongDir(TestDirectory);
729 for (size_t I = 0; I < NLevels; ++I)
730 LongDir.append(OneDir);
731 ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir)));
732 ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir)));
733 ASSERT_EQ(fs::create_directories(Twine(LongDir), false),
735 // Tidy up, "recursively" removing the directories.
736 StringRef ThisDir(LongDir);
737 for (size_t J = 0; J < NLevels; ++J) {
738 ASSERT_NO_ERROR(fs::remove(ThisDir));
739 ThisDir = path::parent_path(ThisDir);
742 // Also verify that paths with Unix separators are handled correctly.
743 std::string LongPathWithUnixSeparators(TestDirectory.str());
744 // Add at least one subdirectory to TestDirectory, and replace slashes with
747 LongPathWithUnixSeparators.append("/DirNameWith19Charss");
748 } while (LongPathWithUnixSeparators.size() < 260);
749 std::replace(LongPathWithUnixSeparators.begin(),
750 LongPathWithUnixSeparators.end(),
752 ASSERT_NO_ERROR(fs::create_directories(Twine(LongPathWithUnixSeparators)));
754 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) +
755 "/DirNameWith19Charss"));
757 // Similarly for a relative pathname. Need to set the current directory to
758 // TestDirectory so that the one we create ends up in the right place.
759 char PreviousDir[260];
760 size_t PreviousDirLen = ::GetCurrentDirectoryA(260, PreviousDir);
761 ASSERT_GT(PreviousDirLen, 0U);
762 ASSERT_LT(PreviousDirLen, 260U);
763 ASSERT_NE(::SetCurrentDirectoryA(TestDirectory.c_str()), 0);
765 // Generate a relative directory name with absolute length > 248.
766 size_t LongDirLen = 249 - TestDirectory.size();
767 LongDir.assign(LongDirLen, 'a');
768 ASSERT_NO_ERROR(fs::create_directory(Twine(LongDir)));
769 // While we're here, prove that .. and . handling works in these long paths.
770 const char *DotDotDirs = "\\..\\.\\b";
771 LongDir.append(DotDotDirs);
772 ASSERT_NO_ERROR(fs::create_directory("b"));
773 ASSERT_EQ(fs::create_directory(Twine(LongDir), false), errc::file_exists);
775 ASSERT_NO_ERROR(fs::remove("b"));
776 ASSERT_NO_ERROR(fs::remove(
777 Twine(LongDir.substr(0, LongDir.size() - strlen(DotDotDirs)))));
778 ASSERT_NE(::SetCurrentDirectoryA(PreviousDir), 0);
782 TEST_F(FileSystemTest, DirectoryIteration) {
784 for (fs::directory_iterator i(".", ec), e; i != e; i.increment(ec))
787 // Create a known hierarchy to recurse over.
789 fs::create_directories(Twine(TestDirectory) + "/recursive/a0/aa1"));
791 fs::create_directories(Twine(TestDirectory) + "/recursive/a0/ab1"));
792 ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) +
793 "/recursive/dontlookhere/da1"));
795 fs::create_directories(Twine(TestDirectory) + "/recursive/z0/za1"));
797 fs::create_directories(Twine(TestDirectory) + "/recursive/pop/p1"));
798 typedef std::vector<std::string> v_t;
800 for (fs::recursive_directory_iterator i(Twine(TestDirectory)
801 + "/recursive", ec), e; i != e; i.increment(ec)){
803 if (path::filename(i->path()) == "p1") {
805 // FIXME: recursive_directory_iterator should be more robust.
808 if (path::filename(i->path()) == "dontlookhere")
810 visited.push_back(path::filename(i->path()));
812 v_t::const_iterator a0 = find(visited, "a0");
813 v_t::const_iterator aa1 = find(visited, "aa1");
814 v_t::const_iterator ab1 = find(visited, "ab1");
815 v_t::const_iterator dontlookhere = find(visited, "dontlookhere");
816 v_t::const_iterator da1 = find(visited, "da1");
817 v_t::const_iterator z0 = find(visited, "z0");
818 v_t::const_iterator za1 = find(visited, "za1");
819 v_t::const_iterator pop = find(visited, "pop");
820 v_t::const_iterator p1 = find(visited, "p1");
822 // Make sure that each path was visited correctly.
823 ASSERT_NE(a0, visited.end());
824 ASSERT_NE(aa1, visited.end());
825 ASSERT_NE(ab1, visited.end());
826 ASSERT_NE(dontlookhere, visited.end());
827 ASSERT_EQ(da1, visited.end()); // Not visited.
828 ASSERT_NE(z0, visited.end());
829 ASSERT_NE(za1, visited.end());
830 ASSERT_NE(pop, visited.end());
831 ASSERT_EQ(p1, visited.end()); // Not visited.
833 // Make sure that parents were visited before children. No other ordering
834 // guarantees can be made across siblings.
839 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/aa1"));
840 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/ab1"));
841 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0"));
843 fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere/da1"));
844 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere"));
845 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop/p1"));
846 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop"));
847 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0/za1"));
848 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0"));
849 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive"));
851 // Test recursive_directory_iterator level()
853 fs::create_directories(Twine(TestDirectory) + "/reclevel/a/b/c"));
854 fs::recursive_directory_iterator I(Twine(TestDirectory) + "/reclevel", ec), E;
855 for (int l = 0; I != E; I.increment(ec), ++l) {
857 EXPECT_EQ(I.level(), l);
860 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a/b/c"));
861 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a/b"));
862 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a"));
863 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel"));
867 TEST_F(FileSystemTest, BrokenSymlinkDirectoryIteration) {
868 // Create a known hierarchy to recurse over.
869 ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) + "/symlink"));
871 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/a"));
873 fs::create_directories(Twine(TestDirectory) + "/symlink/b/bb"));
875 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/b/ba"));
877 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/b/bc"));
879 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/c"));
881 fs::create_directories(Twine(TestDirectory) + "/symlink/d/dd/ddd"));
882 ASSERT_NO_ERROR(fs::create_link(Twine(TestDirectory) + "/symlink/d/dd",
883 Twine(TestDirectory) + "/symlink/d/da"));
885 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/e"));
887 typedef std::vector<std::string> v_t;
888 v_t VisitedNonBrokenSymlinks;
889 v_t VisitedBrokenSymlinks;
892 // Broken symbol links are expected to throw an error.
893 for (fs::directory_iterator i(Twine(TestDirectory) + "/symlink", ec), e;
894 i != e; i.increment(ec)) {
895 if (ec == std::make_error_code(std::errc::no_such_file_or_directory)) {
896 VisitedBrokenSymlinks.push_back(path::filename(i->path()));
901 VisitedNonBrokenSymlinks.push_back(path::filename(i->path()));
903 llvm::sort(VisitedNonBrokenSymlinks.begin(), VisitedNonBrokenSymlinks.end());
904 llvm::sort(VisitedBrokenSymlinks.begin(), VisitedBrokenSymlinks.end());
905 v_t ExpectedNonBrokenSymlinks = {"b", "d"};
906 ASSERT_EQ(ExpectedNonBrokenSymlinks.size(), VisitedNonBrokenSymlinks.size());
907 ASSERT_TRUE(std::equal(VisitedNonBrokenSymlinks.begin(),
908 VisitedNonBrokenSymlinks.end(),
909 ExpectedNonBrokenSymlinks.begin()));
910 VisitedNonBrokenSymlinks.clear();
912 v_t ExpectedBrokenSymlinks = {"a", "c", "e"};
913 ASSERT_EQ(ExpectedBrokenSymlinks.size(), VisitedBrokenSymlinks.size());
914 ASSERT_TRUE(std::equal(VisitedBrokenSymlinks.begin(),
915 VisitedBrokenSymlinks.end(),
916 ExpectedBrokenSymlinks.begin()));
917 VisitedBrokenSymlinks.clear();
919 // Broken symbol links are expected to throw an error.
920 for (fs::recursive_directory_iterator i(
921 Twine(TestDirectory) + "/symlink", ec), e; i != e; i.increment(ec)) {
922 if (ec == std::make_error_code(std::errc::no_such_file_or_directory)) {
923 VisitedBrokenSymlinks.push_back(path::filename(i->path()));
928 VisitedNonBrokenSymlinks.push_back(path::filename(i->path()));
930 llvm::sort(VisitedNonBrokenSymlinks.begin(), VisitedNonBrokenSymlinks.end());
931 llvm::sort(VisitedBrokenSymlinks.begin(), VisitedBrokenSymlinks.end());
932 ExpectedNonBrokenSymlinks = {"b", "bb", "d", "da", "dd", "ddd", "ddd"};
933 ASSERT_EQ(ExpectedNonBrokenSymlinks.size(), VisitedNonBrokenSymlinks.size());
934 ASSERT_TRUE(std::equal(VisitedNonBrokenSymlinks.begin(),
935 VisitedNonBrokenSymlinks.end(),
936 ExpectedNonBrokenSymlinks.begin()));
937 VisitedNonBrokenSymlinks.clear();
939 ExpectedBrokenSymlinks = {"a", "ba", "bc", "c", "e"};
940 ASSERT_EQ(ExpectedBrokenSymlinks.size(), VisitedBrokenSymlinks.size());
941 ASSERT_TRUE(std::equal(VisitedBrokenSymlinks.begin(),
942 VisitedBrokenSymlinks.end(),
943 ExpectedBrokenSymlinks.begin()));
944 VisitedBrokenSymlinks.clear();
946 for (fs::recursive_directory_iterator i(
947 Twine(TestDirectory) + "/symlink", ec, /*follow_symlinks=*/false), e;
948 i != e; i.increment(ec)) {
949 if (ec == std::make_error_code(std::errc::no_such_file_or_directory)) {
950 VisitedBrokenSymlinks.push_back(path::filename(i->path()));
955 VisitedNonBrokenSymlinks.push_back(path::filename(i->path()));
957 llvm::sort(VisitedNonBrokenSymlinks.begin(), VisitedNonBrokenSymlinks.end());
958 llvm::sort(VisitedBrokenSymlinks.begin(), VisitedBrokenSymlinks.end());
959 ExpectedNonBrokenSymlinks = {"a", "b", "ba", "bb", "bc", "c", "d", "da", "dd",
961 ASSERT_EQ(ExpectedNonBrokenSymlinks.size(), VisitedNonBrokenSymlinks.size());
962 ASSERT_TRUE(std::equal(VisitedNonBrokenSymlinks.begin(),
963 VisitedNonBrokenSymlinks.end(),
964 ExpectedNonBrokenSymlinks.begin()));
965 VisitedNonBrokenSymlinks.clear();
967 ExpectedBrokenSymlinks = {};
968 ASSERT_EQ(ExpectedBrokenSymlinks.size(), VisitedBrokenSymlinks.size());
969 ASSERT_TRUE(std::equal(VisitedBrokenSymlinks.begin(),
970 VisitedBrokenSymlinks.end(),
971 ExpectedBrokenSymlinks.begin()));
972 VisitedBrokenSymlinks.clear();
974 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/symlink"));
978 TEST_F(FileSystemTest, Remove) {
979 SmallString<64> BaseDir;
980 SmallString<64> Paths[4];
982 ASSERT_NO_ERROR(fs::createUniqueDirectory("fs_remove", BaseDir));
984 ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir) + "/foo/bar/baz"));
985 ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir) + "/foo/bar/buzz"));
986 ASSERT_NO_ERROR(fs::createUniqueFile(
987 Twine(BaseDir) + "/foo/bar/baz/%%%%%%.tmp", fds[0], Paths[0]));
988 ASSERT_NO_ERROR(fs::createUniqueFile(
989 Twine(BaseDir) + "/foo/bar/baz/%%%%%%.tmp", fds[1], Paths[1]));
990 ASSERT_NO_ERROR(fs::createUniqueFile(
991 Twine(BaseDir) + "/foo/bar/buzz/%%%%%%.tmp", fds[2], Paths[2]));
992 ASSERT_NO_ERROR(fs::createUniqueFile(
993 Twine(BaseDir) + "/foo/bar/buzz/%%%%%%.tmp", fds[3], Paths[3]));
998 EXPECT_TRUE(fs::exists(Twine(BaseDir) + "/foo/bar/baz"));
999 EXPECT_TRUE(fs::exists(Twine(BaseDir) + "/foo/bar/buzz"));
1000 EXPECT_TRUE(fs::exists(Paths[0]));
1001 EXPECT_TRUE(fs::exists(Paths[1]));
1002 EXPECT_TRUE(fs::exists(Paths[2]));
1003 EXPECT_TRUE(fs::exists(Paths[3]));
1005 ASSERT_NO_ERROR(fs::remove_directories("D:/footest"));
1007 ASSERT_NO_ERROR(fs::remove_directories(BaseDir));
1008 ASSERT_FALSE(fs::exists(BaseDir));
1011 #ifdef LLVM_ON_WIN32
1012 TEST_F(FileSystemTest, CarriageReturn) {
1013 SmallString<128> FilePathname(TestDirectory);
1015 path::append(FilePathname, "test");
1018 raw_fd_ostream File(FilePathname, EC, sys::fs::F_Text);
1019 ASSERT_NO_ERROR(EC);
1023 auto Buf = MemoryBuffer::getFile(FilePathname.str());
1024 EXPECT_TRUE((bool)Buf);
1025 EXPECT_EQ(Buf.get()->getBuffer(), "\r\n");
1029 raw_fd_ostream File(FilePathname, EC, sys::fs::F_None);
1030 ASSERT_NO_ERROR(EC);
1034 auto Buf = MemoryBuffer::getFile(FilePathname.str());
1035 EXPECT_TRUE((bool)Buf);
1036 EXPECT_EQ(Buf.get()->getBuffer(), "\n");
1038 ASSERT_NO_ERROR(fs::remove(Twine(FilePathname)));
1042 TEST_F(FileSystemTest, Resize) {
1044 SmallString<64> TempPath;
1045 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1046 ASSERT_NO_ERROR(fs::resize_file(FD, 123));
1047 fs::file_status Status;
1048 ASSERT_NO_ERROR(fs::status(FD, Status));
1049 ASSERT_EQ(Status.getSize(), 123U);
1051 ASSERT_NO_ERROR(fs::remove(TempPath));
1054 TEST_F(FileSystemTest, MD5) {
1056 SmallString<64> TempPath;
1057 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1058 StringRef Data("abcdefghijklmnopqrstuvwxyz");
1059 ASSERT_EQ(write(FD, Data.data(), Data.size()), static_cast<ssize_t>(Data.size()));
1060 lseek(FD, 0, SEEK_SET);
1061 auto Hash = fs::md5_contents(FD);
1063 ASSERT_NO_ERROR(Hash.getError());
1065 EXPECT_STREQ("c3fcd3d76192e4007dfb496cca67e13b", Hash->digest().c_str());
1068 TEST_F(FileSystemTest, FileMapping) {
1069 // Create a temp file.
1071 SmallString<64> TempPath;
1073 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
1074 unsigned Size = 4096;
1075 ASSERT_NO_ERROR(fs::resize_file(FileDescriptor, Size));
1077 // Map in temp file and add some content
1079 StringRef Val("hello there");
1081 fs::mapped_file_region mfr(FileDescriptor,
1082 fs::mapped_file_region::readwrite, Size, 0, EC);
1083 ASSERT_NO_ERROR(EC);
1084 std::copy(Val.begin(), Val.end(), mfr.data());
1085 // Explicitly add a 0.
1086 mfr.data()[Val.size()] = 0;
1089 ASSERT_EQ(close(FileDescriptor), 0);
1091 // Map it back in read-only
1094 EC = fs::openFileForRead(Twine(TempPath), FD);
1095 ASSERT_NO_ERROR(EC);
1096 fs::mapped_file_region mfr(FD, fs::mapped_file_region::readonly, Size, 0, EC);
1097 ASSERT_NO_ERROR(EC);
1100 EXPECT_EQ(StringRef(mfr.const_data()), Val);
1103 fs::mapped_file_region m(FD, fs::mapped_file_region::readonly, Size, 0, EC);
1104 ASSERT_NO_ERROR(EC);
1105 ASSERT_EQ(close(FD), 0);
1107 ASSERT_NO_ERROR(fs::remove(TempPath));
1110 TEST(Support, NormalizePath) {
1111 using TestTuple = std::tuple<const char *, const char *, const char *>;
1112 std::vector<TestTuple> Tests;
1113 Tests.emplace_back("a", "a", "a");
1114 Tests.emplace_back("a/b", "a\\b", "a/b");
1115 Tests.emplace_back("a\\b", "a\\b", "a/b");
1116 Tests.emplace_back("a\\\\b", "a\\\\b", "a\\\\b");
1117 Tests.emplace_back("\\a", "\\a", "/a");
1118 Tests.emplace_back("a\\", "a\\", "a/");
1120 for (auto &T : Tests) {
1121 SmallString<64> Win(std::get<0>(T));
1122 SmallString<64> Posix(Win);
1123 path::native(Win, path::Style::windows);
1124 path::native(Posix, path::Style::posix);
1125 EXPECT_EQ(std::get<1>(T), Win);
1126 EXPECT_EQ(std::get<2>(T), Posix);
1129 #if defined(LLVM_ON_WIN32)
1130 SmallString<64> PathHome;
1131 path::home_directory(PathHome);
1133 const char *Path7a = "~/aaa";
1134 SmallString<64> Path7(Path7a);
1135 path::native(Path7);
1136 EXPECT_TRUE(Path7.endswith("\\aaa"));
1137 EXPECT_TRUE(Path7.startswith(PathHome));
1138 EXPECT_EQ(Path7.size(), PathHome.size() + strlen(Path7a + 1));
1140 const char *Path8a = "~";
1141 SmallString<64> Path8(Path8a);
1142 path::native(Path8);
1143 EXPECT_EQ(Path8, PathHome);
1145 const char *Path9a = "~aaa";
1146 SmallString<64> Path9(Path9a);
1147 path::native(Path9);
1148 EXPECT_EQ(Path9, "~aaa");
1150 const char *Path10a = "aaa/~/b";
1151 SmallString<64> Path10(Path10a);
1152 path::native(Path10);
1153 EXPECT_EQ(Path10, "aaa\\~\\b");
1157 TEST(Support, RemoveLeadingDotSlash) {
1158 StringRef Path1("././/foolz/wat");
1159 StringRef Path2("./////");
1161 Path1 = path::remove_leading_dotslash(Path1);
1162 EXPECT_EQ(Path1, "foolz/wat");
1163 Path2 = path::remove_leading_dotslash(Path2);
1164 EXPECT_EQ(Path2, "");
1167 static std::string remove_dots(StringRef path, bool remove_dot_dot,
1168 path::Style style) {
1169 SmallString<256> buffer(path);
1170 path::remove_dots(buffer, remove_dot_dot, style);
1171 return buffer.str();
1174 TEST(Support, RemoveDots) {
1175 EXPECT_EQ("foolz\\wat",
1176 remove_dots(".\\.\\\\foolz\\wat", false, path::Style::windows));
1177 EXPECT_EQ("", remove_dots(".\\\\\\\\\\", false, path::Style::windows));
1179 EXPECT_EQ("a\\..\\b\\c",
1180 remove_dots(".\\a\\..\\b\\c", false, path::Style::windows));
1181 EXPECT_EQ("b\\c", remove_dots(".\\a\\..\\b\\c", true, path::Style::windows));
1182 EXPECT_EQ("c", remove_dots(".\\.\\c", true, path::Style::windows));
1183 EXPECT_EQ("..\\a\\c",
1184 remove_dots("..\\a\\b\\..\\c", true, path::Style::windows));
1185 EXPECT_EQ("..\\..\\a\\c",
1186 remove_dots("..\\..\\a\\b\\..\\c", true, path::Style::windows));
1188 SmallString<64> Path1(".\\.\\c");
1189 EXPECT_TRUE(path::remove_dots(Path1, true, path::Style::windows));
1190 EXPECT_EQ("c", Path1);
1192 EXPECT_EQ("foolz/wat",
1193 remove_dots("././/foolz/wat", false, path::Style::posix));
1194 EXPECT_EQ("", remove_dots("./////", false, path::Style::posix));
1196 EXPECT_EQ("a/../b/c", remove_dots("./a/../b/c", false, path::Style::posix));
1197 EXPECT_EQ("b/c", remove_dots("./a/../b/c", true, path::Style::posix));
1198 EXPECT_EQ("c", remove_dots("././c", true, path::Style::posix));
1199 EXPECT_EQ("../a/c", remove_dots("../a/b/../c", true, path::Style::posix));
1200 EXPECT_EQ("../../a/c",
1201 remove_dots("../../a/b/../c", true, path::Style::posix));
1202 EXPECT_EQ("/a/c", remove_dots("/../../a/c", true, path::Style::posix));
1204 remove_dots("/../a/b//../././/c", true, path::Style::posix));
1206 SmallString<64> Path2("././c");
1207 EXPECT_TRUE(path::remove_dots(Path2, true, path::Style::posix));
1208 EXPECT_EQ("c", Path2);
1211 TEST(Support, ReplacePathPrefix) {
1212 SmallString<64> Path1("/foo");
1213 SmallString<64> Path2("/old/foo");
1214 SmallString<64> OldPrefix("/old");
1215 SmallString<64> NewPrefix("/new");
1216 SmallString<64> NewPrefix2("/longernew");
1217 SmallString<64> EmptyPrefix("");
1219 SmallString<64> Path = Path1;
1220 path::replace_path_prefix(Path, OldPrefix, NewPrefix);
1221 EXPECT_EQ(Path, "/foo");
1223 path::replace_path_prefix(Path, OldPrefix, NewPrefix);
1224 EXPECT_EQ(Path, "/new/foo");
1226 path::replace_path_prefix(Path, OldPrefix, NewPrefix2);
1227 EXPECT_EQ(Path, "/longernew/foo");
1229 path::replace_path_prefix(Path, EmptyPrefix, NewPrefix);
1230 EXPECT_EQ(Path, "/new/foo");
1232 path::replace_path_prefix(Path, OldPrefix, EmptyPrefix);
1233 EXPECT_EQ(Path, "/foo");
1236 TEST_F(FileSystemTest, OpenFileForRead) {
1237 // Create a temp file.
1239 SmallString<64> TempPath;
1241 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
1242 FileRemover Cleanup(TempPath);
1244 // Make sure it exists.
1245 ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
1247 // Open the file for read
1248 int FileDescriptor2;
1249 SmallString<64> ResultPath;
1251 fs::openFileForRead(Twine(TempPath), FileDescriptor2, &ResultPath))
1253 // If we succeeded, check that the paths are the same (modulo case):
1254 if (!ResultPath.empty()) {
1255 // The paths returned by createTemporaryFile and getPathFromOpenFD
1256 // should reference the same file on disk.
1257 fs::UniqueID D1, D2;
1258 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), D1));
1259 ASSERT_NO_ERROR(fs::getUniqueID(Twine(ResultPath), D2));
1263 ::close(FileDescriptor);
1266 TEST_F(FileSystemTest, set_current_path) {
1267 SmallString<128> path;
1269 ASSERT_NO_ERROR(fs::current_path(path));
1270 ASSERT_NE(TestDirectory, path);
1272 struct RestorePath {
1273 SmallString<128> path;
1274 RestorePath(const SmallString<128> &path) : path(path) {}
1275 ~RestorePath() { fs::set_current_path(path); }
1276 } restore_path(path);
1278 ASSERT_NO_ERROR(fs::set_current_path(TestDirectory));
1280 ASSERT_NO_ERROR(fs::current_path(path));
1282 fs::UniqueID D1, D2;
1283 ASSERT_NO_ERROR(fs::getUniqueID(TestDirectory, D1));
1284 ASSERT_NO_ERROR(fs::getUniqueID(path, D2));
1285 ASSERT_EQ(D1, D2) << "D1: " << TestDirectory << "\nD2: " << path;
1288 TEST_F(FileSystemTest, permissions) {
1290 SmallString<64> TempPath;
1291 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1292 FileRemover Cleanup(TempPath);
1294 // Make sure it exists.
1295 ASSERT_TRUE(fs::exists(Twine(TempPath)));
1297 auto CheckPermissions = [&](fs::perms Expected) {
1298 ErrorOr<fs::perms> Actual = fs::getPermissions(TempPath);
1299 return Actual && *Actual == Expected;
1302 std::error_code NoError;
1303 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_all), NoError);
1304 EXPECT_TRUE(CheckPermissions(fs::all_all));
1306 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read | fs::all_exe), NoError);
1307 EXPECT_TRUE(CheckPermissions(fs::all_read | fs::all_exe));
1309 #if defined(LLVM_ON_WIN32)
1310 fs::perms ReadOnly = fs::all_read | fs::all_exe;
1311 EXPECT_EQ(fs::setPermissions(TempPath, fs::no_perms), NoError);
1312 EXPECT_TRUE(CheckPermissions(ReadOnly));
1314 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_read), NoError);
1315 EXPECT_TRUE(CheckPermissions(ReadOnly));
1317 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_write), NoError);
1318 EXPECT_TRUE(CheckPermissions(fs::all_all));
1320 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_exe), NoError);
1321 EXPECT_TRUE(CheckPermissions(ReadOnly));
1323 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_all), NoError);
1324 EXPECT_TRUE(CheckPermissions(fs::all_all));
1326 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_read), NoError);
1327 EXPECT_TRUE(CheckPermissions(ReadOnly));
1329 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_write), NoError);
1330 EXPECT_TRUE(CheckPermissions(fs::all_all));
1332 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_exe), NoError);
1333 EXPECT_TRUE(CheckPermissions(ReadOnly));
1335 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_all), NoError);
1336 EXPECT_TRUE(CheckPermissions(fs::all_all));
1338 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_read), NoError);
1339 EXPECT_TRUE(CheckPermissions(ReadOnly));
1341 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_write), NoError);
1342 EXPECT_TRUE(CheckPermissions(fs::all_all));
1344 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_exe), NoError);
1345 EXPECT_TRUE(CheckPermissions(ReadOnly));
1347 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_all), NoError);
1348 EXPECT_TRUE(CheckPermissions(fs::all_all));
1350 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read), NoError);
1351 EXPECT_TRUE(CheckPermissions(ReadOnly));
1353 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_write), NoError);
1354 EXPECT_TRUE(CheckPermissions(fs::all_all));
1356 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_exe), NoError);
1357 EXPECT_TRUE(CheckPermissions(ReadOnly));
1359 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe), NoError);
1360 EXPECT_TRUE(CheckPermissions(ReadOnly));
1362 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_gid_on_exe), NoError);
1363 EXPECT_TRUE(CheckPermissions(ReadOnly));
1365 EXPECT_EQ(fs::setPermissions(TempPath, fs::sticky_bit), NoError);
1366 EXPECT_TRUE(CheckPermissions(ReadOnly));
1368 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe |
1369 fs::set_gid_on_exe |
1372 EXPECT_TRUE(CheckPermissions(ReadOnly));
1374 EXPECT_EQ(fs::setPermissions(TempPath, ReadOnly | fs::set_uid_on_exe |
1375 fs::set_gid_on_exe |
1378 EXPECT_TRUE(CheckPermissions(ReadOnly));
1380 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms), NoError);
1381 EXPECT_TRUE(CheckPermissions(fs::all_all));
1383 EXPECT_EQ(fs::setPermissions(TempPath, fs::no_perms), NoError);
1384 EXPECT_TRUE(CheckPermissions(fs::no_perms));
1386 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_read), NoError);
1387 EXPECT_TRUE(CheckPermissions(fs::owner_read));
1389 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_write), NoError);
1390 EXPECT_TRUE(CheckPermissions(fs::owner_write));
1392 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_exe), NoError);
1393 EXPECT_TRUE(CheckPermissions(fs::owner_exe));
1395 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_all), NoError);
1396 EXPECT_TRUE(CheckPermissions(fs::owner_all));
1398 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_read), NoError);
1399 EXPECT_TRUE(CheckPermissions(fs::group_read));
1401 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_write), NoError);
1402 EXPECT_TRUE(CheckPermissions(fs::group_write));
1404 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_exe), NoError);
1405 EXPECT_TRUE(CheckPermissions(fs::group_exe));
1407 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_all), NoError);
1408 EXPECT_TRUE(CheckPermissions(fs::group_all));
1410 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_read), NoError);
1411 EXPECT_TRUE(CheckPermissions(fs::others_read));
1413 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_write), NoError);
1414 EXPECT_TRUE(CheckPermissions(fs::others_write));
1416 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_exe), NoError);
1417 EXPECT_TRUE(CheckPermissions(fs::others_exe));
1419 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_all), NoError);
1420 EXPECT_TRUE(CheckPermissions(fs::others_all));
1422 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read), NoError);
1423 EXPECT_TRUE(CheckPermissions(fs::all_read));
1425 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_write), NoError);
1426 EXPECT_TRUE(CheckPermissions(fs::all_write));
1428 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_exe), NoError);
1429 EXPECT_TRUE(CheckPermissions(fs::all_exe));
1431 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe), NoError);
1432 EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe));
1434 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_gid_on_exe), NoError);
1435 EXPECT_TRUE(CheckPermissions(fs::set_gid_on_exe));
1437 // Modern BSDs require root to set the sticky bit on files.
1438 #if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__)
1439 EXPECT_EQ(fs::setPermissions(TempPath, fs::sticky_bit), NoError);
1440 EXPECT_TRUE(CheckPermissions(fs::sticky_bit));
1442 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe |
1443 fs::set_gid_on_exe |
1446 EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe | fs::set_gid_on_exe |
1449 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read | fs::set_uid_on_exe |
1450 fs::set_gid_on_exe |
1453 EXPECT_TRUE(CheckPermissions(fs::all_read | fs::set_uid_on_exe |
1454 fs::set_gid_on_exe | fs::sticky_bit));
1456 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms), NoError);
1457 EXPECT_TRUE(CheckPermissions(fs::all_perms));
1458 #endif // !FreeBSD && !NetBSD && !OpenBSD
1460 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms & ~fs::sticky_bit),
1462 EXPECT_TRUE(CheckPermissions(fs::all_perms & ~fs::sticky_bit));
1466 } // anonymous namespace