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/SmallVector.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/ADT/Triple.h"
14 #include "llvm/Support/ConvertUTF.h"
15 #include "llvm/Support/Errc.h"
16 #include "llvm/Support/ErrorHandling.h"
17 #include "llvm/Support/FileSystem.h"
18 #include "llvm/Support/FileUtilities.h"
19 #include "llvm/Support/Host.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "gtest/gtest.h"
25 #include "llvm/ADT/ArrayRef.h"
36 using namespace llvm::sys;
38 #define ASSERT_NO_ERROR(x) \
39 if (std::error_code ASSERT_NO_ERROR_ec = x) { \
40 SmallString<128> MessageStorage; \
41 raw_svector_ostream Message(MessageStorage); \
42 Message << #x ": did not return errc::success.\n" \
43 << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n" \
44 << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \
45 GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \
51 TEST(is_separator, Works) {
52 EXPECT_TRUE(path::is_separator('/'));
53 EXPECT_FALSE(path::is_separator('\0'));
54 EXPECT_FALSE(path::is_separator('-'));
55 EXPECT_FALSE(path::is_separator(' '));
57 EXPECT_TRUE(path::is_separator('\\', path::Style::windows));
58 EXPECT_FALSE(path::is_separator('\\', path::Style::posix));
61 EXPECT_TRUE(path::is_separator('\\'));
63 EXPECT_FALSE(path::is_separator('\\'));
68 SmallVector<StringRef, 40> paths;
71 paths.push_back("..");
72 paths.push_back("foo");
74 paths.push_back("/foo");
75 paths.push_back("foo/");
76 paths.push_back("/foo/");
77 paths.push_back("foo/bar");
78 paths.push_back("/foo/bar");
79 paths.push_back("//net");
80 paths.push_back("//net/foo");
81 paths.push_back("///foo///");
82 paths.push_back("///foo///bar");
83 paths.push_back("/.");
84 paths.push_back("./");
85 paths.push_back("/..");
86 paths.push_back("../");
87 paths.push_back("foo/.");
88 paths.push_back("foo/..");
89 paths.push_back("foo/./");
90 paths.push_back("foo/./bar");
91 paths.push_back("foo/..");
92 paths.push_back("foo/../");
93 paths.push_back("foo/../bar");
94 paths.push_back("c:");
95 paths.push_back("c:/");
96 paths.push_back("c:foo");
97 paths.push_back("c:/foo");
98 paths.push_back("c:foo/");
99 paths.push_back("c:/foo/");
100 paths.push_back("c:/foo/bar");
101 paths.push_back("prn:");
102 paths.push_back("c:\\");
103 paths.push_back("c:foo");
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\\bar");
110 SmallVector<StringRef, 5> ComponentStack;
111 for (SmallVector<StringRef, 40>::const_iterator i = paths.begin(),
115 for (sys::path::const_iterator ci = sys::path::begin(*i),
116 ce = sys::path::end(*i);
119 ASSERT_FALSE(ci->empty());
120 ComponentStack.push_back(*ci);
123 for (sys::path::reverse_iterator ci = sys::path::rbegin(*i),
124 ce = sys::path::rend(*i);
127 ASSERT_TRUE(*ci == ComponentStack.back());
128 ComponentStack.pop_back();
130 ASSERT_TRUE(ComponentStack.empty());
132 // Crash test most of the API - since we're iterating over all of our paths
133 // here there isn't really anything reasonable to assert on in the results.
134 (void)path::has_root_path(*i);
135 (void)path::root_path(*i);
136 (void)path::has_root_name(*i);
137 (void)path::root_name(*i);
138 (void)path::has_root_directory(*i);
139 (void)path::root_directory(*i);
140 (void)path::has_parent_path(*i);
141 (void)path::parent_path(*i);
142 (void)path::has_filename(*i);
143 (void)path::filename(*i);
144 (void)path::has_stem(*i);
145 (void)path::stem(*i);
146 (void)path::has_extension(*i);
147 (void)path::extension(*i);
148 (void)path::is_absolute(*i);
149 (void)path::is_relative(*i);
151 SmallString<128> temp_store;
153 ASSERT_NO_ERROR(fs::make_absolute(temp_store));
155 path::remove_filename(temp_store);
158 path::replace_extension(temp_store, "ext");
159 StringRef filename(temp_store.begin(), temp_store.size()), stem, ext;
160 stem = path::stem(filename);
161 ext = path::extension(filename);
162 EXPECT_EQ(*sys::path::rbegin(filename), (stem + ext).str());
164 path::native(*i, temp_store);
167 SmallString<32> Relative("foo.cpp");
168 ASSERT_NO_ERROR(sys::fs::make_absolute("/root", Relative));
169 Relative[5] = '/'; // Fix up windows paths.
170 ASSERT_EQ("/root/foo.cpp", Relative);
173 TEST(Support, RelativePathIterator) {
174 SmallString<64> Path(StringRef("c/d/e/foo.txt"));
175 typedef SmallVector<StringRef, 4> PathComponents;
176 PathComponents ExpectedPathComponents;
177 PathComponents ActualPathComponents;
179 StringRef(Path).split(ExpectedPathComponents, '/');
181 for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
183 ActualPathComponents.push_back(*I);
186 ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
188 for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
189 EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
193 TEST(Support, RelativePathDotIterator) {
194 SmallString<64> Path(StringRef(".c/.d/../."));
195 typedef SmallVector<StringRef, 4> PathComponents;
196 PathComponents ExpectedPathComponents;
197 PathComponents ActualPathComponents;
199 StringRef(Path).split(ExpectedPathComponents, '/');
201 for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
203 ActualPathComponents.push_back(*I);
206 ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
208 for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
209 EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
213 TEST(Support, AbsolutePathIterator) {
214 SmallString<64> Path(StringRef("/c/d/e/foo.txt"));
215 typedef SmallVector<StringRef, 4> PathComponents;
216 PathComponents ExpectedPathComponents;
217 PathComponents ActualPathComponents;
219 StringRef(Path).split(ExpectedPathComponents, '/');
221 // The root path will also be a component when iterating
222 ExpectedPathComponents[0] = "/";
224 for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
226 ActualPathComponents.push_back(*I);
229 ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
231 for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
232 EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
236 TEST(Support, AbsolutePathDotIterator) {
237 SmallString<64> Path(StringRef("/.c/.d/../."));
238 typedef SmallVector<StringRef, 4> PathComponents;
239 PathComponents ExpectedPathComponents;
240 PathComponents ActualPathComponents;
242 StringRef(Path).split(ExpectedPathComponents, '/');
244 // The root path will also be a component when iterating
245 ExpectedPathComponents[0] = "/";
247 for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
249 ActualPathComponents.push_back(*I);
252 ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
254 for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
255 EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
259 TEST(Support, AbsolutePathIteratorWin32) {
260 SmallString<64> Path(StringRef("c:\\c\\e\\foo.txt"));
261 typedef SmallVector<StringRef, 4> PathComponents;
262 PathComponents ExpectedPathComponents;
263 PathComponents ActualPathComponents;
265 StringRef(Path).split(ExpectedPathComponents, "\\");
267 // The root path (which comes after the drive name) will also be a component
269 ExpectedPathComponents.insert(ExpectedPathComponents.begin()+1, "\\");
271 for (path::const_iterator I = path::begin(Path, path::Style::windows),
274 ActualPathComponents.push_back(*I);
277 ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
279 for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
280 EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
284 TEST(Support, AbsolutePathIteratorEnd) {
285 // Trailing slashes are converted to '.' unless they are part of the root path.
286 SmallVector<std::pair<StringRef, path::Style>, 4> Paths;
287 Paths.emplace_back("/foo/", path::Style::native);
288 Paths.emplace_back("/foo//", path::Style::native);
289 Paths.emplace_back("//net//", path::Style::native);
290 Paths.emplace_back("c:\\\\", path::Style::windows);
292 for (auto &Path : Paths) {
293 StringRef LastComponent = *path::rbegin(Path.first, Path.second);
294 EXPECT_EQ(".", LastComponent);
297 SmallVector<std::pair<StringRef, path::Style>, 3> RootPaths;
298 RootPaths.emplace_back("/", path::Style::native);
299 RootPaths.emplace_back("//net/", path::Style::native);
300 RootPaths.emplace_back("c:\\", path::Style::windows);
302 for (auto &Path : RootPaths) {
303 StringRef LastComponent = *path::rbegin(Path.first, Path.second);
304 EXPECT_EQ(1u, LastComponent.size());
305 EXPECT_TRUE(path::is_separator(LastComponent[0], Path.second));
309 TEST(Support, HomeDirectory) {
310 std::string expected;
312 if (wchar_t const *path = ::_wgetenv(L"USERPROFILE")) {
313 auto pathLen = ::wcslen(path);
314 ArrayRef<char> ref{reinterpret_cast<char const *>(path),
315 pathLen * sizeof(wchar_t)};
316 convertUTF16ToUTF8String(ref, expected);
319 if (char const *path = ::getenv("HOME"))
322 // Do not try to test it if we don't know what to expect.
323 // On Windows we use something better than env vars.
324 if (!expected.empty()) {
325 SmallString<128> HomeDir;
326 auto status = path::home_directory(HomeDir);
328 EXPECT_EQ(expected, HomeDir);
333 TEST(Support, HomeDirectoryWithNoEnv) {
334 std::string OriginalStorage;
335 char const *OriginalEnv = ::getenv("HOME");
337 // We're going to unset it, so make a copy and save a pointer to the copy
338 // so that we can reset it at the end of the test.
339 OriginalStorage = OriginalEnv;
340 OriginalEnv = OriginalStorage.c_str();
343 // Don't run the test if we have nothing to compare against.
344 struct passwd *pw = getpwuid(getuid());
345 if (!pw || !pw->pw_dir) return;
348 EXPECT_EQ(nullptr, ::getenv("HOME"));
349 std::string PwDir = pw->pw_dir;
351 SmallString<128> HomeDir;
352 auto status = path::home_directory(HomeDir);
354 EXPECT_EQ(PwDir, HomeDir);
356 // Now put the environment back to its original state (meaning that if it was
357 // unset before, we don't reset it).
358 if (OriginalEnv) ::setenv("HOME", OriginalEnv, 1);
362 TEST(Support, UserCacheDirectory) {
363 SmallString<13> CacheDir;
364 SmallString<20> CacheDir2;
365 auto Status = path::user_cache_directory(CacheDir, "");
366 EXPECT_TRUE(Status ^ CacheDir.empty());
369 EXPECT_TRUE(path::user_cache_directory(CacheDir2, "")); // should succeed
370 EXPECT_EQ(CacheDir, CacheDir2); // and return same paths
372 EXPECT_TRUE(path::user_cache_directory(CacheDir, "A", "B", "file.c"));
373 auto It = path::rbegin(CacheDir);
374 EXPECT_EQ("file.c", *It);
375 EXPECT_EQ("B", *++It);
376 EXPECT_EQ("A", *++It);
377 auto ParentDir = *++It;
379 // Test Unicode: "<user_cache_dir>/(pi)r^2/aleth.0"
380 EXPECT_TRUE(path::user_cache_directory(CacheDir2, "\xCF\x80r\xC2\xB2",
382 auto It2 = path::rbegin(CacheDir2);
383 EXPECT_EQ("\xE2\x84\xB5.0", *It2);
384 EXPECT_EQ("\xCF\x80r\xC2\xB2", *++It2);
385 auto ParentDir2 = *++It2;
387 EXPECT_EQ(ParentDir, ParentDir2);
391 TEST(Support, TempDirectory) {
392 SmallString<32> TempDir;
393 path::system_temp_directory(false, TempDir);
394 EXPECT_TRUE(!TempDir.empty());
396 path::system_temp_directory(true, TempDir);
397 EXPECT_TRUE(!TempDir.empty());
401 static std::string path2regex(std::string Path) {
403 while ((Pos = Path.find('\\', Pos)) != std::string::npos) {
404 Path.replace(Pos, 1, "\\\\");
410 /// Helper for running temp dir test in separated process. See below.
411 #define EXPECT_TEMP_DIR(prepare, expected) \
415 SmallString<300> TempDir; \
416 path::system_temp_directory(true, TempDir); \
417 raw_os_ostream(std::cerr) << TempDir; \
420 ::testing::ExitedWithCode(0), path2regex(expected))
422 TEST(SupportDeathTest, TempDirectoryOnWindows) {
423 // In this test we want to check how system_temp_directory responds to
424 // different values of specific env vars. To prevent corrupting env vars of
425 // the current process all checks are done in separated processes.
426 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"C:\\OtherFolder"), "C:\\OtherFolder");
427 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"C:/Unix/Path/Seperators"),
428 "C:\\Unix\\Path\\Seperators");
429 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"Local Path"), ".+\\Local Path$");
430 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"F:\\TrailingSep\\"), "F:\\TrailingSep");
432 _wputenv_s(L"TMP", L"C:\\2\x03C0r-\x00B5\x00B3\\\x2135\x2080"),
433 "C:\\2\xCF\x80r-\xC2\xB5\xC2\xB3\\\xE2\x84\xB5\xE2\x82\x80");
435 // Test $TMP empty, $TEMP set.
438 _wputenv_s(L"TMP", L"");
439 _wputenv_s(L"TEMP", L"C:\\Valid\\Path");
443 // All related env vars empty
446 _wputenv_s(L"TMP", L"");
447 _wputenv_s(L"TEMP", L"");
448 _wputenv_s(L"USERPROFILE", L"");
452 // Test evn var / path with 260 chars.
453 SmallString<270> Expected{"C:\\Temp\\AB\\123456789"};
454 while (Expected.size() < 260)
455 Expected.append("\\DirNameWith19Charss");
456 ASSERT_EQ(260U, Expected.size());
457 EXPECT_TEMP_DIR(_putenv_s("TMP", Expected.c_str()), Expected.c_str());
461 class FileSystemTest : public testing::Test {
463 /// Unique temporary directory in which all created filesystem entities must
464 /// be placed. It is removed at the end of each test (must be empty).
465 SmallString<128> TestDirectory;
467 void SetUp() override {
469 fs::createUniqueDirectory("file-system-test", TestDirectory));
470 // We don't care about this specific file.
471 errs() << "Test Directory: " << TestDirectory << '\n';
475 void TearDown() override { ASSERT_NO_ERROR(fs::remove(TestDirectory.str())); }
478 TEST_F(FileSystemTest, Unique) {
479 // Create a temp file.
481 SmallString<64> TempPath;
483 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
485 // The same file should return an identical unique id.
487 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F1));
488 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F2));
491 // Different files should return different unique ids.
493 SmallString<64> TempPath2;
495 fs::createTemporaryFile("prefix", "temp", FileDescriptor2, TempPath2));
498 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D));
500 ::close(FileDescriptor2);
502 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
504 // Two paths representing the same file on disk should still provide the
505 // same unique id. We can test this by making a hard link.
506 ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2)));
508 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D2));
511 ::close(FileDescriptor);
513 SmallString<128> Dir1;
515 fs::createUniqueDirectory("dir1", Dir1));
516 ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F1));
517 ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F2));
520 SmallString<128> Dir2;
522 fs::createUniqueDirectory("dir2", Dir2));
523 ASSERT_NO_ERROR(fs::getUniqueID(Dir2.c_str(), F2));
525 ASSERT_NO_ERROR(fs::remove(Dir1));
526 ASSERT_NO_ERROR(fs::remove(Dir2));
527 ASSERT_NO_ERROR(fs::remove(TempPath2));
528 ASSERT_NO_ERROR(fs::remove(TempPath));
531 TEST_F(FileSystemTest, RealPath) {
533 fs::create_directories(Twine(TestDirectory) + "/test1/test2/test3"));
534 ASSERT_TRUE(fs::exists(Twine(TestDirectory) + "/test1/test2/test3"));
536 SmallString<64> RealBase;
537 SmallString<64> Expected;
538 SmallString<64> Actual;
540 // TestDirectory itself might be under a symlink or have been specified with
541 // a different case than the existing temp directory. In such cases real_path
542 // on the concatenated path will differ in the TestDirectory portion from
543 // how we specified it. Make sure to compare against the real_path of the
544 // TestDirectory, and not just the value of TestDirectory.
545 ASSERT_NO_ERROR(fs::real_path(TestDirectory, RealBase));
546 path::native(Twine(RealBase) + "/test1/test2", Expected);
548 ASSERT_NO_ERROR(fs::real_path(
549 Twine(TestDirectory) + "/././test1/../test1/test2/./test3/..", Actual));
551 EXPECT_EQ(Expected, Actual);
553 SmallString<64> HomeDir;
554 bool Result = llvm::sys::path::home_directory(HomeDir);
556 ASSERT_NO_ERROR(fs::real_path(HomeDir, Expected));
557 ASSERT_NO_ERROR(fs::real_path("~", Actual, true));
558 EXPECT_EQ(Expected, Actual);
559 ASSERT_NO_ERROR(fs::real_path("~/", Actual, true));
560 EXPECT_EQ(Expected, Actual);
563 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/test1"));
566 TEST_F(FileSystemTest, TempFiles) {
567 // Create a temp file.
569 SmallString<64> TempPath;
571 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
573 // Make sure it exists.
574 ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
576 // Create another temp tile.
578 SmallString<64> TempPath2;
579 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD2, TempPath2));
580 ASSERT_TRUE(TempPath2.endswith(".temp"));
581 ASSERT_NE(TempPath.str(), TempPath2.str());
583 fs::file_status A, B;
584 ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
585 ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
586 EXPECT_FALSE(fs::equivalent(A, B));
591 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
592 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
593 ASSERT_EQ(fs::remove(Twine(TempPath2), false),
594 errc::no_such_file_or_directory);
596 std::error_code EC = fs::status(TempPath2.c_str(), B);
597 EXPECT_EQ(EC, errc::no_such_file_or_directory);
598 EXPECT_EQ(B.type(), fs::file_type::file_not_found);
600 // Make sure Temp2 doesn't exist.
601 ASSERT_EQ(fs::access(Twine(TempPath2), sys::fs::AccessMode::Exist),
602 errc::no_such_file_or_directory);
604 SmallString<64> TempPath3;
605 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "", TempPath3));
606 ASSERT_FALSE(TempPath3.endswith("."));
607 FileRemover Cleanup3(TempPath3);
609 // Create a hard link to Temp1.
610 ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2)));
612 ASSERT_NO_ERROR(fs::equivalent(Twine(TempPath), Twine(TempPath2), equal));
614 ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
615 ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
616 EXPECT_TRUE(fs::equivalent(A, B));
619 ::close(FileDescriptor);
620 ASSERT_NO_ERROR(fs::remove(Twine(TempPath)));
622 // Remove the hard link.
623 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
625 // Make sure Temp1 doesn't exist.
626 ASSERT_EQ(fs::access(Twine(TempPath), sys::fs::AccessMode::Exist),
627 errc::no_such_file_or_directory);
630 // Path name > 260 chars should get an error.
631 const char *Path270 =
632 "abcdefghijklmnopqrstuvwxyz9abcdefghijklmnopqrstuvwxyz8"
633 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
634 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
635 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
636 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
637 EXPECT_EQ(fs::createUniqueFile(Path270, FileDescriptor, TempPath),
638 errc::invalid_argument);
639 // Relative path < 247 chars, no problem.
640 const char *Path216 =
641 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
642 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
643 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
644 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
645 ASSERT_NO_ERROR(fs::createTemporaryFile(Path216, "", TempPath));
646 ASSERT_NO_ERROR(fs::remove(Twine(TempPath)));
650 TEST_F(FileSystemTest, CreateDir) {
651 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
652 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
653 ASSERT_EQ(fs::create_directory(Twine(TestDirectory) + "foo", false),
655 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "foo"));
658 // Set a 0000 umask so that we can test our directory permissions.
659 mode_t OldUmask = ::umask(0000);
661 fs::file_status Status;
663 fs::create_directory(Twine(TestDirectory) + "baz500", false,
664 fs::perms::owner_read | fs::perms::owner_exe));
665 ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz500", Status));
666 ASSERT_EQ(Status.permissions() & fs::perms::all_all,
667 fs::perms::owner_read | fs::perms::owner_exe);
668 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "baz777", false,
669 fs::perms::all_all));
670 ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz777", Status));
671 ASSERT_EQ(Status.permissions() & fs::perms::all_all, fs::perms::all_all);
673 // Restore umask to be safe.
678 // Prove that create_directories() can handle a pathname > 248 characters,
679 // which is the documented limit for CreateDirectory().
680 // (248 is MAX_PATH subtracting room for an 8.3 filename.)
681 // Generate a directory path guaranteed to fall into that range.
682 size_t TmpLen = TestDirectory.size();
683 const char *OneDir = "\\123456789";
684 size_t OneDirLen = strlen(OneDir);
685 ASSERT_LT(OneDirLen, 12U);
686 size_t NLevels = ((248 - TmpLen) / OneDirLen) + 1;
687 SmallString<260> LongDir(TestDirectory);
688 for (size_t I = 0; I < NLevels; ++I)
689 LongDir.append(OneDir);
690 ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir)));
691 ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir)));
692 ASSERT_EQ(fs::create_directories(Twine(LongDir), false),
694 // Tidy up, "recursively" removing the directories.
695 StringRef ThisDir(LongDir);
696 for (size_t J = 0; J < NLevels; ++J) {
697 ASSERT_NO_ERROR(fs::remove(ThisDir));
698 ThisDir = path::parent_path(ThisDir);
701 // Similarly for a relative pathname. Need to set the current directory to
702 // TestDirectory so that the one we create ends up in the right place.
703 char PreviousDir[260];
704 size_t PreviousDirLen = ::GetCurrentDirectoryA(260, PreviousDir);
705 ASSERT_GT(PreviousDirLen, 0U);
706 ASSERT_LT(PreviousDirLen, 260U);
707 ASSERT_NE(::SetCurrentDirectoryA(TestDirectory.c_str()), 0);
709 // Generate a relative directory name with absolute length > 248.
710 size_t LongDirLen = 249 - TestDirectory.size();
711 LongDir.assign(LongDirLen, 'a');
712 ASSERT_NO_ERROR(fs::create_directory(Twine(LongDir)));
713 // While we're here, prove that .. and . handling works in these long paths.
714 const char *DotDotDirs = "\\..\\.\\b";
715 LongDir.append(DotDotDirs);
716 ASSERT_NO_ERROR(fs::create_directory("b"));
717 ASSERT_EQ(fs::create_directory(Twine(LongDir), false), errc::file_exists);
719 ASSERT_NO_ERROR(fs::remove("b"));
720 ASSERT_NO_ERROR(fs::remove(
721 Twine(LongDir.substr(0, LongDir.size() - strlen(DotDotDirs)))));
722 ASSERT_NE(::SetCurrentDirectoryA(PreviousDir), 0);
726 TEST_F(FileSystemTest, DirectoryIteration) {
728 for (fs::directory_iterator i(".", ec), e; i != e; i.increment(ec))
731 // Create a known hierarchy to recurse over.
733 fs::create_directories(Twine(TestDirectory) + "/recursive/a0/aa1"));
735 fs::create_directories(Twine(TestDirectory) + "/recursive/a0/ab1"));
736 ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) +
737 "/recursive/dontlookhere/da1"));
739 fs::create_directories(Twine(TestDirectory) + "/recursive/z0/za1"));
741 fs::create_directories(Twine(TestDirectory) + "/recursive/pop/p1"));
742 typedef std::vector<std::string> v_t;
744 for (fs::recursive_directory_iterator i(Twine(TestDirectory)
745 + "/recursive", ec), e; i != e; i.increment(ec)){
747 if (path::filename(i->path()) == "p1") {
749 // FIXME: recursive_directory_iterator should be more robust.
752 if (path::filename(i->path()) == "dontlookhere")
754 visited.push_back(path::filename(i->path()));
756 v_t::const_iterator a0 = find(visited, "a0");
757 v_t::const_iterator aa1 = find(visited, "aa1");
758 v_t::const_iterator ab1 = find(visited, "ab1");
759 v_t::const_iterator dontlookhere = find(visited, "dontlookhere");
760 v_t::const_iterator da1 = find(visited, "da1");
761 v_t::const_iterator z0 = find(visited, "z0");
762 v_t::const_iterator za1 = find(visited, "za1");
763 v_t::const_iterator pop = find(visited, "pop");
764 v_t::const_iterator p1 = find(visited, "p1");
766 // Make sure that each path was visited correctly.
767 ASSERT_NE(a0, visited.end());
768 ASSERT_NE(aa1, visited.end());
769 ASSERT_NE(ab1, visited.end());
770 ASSERT_NE(dontlookhere, visited.end());
771 ASSERT_EQ(da1, visited.end()); // Not visited.
772 ASSERT_NE(z0, visited.end());
773 ASSERT_NE(za1, visited.end());
774 ASSERT_NE(pop, visited.end());
775 ASSERT_EQ(p1, visited.end()); // Not visited.
777 // Make sure that parents were visited before children. No other ordering
778 // guarantees can be made across siblings.
783 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/aa1"));
784 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/ab1"));
785 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0"));
787 fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere/da1"));
788 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere"));
789 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop/p1"));
790 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop"));
791 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0/za1"));
792 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0"));
793 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive"));
795 // Test recursive_directory_iterator level()
797 fs::create_directories(Twine(TestDirectory) + "/reclevel/a/b/c"));
798 fs::recursive_directory_iterator I(Twine(TestDirectory) + "/reclevel", ec), E;
799 for (int l = 0; I != E; I.increment(ec), ++l) {
801 EXPECT_EQ(I.level(), l);
804 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a/b/c"));
805 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a/b"));
806 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a"));
807 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel"));
811 TEST_F(FileSystemTest, BrokenSymlinkDirectoryIteration) {
812 // Create a known hierarchy to recurse over.
813 ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) + "/symlink"));
815 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/a"));
817 fs::create_directories(Twine(TestDirectory) + "/symlink/b/bb"));
819 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/b/ba"));
821 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/b/bc"));
823 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/c"));
825 fs::create_directories(Twine(TestDirectory) + "/symlink/d/dd/ddd"));
826 ASSERT_NO_ERROR(fs::create_link(Twine(TestDirectory) + "/symlink/d/dd",
827 Twine(TestDirectory) + "/symlink/d/da"));
829 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/e"));
831 typedef std::vector<std::string> v_t;
834 // The directory iterator doesn't stat the file, so we should be able to
835 // iterate over the whole directory.
837 for (fs::directory_iterator i(Twine(TestDirectory) + "/symlink", ec), e;
838 i != e; i.increment(ec)) {
840 visited.push_back(path::filename(i->path()));
842 std::sort(visited.begin(), visited.end());
843 v_t expected = {"a", "b", "c", "d", "e"};
844 ASSERT_TRUE(visited.size() == expected.size());
845 ASSERT_TRUE(std::equal(visited.begin(), visited.end(), expected.begin()));
848 // The recursive directory iterator has to stat the file, so we need to skip
849 // the broken symlinks.
850 for (fs::recursive_directory_iterator
851 i(Twine(TestDirectory) + "/symlink", ec),
853 i != e; i.increment(ec)) {
856 fs::file_status status;
857 if (i->status(status) ==
858 std::make_error_code(std::errc::no_such_file_or_directory)) {
863 visited.push_back(path::filename(i->path()));
865 std::sort(visited.begin(), visited.end());
866 expected = {"b", "bb", "d", "da", "dd", "ddd", "ddd"};
867 ASSERT_TRUE(visited.size() == expected.size());
868 ASSERT_TRUE(std::equal(visited.begin(), visited.end(), expected.begin()));
871 // This recursive directory iterator doesn't follow symlinks, so we don't need
873 for (fs::recursive_directory_iterator
874 i(Twine(TestDirectory) + "/symlink", ec, /*follow_symlinks=*/false),
876 i != e; i.increment(ec)) {
878 visited.push_back(path::filename(i->path()));
880 std::sort(visited.begin(), visited.end());
881 expected = {"a", "b", "ba", "bb", "bc", "c", "d", "da", "dd", "ddd", "e"};
882 ASSERT_TRUE(visited.size() == expected.size());
883 ASSERT_TRUE(std::equal(visited.begin(), visited.end(), expected.begin()));
885 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/symlink"));
889 TEST_F(FileSystemTest, Remove) {
890 SmallString<64> BaseDir;
891 SmallString<64> Paths[4];
893 ASSERT_NO_ERROR(fs::createUniqueDirectory("fs_remove", BaseDir));
895 ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir) + "/foo/bar/baz"));
896 ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir) + "/foo/bar/buzz"));
897 ASSERT_NO_ERROR(fs::createUniqueFile(
898 Twine(BaseDir) + "/foo/bar/baz/%%%%%%.tmp", fds[0], Paths[0]));
899 ASSERT_NO_ERROR(fs::createUniqueFile(
900 Twine(BaseDir) + "/foo/bar/baz/%%%%%%.tmp", fds[1], Paths[1]));
901 ASSERT_NO_ERROR(fs::createUniqueFile(
902 Twine(BaseDir) + "/foo/bar/buzz/%%%%%%.tmp", fds[2], Paths[2]));
903 ASSERT_NO_ERROR(fs::createUniqueFile(
904 Twine(BaseDir) + "/foo/bar/buzz/%%%%%%.tmp", fds[3], Paths[3]));
909 EXPECT_TRUE(fs::exists(Twine(BaseDir) + "/foo/bar/baz"));
910 EXPECT_TRUE(fs::exists(Twine(BaseDir) + "/foo/bar/buzz"));
911 EXPECT_TRUE(fs::exists(Paths[0]));
912 EXPECT_TRUE(fs::exists(Paths[1]));
913 EXPECT_TRUE(fs::exists(Paths[2]));
914 EXPECT_TRUE(fs::exists(Paths[3]));
916 ASSERT_NO_ERROR(fs::remove_directories("D:/footest"));
918 ASSERT_NO_ERROR(fs::remove_directories(BaseDir));
919 ASSERT_FALSE(fs::exists(BaseDir));
922 const char archive[] = "!<arch>\x0A";
923 const char bitcode[] = "\xde\xc0\x17\x0b";
924 const char coff_object[] = "\x00\x00......";
925 const char coff_bigobj[] = "\x00\x00\xff\xff\x00\x02......"
926 "\xc7\xa1\xba\xd1\xee\xba\xa9\x4b\xaf\x20\xfa\xf6\x6a\xa4\xdc\xb8";
927 const char coff_import_library[] = "\x00\x00\xff\xff....";
928 const char elf_relocatable[] = { 0x7f, 'E', 'L', 'F', 1, 2, 1, 0, 0,
929 0, 0, 0, 0, 0, 0, 0, 0, 1 };
930 const char macho_universal_binary[] = "\xca\xfe\xba\xbe...\x00";
931 const char macho_object[] =
932 "\xfe\xed\xfa\xce........\x00\x00\x00\x01............";
933 const char macho_executable[] =
934 "\xfe\xed\xfa\xce........\x00\x00\x00\x02............";
935 const char macho_fixed_virtual_memory_shared_lib[] =
936 "\xfe\xed\xfa\xce........\x00\x00\x00\x03............";
937 const char macho_core[] =
938 "\xfe\xed\xfa\xce........\x00\x00\x00\x04............";
939 const char macho_preload_executable[] =
940 "\xfe\xed\xfa\xce........\x00\x00\x00\x05............";
941 const char macho_dynamically_linked_shared_lib[] =
942 "\xfe\xed\xfa\xce........\x00\x00\x00\x06............";
943 const char macho_dynamic_linker[] =
944 "\xfe\xed\xfa\xce........\x00\x00\x00\x07............";
945 const char macho_bundle[] =
946 "\xfe\xed\xfa\xce........\x00\x00\x00\x08............";
947 const char macho_dsym_companion[] =
948 "\xfe\xed\xfa\xce........\x00\x00\x00\x0a............";
949 const char macho_kext_bundle[] =
950 "\xfe\xed\xfa\xce........\x00\x00\x00\x0b............";
951 const char windows_resource[] = "\x00\x00\x00\x00\x020\x00\x00\x00\xff";
952 const char macho_dynamically_linked_shared_lib_stub[] =
953 "\xfe\xed\xfa\xce........\x00\x00\x00\x09............";
955 TEST_F(FileSystemTest, Magic) {
957 const char *filename;
958 const char *magic_str;
959 size_t magic_str_len;
960 fs::file_magic magic;
962 #define DEFINE(magic) \
963 { #magic, magic, sizeof(magic), fs::file_magic::magic }
967 { "coff_bigobj", coff_bigobj, sizeof(coff_bigobj), fs::file_magic::coff_object },
968 DEFINE(coff_import_library),
969 DEFINE(elf_relocatable),
970 DEFINE(macho_universal_binary),
971 DEFINE(macho_object),
972 DEFINE(macho_executable),
973 DEFINE(macho_fixed_virtual_memory_shared_lib),
975 DEFINE(macho_preload_executable),
976 DEFINE(macho_dynamically_linked_shared_lib),
977 DEFINE(macho_dynamic_linker),
978 DEFINE(macho_bundle),
979 DEFINE(macho_dynamically_linked_shared_lib_stub),
980 DEFINE(macho_dsym_companion),
981 DEFINE(macho_kext_bundle),
982 DEFINE(windows_resource)
986 // Create some files filled with magic.
987 for (type *i = types, *e = types + (sizeof(types) / sizeof(type)); i != e;
989 SmallString<128> file_pathname(TestDirectory);
990 path::append(file_pathname, i->filename);
992 raw_fd_ostream file(file_pathname, EC, sys::fs::F_None);
993 ASSERT_FALSE(file.has_error());
994 StringRef magic(i->magic_str, i->magic_str_len);
997 EXPECT_EQ(i->magic, fs::identify_magic(magic));
998 ASSERT_NO_ERROR(fs::remove(Twine(file_pathname)));
1002 #ifdef LLVM_ON_WIN32
1003 TEST_F(FileSystemTest, CarriageReturn) {
1004 SmallString<128> FilePathname(TestDirectory);
1006 path::append(FilePathname, "test");
1009 raw_fd_ostream File(FilePathname, EC, sys::fs::F_Text);
1010 ASSERT_NO_ERROR(EC);
1014 auto Buf = MemoryBuffer::getFile(FilePathname.str());
1015 EXPECT_TRUE((bool)Buf);
1016 EXPECT_EQ(Buf.get()->getBuffer(), "\r\n");
1020 raw_fd_ostream File(FilePathname, EC, sys::fs::F_None);
1021 ASSERT_NO_ERROR(EC);
1025 auto Buf = MemoryBuffer::getFile(FilePathname.str());
1026 EXPECT_TRUE((bool)Buf);
1027 EXPECT_EQ(Buf.get()->getBuffer(), "\n");
1029 ASSERT_NO_ERROR(fs::remove(Twine(FilePathname)));
1033 TEST_F(FileSystemTest, Resize) {
1035 SmallString<64> TempPath;
1036 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1037 ASSERT_NO_ERROR(fs::resize_file(FD, 123));
1038 fs::file_status Status;
1039 ASSERT_NO_ERROR(fs::status(FD, Status));
1040 ASSERT_EQ(Status.getSize(), 123U);
1042 ASSERT_NO_ERROR(fs::remove(TempPath));
1045 TEST_F(FileSystemTest, MD5) {
1047 SmallString<64> TempPath;
1048 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1049 StringRef Data("abcdefghijklmnopqrstuvwxyz");
1050 ASSERT_EQ(write(FD, Data.data(), Data.size()), static_cast<ssize_t>(Data.size()));
1051 lseek(FD, 0, SEEK_SET);
1052 auto Hash = fs::md5_contents(FD);
1054 ASSERT_NO_ERROR(Hash.getError());
1056 EXPECT_STREQ("c3fcd3d76192e4007dfb496cca67e13b", Hash->digest().c_str());
1059 TEST_F(FileSystemTest, FileMapping) {
1060 // Create a temp file.
1062 SmallString<64> TempPath;
1064 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
1065 unsigned Size = 4096;
1066 ASSERT_NO_ERROR(fs::resize_file(FileDescriptor, Size));
1068 // Map in temp file and add some content
1070 StringRef Val("hello there");
1072 fs::mapped_file_region mfr(FileDescriptor,
1073 fs::mapped_file_region::readwrite, Size, 0, EC);
1074 ASSERT_NO_ERROR(EC);
1075 std::copy(Val.begin(), Val.end(), mfr.data());
1076 // Explicitly add a 0.
1077 mfr.data()[Val.size()] = 0;
1080 ASSERT_EQ(close(FileDescriptor), 0);
1082 // Map it back in read-only
1085 EC = fs::openFileForRead(Twine(TempPath), FD);
1086 ASSERT_NO_ERROR(EC);
1087 fs::mapped_file_region mfr(FD, fs::mapped_file_region::readonly, Size, 0, EC);
1088 ASSERT_NO_ERROR(EC);
1091 EXPECT_EQ(StringRef(mfr.const_data()), Val);
1094 fs::mapped_file_region m(FD, fs::mapped_file_region::readonly, Size, 0, EC);
1095 ASSERT_NO_ERROR(EC);
1096 ASSERT_EQ(close(FD), 0);
1098 ASSERT_NO_ERROR(fs::remove(TempPath));
1101 TEST(Support, NormalizePath) {
1102 using TestTuple = std::tuple<const char *, const char *, const char *>;
1103 std::vector<TestTuple> Tests;
1104 Tests.emplace_back("a", "a", "a");
1105 Tests.emplace_back("a/b", "a\\b", "a/b");
1106 Tests.emplace_back("a\\b", "a\\b", "a/b");
1107 Tests.emplace_back("a\\\\b", "a\\\\b", "a\\\\b");
1108 Tests.emplace_back("\\a", "\\a", "/a");
1109 Tests.emplace_back("a\\", "a\\", "a/");
1111 for (auto &T : Tests) {
1112 SmallString<64> Win(std::get<0>(T));
1113 SmallString<64> Posix(Win);
1114 path::native(Win, path::Style::windows);
1115 path::native(Posix, path::Style::posix);
1116 EXPECT_EQ(std::get<1>(T), Win);
1117 EXPECT_EQ(std::get<2>(T), Posix);
1120 #if defined(LLVM_ON_WIN32)
1121 SmallString<64> PathHome;
1122 path::home_directory(PathHome);
1124 const char *Path7a = "~/aaa";
1125 SmallString<64> Path7(Path7a);
1126 path::native(Path7);
1127 EXPECT_TRUE(Path7.endswith("\\aaa"));
1128 EXPECT_TRUE(Path7.startswith(PathHome));
1129 EXPECT_EQ(Path7.size(), PathHome.size() + strlen(Path7a + 1));
1131 const char *Path8a = "~";
1132 SmallString<64> Path8(Path8a);
1133 path::native(Path8);
1134 EXPECT_EQ(Path8, PathHome);
1136 const char *Path9a = "~aaa";
1137 SmallString<64> Path9(Path9a);
1138 path::native(Path9);
1139 EXPECT_EQ(Path9, "~aaa");
1141 const char *Path10a = "aaa/~/b";
1142 SmallString<64> Path10(Path10a);
1143 path::native(Path10);
1144 EXPECT_EQ(Path10, "aaa\\~\\b");
1148 TEST(Support, RemoveLeadingDotSlash) {
1149 StringRef Path1("././/foolz/wat");
1150 StringRef Path2("./////");
1152 Path1 = path::remove_leading_dotslash(Path1);
1153 EXPECT_EQ(Path1, "foolz/wat");
1154 Path2 = path::remove_leading_dotslash(Path2);
1155 EXPECT_EQ(Path2, "");
1158 static std::string remove_dots(StringRef path, bool remove_dot_dot,
1159 path::Style style) {
1160 SmallString<256> buffer(path);
1161 path::remove_dots(buffer, remove_dot_dot, style);
1162 return buffer.str();
1165 TEST(Support, RemoveDots) {
1166 EXPECT_EQ("foolz\\wat",
1167 remove_dots(".\\.\\\\foolz\\wat", false, path::Style::windows));
1168 EXPECT_EQ("", remove_dots(".\\\\\\\\\\", false, path::Style::windows));
1170 EXPECT_EQ("a\\..\\b\\c",
1171 remove_dots(".\\a\\..\\b\\c", false, path::Style::windows));
1172 EXPECT_EQ("b\\c", remove_dots(".\\a\\..\\b\\c", true, path::Style::windows));
1173 EXPECT_EQ("c", remove_dots(".\\.\\c", true, path::Style::windows));
1174 EXPECT_EQ("..\\a\\c",
1175 remove_dots("..\\a\\b\\..\\c", true, path::Style::windows));
1176 EXPECT_EQ("..\\..\\a\\c",
1177 remove_dots("..\\..\\a\\b\\..\\c", true, path::Style::windows));
1179 SmallString<64> Path1(".\\.\\c");
1180 EXPECT_TRUE(path::remove_dots(Path1, true, path::Style::windows));
1181 EXPECT_EQ("c", Path1);
1183 EXPECT_EQ("foolz/wat",
1184 remove_dots("././/foolz/wat", false, path::Style::posix));
1185 EXPECT_EQ("", remove_dots("./////", false, path::Style::posix));
1187 EXPECT_EQ("a/../b/c", remove_dots("./a/../b/c", false, path::Style::posix));
1188 EXPECT_EQ("b/c", remove_dots("./a/../b/c", true, path::Style::posix));
1189 EXPECT_EQ("c", remove_dots("././c", true, path::Style::posix));
1190 EXPECT_EQ("../a/c", remove_dots("../a/b/../c", true, path::Style::posix));
1191 EXPECT_EQ("../../a/c",
1192 remove_dots("../../a/b/../c", true, path::Style::posix));
1193 EXPECT_EQ("/a/c", remove_dots("/../../a/c", true, path::Style::posix));
1195 remove_dots("/../a/b//../././/c", true, path::Style::posix));
1197 SmallString<64> Path2("././c");
1198 EXPECT_TRUE(path::remove_dots(Path2, true, path::Style::posix));
1199 EXPECT_EQ("c", Path2);
1202 TEST(Support, ReplacePathPrefix) {
1203 SmallString<64> Path1("/foo");
1204 SmallString<64> Path2("/old/foo");
1205 SmallString<64> OldPrefix("/old");
1206 SmallString<64> NewPrefix("/new");
1207 SmallString<64> NewPrefix2("/longernew");
1208 SmallString<64> EmptyPrefix("");
1210 SmallString<64> Path = Path1;
1211 path::replace_path_prefix(Path, OldPrefix, NewPrefix);
1212 EXPECT_EQ(Path, "/foo");
1214 path::replace_path_prefix(Path, OldPrefix, NewPrefix);
1215 EXPECT_EQ(Path, "/new/foo");
1217 path::replace_path_prefix(Path, OldPrefix, NewPrefix2);
1218 EXPECT_EQ(Path, "/longernew/foo");
1220 path::replace_path_prefix(Path, EmptyPrefix, NewPrefix);
1221 EXPECT_EQ(Path, "/new/foo");
1223 path::replace_path_prefix(Path, OldPrefix, EmptyPrefix);
1224 EXPECT_EQ(Path, "/foo");
1227 TEST_F(FileSystemTest, PathFromFD) {
1228 // Create a temp file.
1230 SmallString<64> TempPath;
1232 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
1233 FileRemover Cleanup(TempPath);
1235 // Make sure it exists.
1236 ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
1238 // Try to get the path from the file descriptor
1239 SmallString<64> ResultPath;
1240 std::error_code ErrorCode =
1241 fs::getPathFromOpenFD(FileDescriptor, ResultPath);
1243 // If we succeeded, check that the paths are the same (modulo case):
1245 // The paths returned by createTemporaryFile and getPathFromOpenFD
1246 // should reference the same file on disk.
1247 fs::UniqueID D1, D2;
1248 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), D1));
1249 ASSERT_NO_ERROR(fs::getUniqueID(Twine(ResultPath), D2));
1253 ::close(FileDescriptor);
1256 TEST_F(FileSystemTest, PathFromFDWin32) {
1257 // Create a temp file.
1259 SmallString<64> TempPath;
1261 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
1262 FileRemover Cleanup(TempPath);
1264 // Make sure it exists.
1265 ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
1267 SmallVector<char, 8> ResultPath;
1268 std::error_code ErrorCode =
1269 fs::getPathFromOpenFD(FileDescriptor, ResultPath);
1272 // Now that we know how much space is required for the path, create a path
1273 // buffer with exactly enough space (sans null terminator, which should not
1274 // be present), and call getPathFromOpenFD again to ensure that the API
1275 // properly handles exactly-sized buffers.
1276 SmallVector<char, 8> ExactSizedPath(ResultPath.size());
1277 ErrorCode = fs::getPathFromOpenFD(FileDescriptor, ExactSizedPath);
1278 ResultPath = ExactSizedPath;
1282 fs::UniqueID D1, D2;
1283 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), D1));
1284 ASSERT_NO_ERROR(fs::getUniqueID(Twine(ResultPath), D2));
1287 ::close(FileDescriptor);
1290 TEST_F(FileSystemTest, PathFromFDUnicode) {
1291 // Create a temp file.
1293 SmallString<64> TempPath;
1295 // Test Unicode: "<temp directory>/(pi)r^2<temp rand chars>.aleth.0"
1297 fs::createTemporaryFile("\xCF\x80r\xC2\xB2",
1298 "\xE2\x84\xB5.0", FileDescriptor, TempPath));
1299 FileRemover Cleanup(TempPath);
1301 // Make sure it exists.
1302 ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
1304 SmallVector<char, 8> ResultPath;
1305 std::error_code ErrorCode =
1306 fs::getPathFromOpenFD(FileDescriptor, ResultPath);
1309 fs::UniqueID D1, D2;
1310 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), D1));
1311 ASSERT_NO_ERROR(fs::getUniqueID(Twine(ResultPath), D2));
1314 ::close(FileDescriptor);
1317 TEST_F(FileSystemTest, OpenFileForRead) {
1318 // Create a temp file.
1320 SmallString<64> TempPath;
1322 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
1323 FileRemover Cleanup(TempPath);
1325 // Make sure it exists.
1326 ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
1328 // Open the file for read
1329 int FileDescriptor2;
1330 SmallString<64> ResultPath;
1332 fs::openFileForRead(Twine(TempPath), FileDescriptor2, &ResultPath))
1334 // If we succeeded, check that the paths are the same (modulo case):
1335 if (!ResultPath.empty()) {
1336 // The paths returned by createTemporaryFile and getPathFromOpenFD
1337 // should reference the same file on disk.
1338 fs::UniqueID D1, D2;
1339 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), D1));
1340 ASSERT_NO_ERROR(fs::getUniqueID(Twine(ResultPath), D2));
1344 ::close(FileDescriptor);
1347 TEST_F(FileSystemTest, set_current_path) {
1348 SmallString<128> path;
1350 ASSERT_NO_ERROR(fs::current_path(path));
1351 ASSERT_NE(TestDirectory, path);
1353 struct RestorePath {
1354 SmallString<128> path;
1355 RestorePath(const SmallString<128> &path) : path(path) {}
1356 ~RestorePath() { fs::set_current_path(path); }
1357 } restore_path(path);
1359 ASSERT_NO_ERROR(fs::set_current_path(TestDirectory));
1361 ASSERT_NO_ERROR(fs::current_path(path));
1363 fs::UniqueID D1, D2;
1364 ASSERT_NO_ERROR(fs::getUniqueID(TestDirectory, D1));
1365 ASSERT_NO_ERROR(fs::getUniqueID(path, D2));
1366 ASSERT_EQ(D1, D2) << "D1: " << TestDirectory << "\nD2: " << path;
1369 TEST_F(FileSystemTest, permissions) {
1371 SmallString<64> TempPath;
1372 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1373 FileRemover Cleanup(TempPath);
1375 // Make sure it exists.
1376 ASSERT_TRUE(fs::exists(Twine(TempPath)));
1378 auto CheckPermissions = [&](fs::perms Expected) {
1379 ErrorOr<fs::perms> Actual = fs::getPermissions(TempPath);
1380 return Actual && *Actual == Expected;
1383 std::error_code NoError;
1384 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_all), NoError);
1385 EXPECT_TRUE(CheckPermissions(fs::all_all));
1387 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read | fs::all_exe), NoError);
1388 EXPECT_TRUE(CheckPermissions(fs::all_read | fs::all_exe));
1390 #if defined(LLVM_ON_WIN32)
1391 fs::perms ReadOnly = fs::all_read | fs::all_exe;
1392 EXPECT_EQ(fs::setPermissions(TempPath, fs::no_perms), NoError);
1393 EXPECT_TRUE(CheckPermissions(ReadOnly));
1395 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_read), NoError);
1396 EXPECT_TRUE(CheckPermissions(ReadOnly));
1398 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_write), NoError);
1399 EXPECT_TRUE(CheckPermissions(fs::all_all));
1401 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_exe), NoError);
1402 EXPECT_TRUE(CheckPermissions(ReadOnly));
1404 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_all), NoError);
1405 EXPECT_TRUE(CheckPermissions(fs::all_all));
1407 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_read), NoError);
1408 EXPECT_TRUE(CheckPermissions(ReadOnly));
1410 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_write), NoError);
1411 EXPECT_TRUE(CheckPermissions(fs::all_all));
1413 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_exe), NoError);
1414 EXPECT_TRUE(CheckPermissions(ReadOnly));
1416 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_all), NoError);
1417 EXPECT_TRUE(CheckPermissions(fs::all_all));
1419 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_read), NoError);
1420 EXPECT_TRUE(CheckPermissions(ReadOnly));
1422 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_write), NoError);
1423 EXPECT_TRUE(CheckPermissions(fs::all_all));
1425 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_exe), NoError);
1426 EXPECT_TRUE(CheckPermissions(ReadOnly));
1428 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_all), NoError);
1429 EXPECT_TRUE(CheckPermissions(fs::all_all));
1431 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read), NoError);
1432 EXPECT_TRUE(CheckPermissions(ReadOnly));
1434 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_write), NoError);
1435 EXPECT_TRUE(CheckPermissions(fs::all_all));
1437 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_exe), NoError);
1438 EXPECT_TRUE(CheckPermissions(ReadOnly));
1440 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe), NoError);
1441 EXPECT_TRUE(CheckPermissions(ReadOnly));
1443 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_gid_on_exe), NoError);
1444 EXPECT_TRUE(CheckPermissions(ReadOnly));
1446 EXPECT_EQ(fs::setPermissions(TempPath, fs::sticky_bit), NoError);
1447 EXPECT_TRUE(CheckPermissions(ReadOnly));
1449 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe |
1450 fs::set_gid_on_exe |
1453 EXPECT_TRUE(CheckPermissions(ReadOnly));
1455 EXPECT_EQ(fs::setPermissions(TempPath, ReadOnly | fs::set_uid_on_exe |
1456 fs::set_gid_on_exe |
1459 EXPECT_TRUE(CheckPermissions(ReadOnly));
1461 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms), NoError);
1462 EXPECT_TRUE(CheckPermissions(fs::all_all));
1464 EXPECT_EQ(fs::setPermissions(TempPath, fs::no_perms), NoError);
1465 EXPECT_TRUE(CheckPermissions(fs::no_perms));
1467 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_read), NoError);
1468 EXPECT_TRUE(CheckPermissions(fs::owner_read));
1470 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_write), NoError);
1471 EXPECT_TRUE(CheckPermissions(fs::owner_write));
1473 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_exe), NoError);
1474 EXPECT_TRUE(CheckPermissions(fs::owner_exe));
1476 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_all), NoError);
1477 EXPECT_TRUE(CheckPermissions(fs::owner_all));
1479 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_read), NoError);
1480 EXPECT_TRUE(CheckPermissions(fs::group_read));
1482 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_write), NoError);
1483 EXPECT_TRUE(CheckPermissions(fs::group_write));
1485 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_exe), NoError);
1486 EXPECT_TRUE(CheckPermissions(fs::group_exe));
1488 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_all), NoError);
1489 EXPECT_TRUE(CheckPermissions(fs::group_all));
1491 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_read), NoError);
1492 EXPECT_TRUE(CheckPermissions(fs::others_read));
1494 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_write), NoError);
1495 EXPECT_TRUE(CheckPermissions(fs::others_write));
1497 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_exe), NoError);
1498 EXPECT_TRUE(CheckPermissions(fs::others_exe));
1500 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_all), NoError);
1501 EXPECT_TRUE(CheckPermissions(fs::others_all));
1503 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read), NoError);
1504 EXPECT_TRUE(CheckPermissions(fs::all_read));
1506 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_write), NoError);
1507 EXPECT_TRUE(CheckPermissions(fs::all_write));
1509 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_exe), NoError);
1510 EXPECT_TRUE(CheckPermissions(fs::all_exe));
1512 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe), NoError);
1513 EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe));
1515 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_gid_on_exe), NoError);
1516 EXPECT_TRUE(CheckPermissions(fs::set_gid_on_exe));
1518 // Modern BSDs require root to set the sticky bit on files.
1519 #if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__)
1520 EXPECT_EQ(fs::setPermissions(TempPath, fs::sticky_bit), NoError);
1521 EXPECT_TRUE(CheckPermissions(fs::sticky_bit));
1523 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe |
1524 fs::set_gid_on_exe |
1527 EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe | fs::set_gid_on_exe |
1530 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read | fs::set_uid_on_exe |
1531 fs::set_gid_on_exe |
1534 EXPECT_TRUE(CheckPermissions(fs::all_read | fs::set_uid_on_exe |
1535 fs::set_gid_on_exe | fs::sticky_bit));
1537 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms), NoError);
1538 EXPECT_TRUE(CheckPermissions(fs::all_perms));
1539 #endif // !FreeBSD && !NetBSD && !OpenBSD
1541 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms & ~fs::sticky_bit),
1543 EXPECT_TRUE(CheckPermissions(fs::all_perms & ~fs::sticky_bit));
1547 } // anonymous namespace