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/Support/ConvertUTF.h"
12 #include "llvm/Support/Errc.h"
13 #include "llvm/Support/ErrorHandling.h"
14 #include "llvm/Support/FileSystem.h"
15 #include "llvm/Support/MemoryBuffer.h"
16 #include "llvm/Support/raw_ostream.h"
17 #include "gtest/gtest.h"
20 #include "llvm/ADT/ArrayRef.h"
30 using namespace llvm::sys;
32 #define ASSERT_NO_ERROR(x) \
33 if (std::error_code ASSERT_NO_ERROR_ec = x) { \
34 SmallString<128> MessageStorage; \
35 raw_svector_ostream Message(MessageStorage); \
36 Message << #x ": did not return errc::success.\n" \
37 << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n" \
38 << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \
39 GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \
45 TEST(is_separator, Works) {
46 EXPECT_TRUE(path::is_separator('/'));
47 EXPECT_FALSE(path::is_separator('\0'));
48 EXPECT_FALSE(path::is_separator('-'));
49 EXPECT_FALSE(path::is_separator(' '));
52 EXPECT_TRUE(path::is_separator('\\'));
54 EXPECT_FALSE(path::is_separator('\\'));
59 SmallVector<StringRef, 40> paths;
62 paths.push_back("..");
63 paths.push_back("foo");
65 paths.push_back("/foo");
66 paths.push_back("foo/");
67 paths.push_back("/foo/");
68 paths.push_back("foo/bar");
69 paths.push_back("/foo/bar");
70 paths.push_back("//net");
71 paths.push_back("//net/foo");
72 paths.push_back("///foo///");
73 paths.push_back("///foo///bar");
74 paths.push_back("/.");
75 paths.push_back("./");
76 paths.push_back("/..");
77 paths.push_back("../");
78 paths.push_back("foo/.");
79 paths.push_back("foo/..");
80 paths.push_back("foo/./");
81 paths.push_back("foo/./bar");
82 paths.push_back("foo/..");
83 paths.push_back("foo/../");
84 paths.push_back("foo/../bar");
85 paths.push_back("c:");
86 paths.push_back("c:/");
87 paths.push_back("c:foo");
88 paths.push_back("c:/foo");
89 paths.push_back("c:foo/");
90 paths.push_back("c:/foo/");
91 paths.push_back("c:/foo/bar");
92 paths.push_back("prn:");
93 paths.push_back("c:\\");
94 paths.push_back("c:foo");
95 paths.push_back("c:\\foo");
96 paths.push_back("c:foo\\");
97 paths.push_back("c:\\foo\\");
98 paths.push_back("c:\\foo/");
99 paths.push_back("c:/foo\\bar");
101 SmallVector<StringRef, 5> ComponentStack;
102 for (SmallVector<StringRef, 40>::const_iterator i = paths.begin(),
106 for (sys::path::const_iterator ci = sys::path::begin(*i),
107 ce = sys::path::end(*i);
110 ASSERT_FALSE(ci->empty());
111 ComponentStack.push_back(*ci);
114 for (sys::path::reverse_iterator ci = sys::path::rbegin(*i),
115 ce = sys::path::rend(*i);
118 ASSERT_TRUE(*ci == ComponentStack.back());
119 ComponentStack.pop_back();
121 ASSERT_TRUE(ComponentStack.empty());
123 path::has_root_path(*i);
125 path::has_root_name(*i);
127 path::has_root_directory(*i);
128 path::root_directory(*i);
129 path::has_parent_path(*i);
130 path::parent_path(*i);
131 path::has_filename(*i);
135 path::has_extension(*i);
137 path::is_absolute(*i);
138 path::is_relative(*i);
140 SmallString<128> temp_store;
142 ASSERT_NO_ERROR(fs::make_absolute(temp_store));
144 path::remove_filename(temp_store);
147 path::replace_extension(temp_store, "ext");
148 StringRef filename(temp_store.begin(), temp_store.size()), stem, ext;
149 stem = path::stem(filename);
150 ext = path::extension(filename);
151 EXPECT_EQ(*sys::path::rbegin(filename), (stem + ext).str());
153 path::native(*i, temp_store);
156 SmallString<32> Relative("foo.cpp");
157 ASSERT_NO_ERROR(sys::fs::make_absolute("/root", Relative));
158 Relative[5] = '/'; // Fix up windows paths.
159 ASSERT_EQ("/root/foo.cpp", Relative);
162 TEST(Support, RelativePathIterator) {
163 SmallString<64> Path(StringRef("c/d/e/foo.txt"));
164 typedef SmallVector<StringRef, 4> PathComponents;
165 PathComponents ExpectedPathComponents;
166 PathComponents ActualPathComponents;
168 StringRef(Path).split(ExpectedPathComponents, '/');
170 for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
172 ActualPathComponents.push_back(*I);
175 ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
177 for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
178 EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
182 TEST(Support, RelativePathDotIterator) {
183 SmallString<64> Path(StringRef(".c/.d/../."));
184 typedef SmallVector<StringRef, 4> PathComponents;
185 PathComponents ExpectedPathComponents;
186 PathComponents ActualPathComponents;
188 StringRef(Path).split(ExpectedPathComponents, '/');
190 for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
192 ActualPathComponents.push_back(*I);
195 ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
197 for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
198 EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
202 TEST(Support, AbsolutePathIterator) {
203 SmallString<64> Path(StringRef("/c/d/e/foo.txt"));
204 typedef SmallVector<StringRef, 4> PathComponents;
205 PathComponents ExpectedPathComponents;
206 PathComponents ActualPathComponents;
208 StringRef(Path).split(ExpectedPathComponents, '/');
210 // The root path will also be a component when iterating
211 ExpectedPathComponents[0] = "/";
213 for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
215 ActualPathComponents.push_back(*I);
218 ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
220 for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
221 EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
225 TEST(Support, AbsolutePathDotIterator) {
226 SmallString<64> Path(StringRef("/.c/.d/../."));
227 typedef SmallVector<StringRef, 4> PathComponents;
228 PathComponents ExpectedPathComponents;
229 PathComponents ActualPathComponents;
231 StringRef(Path).split(ExpectedPathComponents, '/');
233 // The root path will also be a component when iterating
234 ExpectedPathComponents[0] = "/";
236 for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
238 ActualPathComponents.push_back(*I);
241 ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
243 for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
244 EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
249 TEST(Support, AbsolutePathIteratorWin32) {
250 SmallString<64> Path(StringRef("c:\\c\\e\\foo.txt"));
251 typedef SmallVector<StringRef, 4> PathComponents;
252 PathComponents ExpectedPathComponents;
253 PathComponents ActualPathComponents;
255 StringRef(Path).split(ExpectedPathComponents, "\\");
257 // The root path (which comes after the drive name) will also be a component
259 ExpectedPathComponents.insert(ExpectedPathComponents.begin()+1, "\\");
261 for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
263 ActualPathComponents.push_back(*I);
266 ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
268 for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
269 EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
272 #endif // LLVM_ON_WIN32
274 TEST(Support, AbsolutePathIteratorEnd) {
275 // Trailing slashes are converted to '.' unless they are part of the root path.
276 SmallVector<StringRef, 4> Paths;
277 Paths.push_back("/foo/");
278 Paths.push_back("/foo//");
279 Paths.push_back("//net//");
281 Paths.push_back("c:\\\\");
284 for (StringRef Path : Paths) {
285 StringRef LastComponent = *path::rbegin(Path);
286 EXPECT_EQ(".", LastComponent);
289 SmallVector<StringRef, 3> RootPaths;
290 RootPaths.push_back("/");
291 RootPaths.push_back("//net/");
293 RootPaths.push_back("c:\\");
296 for (StringRef Path : RootPaths) {
297 StringRef LastComponent = *path::rbegin(Path);
298 EXPECT_EQ(1u, LastComponent.size());
299 EXPECT_TRUE(path::is_separator(LastComponent[0]));
303 TEST(Support, HomeDirectory) {
304 std::string expected;
306 if (wchar_t const *path = ::_wgetenv(L"USERPROFILE")) {
307 auto pathLen = ::wcslen(path);
308 ArrayRef<char> ref{reinterpret_cast<char const *>(path),
309 pathLen * sizeof(wchar_t)};
310 convertUTF16ToUTF8String(ref, expected);
313 if (char const *path = ::getenv("HOME"))
316 // Do not try to test it if we don't know what to expect.
317 // On Windows we use something better than env vars.
318 if (!expected.empty()) {
319 SmallString<128> HomeDir;
320 auto status = path::home_directory(HomeDir);
322 EXPECT_EQ(expected, HomeDir);
326 TEST(Support, UserCacheDirectory) {
327 SmallString<13> CacheDir;
328 SmallString<20> CacheDir2;
329 auto Status = path::user_cache_directory(CacheDir, "");
330 EXPECT_TRUE(Status ^ CacheDir.empty());
333 EXPECT_TRUE(path::user_cache_directory(CacheDir2, "")); // should succeed
334 EXPECT_EQ(CacheDir, CacheDir2); // and return same paths
336 EXPECT_TRUE(path::user_cache_directory(CacheDir, "A", "B", "file.c"));
337 auto It = path::rbegin(CacheDir);
338 EXPECT_EQ("file.c", *It);
339 EXPECT_EQ("B", *++It);
340 EXPECT_EQ("A", *++It);
341 auto ParentDir = *++It;
343 // Test Unicode: "<user_cache_dir>/(pi)r^2/aleth.0"
344 EXPECT_TRUE(path::user_cache_directory(CacheDir2, "\xCF\x80r\xC2\xB2",
346 auto It2 = path::rbegin(CacheDir2);
347 EXPECT_EQ("\xE2\x84\xB5.0", *It2);
348 EXPECT_EQ("\xCF\x80r\xC2\xB2", *++It2);
349 auto ParentDir2 = *++It2;
351 EXPECT_EQ(ParentDir, ParentDir2);
355 TEST(Support, TempDirectory) {
356 SmallString<32> TempDir;
357 path::system_temp_directory(false, TempDir);
358 EXPECT_TRUE(!TempDir.empty());
360 path::system_temp_directory(true, TempDir);
361 EXPECT_TRUE(!TempDir.empty());
365 static std::string path2regex(std::string Path) {
367 while ((Pos = Path.find('\\', Pos)) != std::string::npos) {
368 Path.replace(Pos, 1, "\\\\");
374 /// Helper for running temp dir test in separated process. See below.
375 #define EXPECT_TEMP_DIR(prepare, expected) \
379 SmallString<300> TempDir; \
380 path::system_temp_directory(true, TempDir); \
381 raw_os_ostream(std::cerr) << TempDir; \
384 ::testing::ExitedWithCode(0), path2regex(expected))
386 TEST(SupportDeathTest, TempDirectoryOnWindows) {
387 // In this test we want to check how system_temp_directory responds to
388 // different values of specific env vars. To prevent corrupting env vars of
389 // the current process all checks are done in separated processes.
390 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"C:\\OtherFolder"), "C:\\OtherFolder");
391 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"C:/Unix/Path/Seperators"),
392 "C:\\Unix\\Path\\Seperators");
393 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"Local Path"), ".+\\Local Path$");
394 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"F:\\TrailingSep\\"), "F:\\TrailingSep");
396 _wputenv_s(L"TMP", L"C:\\2\x03C0r-\x00B5\x00B3\\\x2135\x2080"),
397 "C:\\2\xCF\x80r-\xC2\xB5\xC2\xB3\\\xE2\x84\xB5\xE2\x82\x80");
399 // Test $TMP empty, $TEMP set.
402 _wputenv_s(L"TMP", L"");
403 _wputenv_s(L"TEMP", L"C:\\Valid\\Path");
407 // All related env vars empty
410 _wputenv_s(L"TMP", L"");
411 _wputenv_s(L"TEMP", L"");
412 _wputenv_s(L"USERPROFILE", L"");
416 // Test evn var / path with 260 chars.
417 SmallString<270> Expected{"C:\\Temp\\AB\\123456789"};
418 while (Expected.size() < 260)
419 Expected.append("\\DirNameWith19Charss");
420 ASSERT_EQ(260U, Expected.size());
421 EXPECT_TEMP_DIR(_putenv_s("TMP", Expected.c_str()), Expected.c_str());
425 class FileSystemTest : public testing::Test {
427 /// Unique temporary directory in which all created filesystem entities must
428 /// be placed. It is removed at the end of each test (must be empty).
429 SmallString<128> TestDirectory;
431 void SetUp() override {
433 fs::createUniqueDirectory("file-system-test", TestDirectory));
434 // We don't care about this specific file.
435 errs() << "Test Directory: " << TestDirectory << '\n';
439 void TearDown() override { ASSERT_NO_ERROR(fs::remove(TestDirectory.str())); }
442 TEST_F(FileSystemTest, Unique) {
443 // Create a temp file.
445 SmallString<64> TempPath;
447 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
449 // The same file should return an identical unique id.
451 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F1));
452 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F2));
455 // Different files should return different unique ids.
457 SmallString<64> TempPath2;
459 fs::createTemporaryFile("prefix", "temp", FileDescriptor2, TempPath2));
462 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D));
464 ::close(FileDescriptor2);
466 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
468 // Two paths representing the same file on disk should still provide the
469 // same unique id. We can test this by making a hard link.
470 ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2)));
472 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D2));
475 ::close(FileDescriptor);
477 SmallString<128> Dir1;
479 fs::createUniqueDirectory("dir1", Dir1));
480 ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F1));
481 ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F2));
484 SmallString<128> Dir2;
486 fs::createUniqueDirectory("dir2", Dir2));
487 ASSERT_NO_ERROR(fs::getUniqueID(Dir2.c_str(), F2));
491 TEST_F(FileSystemTest, TempFiles) {
492 // Create a temp file.
494 SmallString<64> TempPath;
496 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
498 // Make sure it exists.
499 ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
501 // Create another temp tile.
503 SmallString<64> TempPath2;
504 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD2, TempPath2));
505 ASSERT_TRUE(TempPath2.endswith(".temp"));
506 ASSERT_NE(TempPath.str(), TempPath2.str());
508 fs::file_status A, B;
509 ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
510 ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
511 EXPECT_FALSE(fs::equivalent(A, B));
516 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
517 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
518 ASSERT_EQ(fs::remove(Twine(TempPath2), false),
519 errc::no_such_file_or_directory);
521 std::error_code EC = fs::status(TempPath2.c_str(), B);
522 EXPECT_EQ(EC, errc::no_such_file_or_directory);
523 EXPECT_EQ(B.type(), fs::file_type::file_not_found);
525 // Make sure Temp2 doesn't exist.
526 ASSERT_EQ(fs::access(Twine(TempPath2), sys::fs::AccessMode::Exist),
527 errc::no_such_file_or_directory);
529 SmallString<64> TempPath3;
530 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "", TempPath3));
531 ASSERT_FALSE(TempPath3.endswith("."));
533 // Create a hard link to Temp1.
534 ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2)));
536 ASSERT_NO_ERROR(fs::equivalent(Twine(TempPath), Twine(TempPath2), equal));
538 ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
539 ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
540 EXPECT_TRUE(fs::equivalent(A, B));
543 ::close(FileDescriptor);
544 ASSERT_NO_ERROR(fs::remove(Twine(TempPath)));
546 // Remove the hard link.
547 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
549 // Make sure Temp1 doesn't exist.
550 ASSERT_EQ(fs::access(Twine(TempPath), sys::fs::AccessMode::Exist),
551 errc::no_such_file_or_directory);
554 // Path name > 260 chars should get an error.
555 const char *Path270 =
556 "abcdefghijklmnopqrstuvwxyz9abcdefghijklmnopqrstuvwxyz8"
557 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
558 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
559 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
560 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
561 EXPECT_EQ(fs::createUniqueFile(Path270, FileDescriptor, TempPath),
562 errc::invalid_argument);
563 // Relative path < 247 chars, no problem.
564 const char *Path216 =
565 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
566 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
567 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
568 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
569 ASSERT_NO_ERROR(fs::createTemporaryFile(Path216, "", TempPath));
570 ASSERT_NO_ERROR(fs::remove(Twine(TempPath)));
574 TEST_F(FileSystemTest, CreateDir) {
575 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
576 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
577 ASSERT_EQ(fs::create_directory(Twine(TestDirectory) + "foo", false),
579 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "foo"));
582 // Set a 0000 umask so that we can test our directory permissions.
583 mode_t OldUmask = ::umask(0000);
585 fs::file_status Status;
587 fs::create_directory(Twine(TestDirectory) + "baz500", false,
588 fs::perms::owner_read | fs::perms::owner_exe));
589 ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz500", Status));
590 ASSERT_EQ(Status.permissions() & fs::perms::all_all,
591 fs::perms::owner_read | fs::perms::owner_exe);
592 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "baz777", false,
593 fs::perms::all_all));
594 ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz777", Status));
595 ASSERT_EQ(Status.permissions() & fs::perms::all_all, fs::perms::all_all);
597 // Restore umask to be safe.
602 // Prove that create_directories() can handle a pathname > 248 characters,
603 // which is the documented limit for CreateDirectory().
604 // (248 is MAX_PATH subtracting room for an 8.3 filename.)
605 // Generate a directory path guaranteed to fall into that range.
606 size_t TmpLen = TestDirectory.size();
607 const char *OneDir = "\\123456789";
608 size_t OneDirLen = strlen(OneDir);
609 ASSERT_LT(OneDirLen, 12U);
610 size_t NLevels = ((248 - TmpLen) / OneDirLen) + 1;
611 SmallString<260> LongDir(TestDirectory);
612 for (size_t I = 0; I < NLevels; ++I)
613 LongDir.append(OneDir);
614 ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir)));
615 ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir)));
616 ASSERT_EQ(fs::create_directories(Twine(LongDir), false),
618 // Tidy up, "recursively" removing the directories.
619 StringRef ThisDir(LongDir);
620 for (size_t J = 0; J < NLevels; ++J) {
621 ASSERT_NO_ERROR(fs::remove(ThisDir));
622 ThisDir = path::parent_path(ThisDir);
625 // Similarly for a relative pathname. Need to set the current directory to
626 // TestDirectory so that the one we create ends up in the right place.
627 char PreviousDir[260];
628 size_t PreviousDirLen = ::GetCurrentDirectoryA(260, PreviousDir);
629 ASSERT_GT(PreviousDirLen, 0U);
630 ASSERT_LT(PreviousDirLen, 260U);
631 ASSERT_NE(::SetCurrentDirectoryA(TestDirectory.c_str()), 0);
633 // Generate a relative directory name with absolute length > 248.
634 size_t LongDirLen = 249 - TestDirectory.size();
635 LongDir.assign(LongDirLen, 'a');
636 ASSERT_NO_ERROR(fs::create_directory(Twine(LongDir)));
637 // While we're here, prove that .. and . handling works in these long paths.
638 const char *DotDotDirs = "\\..\\.\\b";
639 LongDir.append(DotDotDirs);
640 ASSERT_NO_ERROR(fs::create_directory("b"));
641 ASSERT_EQ(fs::create_directory(Twine(LongDir), false), errc::file_exists);
643 ASSERT_NO_ERROR(fs::remove("b"));
644 ASSERT_NO_ERROR(fs::remove(
645 Twine(LongDir.substr(0, LongDir.size() - strlen(DotDotDirs)))));
646 ASSERT_NE(::SetCurrentDirectoryA(PreviousDir), 0);
650 TEST_F(FileSystemTest, DirectoryIteration) {
652 for (fs::directory_iterator i(".", ec), e; i != e; i.increment(ec))
655 // Create a known hierarchy to recurse over.
657 fs::create_directories(Twine(TestDirectory) + "/recursive/a0/aa1"));
659 fs::create_directories(Twine(TestDirectory) + "/recursive/a0/ab1"));
660 ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) +
661 "/recursive/dontlookhere/da1"));
663 fs::create_directories(Twine(TestDirectory) + "/recursive/z0/za1"));
665 fs::create_directories(Twine(TestDirectory) + "/recursive/pop/p1"));
666 typedef std::vector<std::string> v_t;
668 for (fs::recursive_directory_iterator i(Twine(TestDirectory)
669 + "/recursive", ec), e; i != e; i.increment(ec)){
671 if (path::filename(i->path()) == "p1") {
673 // FIXME: recursive_directory_iterator should be more robust.
676 if (path::filename(i->path()) == "dontlookhere")
678 visited.push_back(path::filename(i->path()));
680 v_t::const_iterator a0 = std::find(visited.begin(), visited.end(), "a0");
681 v_t::const_iterator aa1 = std::find(visited.begin(), visited.end(), "aa1");
682 v_t::const_iterator ab1 = std::find(visited.begin(), visited.end(), "ab1");
683 v_t::const_iterator dontlookhere = std::find(visited.begin(), visited.end(),
685 v_t::const_iterator da1 = std::find(visited.begin(), visited.end(), "da1");
686 v_t::const_iterator z0 = std::find(visited.begin(), visited.end(), "z0");
687 v_t::const_iterator za1 = std::find(visited.begin(), visited.end(), "za1");
688 v_t::const_iterator pop = std::find(visited.begin(), visited.end(), "pop");
689 v_t::const_iterator p1 = std::find(visited.begin(), visited.end(), "p1");
691 // Make sure that each path was visited correctly.
692 ASSERT_NE(a0, visited.end());
693 ASSERT_NE(aa1, visited.end());
694 ASSERT_NE(ab1, visited.end());
695 ASSERT_NE(dontlookhere, visited.end());
696 ASSERT_EQ(da1, visited.end()); // Not visited.
697 ASSERT_NE(z0, visited.end());
698 ASSERT_NE(za1, visited.end());
699 ASSERT_NE(pop, visited.end());
700 ASSERT_EQ(p1, visited.end()); // Not visited.
702 // Make sure that parents were visited before children. No other ordering
703 // guarantees can be made across siblings.
708 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/aa1"));
709 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/ab1"));
710 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0"));
712 fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere/da1"));
713 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere"));
714 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop/p1"));
715 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop"));
716 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0/za1"));
717 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0"));
718 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive"));
720 // Test recursive_directory_iterator level()
722 fs::create_directories(Twine(TestDirectory) + "/reclevel/a/b/c"));
723 fs::recursive_directory_iterator I(Twine(TestDirectory) + "/reclevel", ec), E;
724 for (int l = 0; I != E; I.increment(ec), ++l) {
726 EXPECT_EQ(I.level(), l);
729 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a/b/c"));
730 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a/b"));
731 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a"));
732 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel"));
735 const char archive[] = "!<arch>\x0A";
736 const char bitcode[] = "\xde\xc0\x17\x0b";
737 const char coff_object[] = "\x00\x00......";
738 const char coff_bigobj[] = "\x00\x00\xff\xff\x00\x02......"
739 "\xc7\xa1\xba\xd1\xee\xba\xa9\x4b\xaf\x20\xfa\xf6\x6a\xa4\xdc\xb8";
740 const char coff_import_library[] = "\x00\x00\xff\xff....";
741 const char elf_relocatable[] = { 0x7f, 'E', 'L', 'F', 1, 2, 1, 0, 0,
742 0, 0, 0, 0, 0, 0, 0, 0, 1 };
743 const char macho_universal_binary[] = "\xca\xfe\xba\xbe...\x00";
744 const char macho_object[] =
745 "\xfe\xed\xfa\xce........\x00\x00\x00\x01............";
746 const char macho_executable[] =
747 "\xfe\xed\xfa\xce........\x00\x00\x00\x02............";
748 const char macho_fixed_virtual_memory_shared_lib[] =
749 "\xfe\xed\xfa\xce........\x00\x00\x00\x03............";
750 const char macho_core[] =
751 "\xfe\xed\xfa\xce........\x00\x00\x00\x04............";
752 const char macho_preload_executable[] =
753 "\xfe\xed\xfa\xce........\x00\x00\x00\x05............";
754 const char macho_dynamically_linked_shared_lib[] =
755 "\xfe\xed\xfa\xce........\x00\x00\x00\x06............";
756 const char macho_dynamic_linker[] =
757 "\xfe\xed\xfa\xce........\x00\x00\x00\x07............";
758 const char macho_bundle[] =
759 "\xfe\xed\xfa\xce........\x00\x00\x00\x08............";
760 const char macho_dsym_companion[] =
761 "\xfe\xed\xfa\xce........\x00\x00\x00\x0a............";
762 const char macho_kext_bundle[] =
763 "\xfe\xed\xfa\xce........\x00\x00\x00\x0b............";
764 const char windows_resource[] = "\x00\x00\x00\x00\x020\x00\x00\x00\xff";
765 const char macho_dynamically_linked_shared_lib_stub[] =
766 "\xfe\xed\xfa\xce........\x00\x00\x00\x09............";
768 TEST_F(FileSystemTest, Magic) {
770 const char *filename;
771 const char *magic_str;
772 size_t magic_str_len;
773 fs::file_magic magic;
775 #define DEFINE(magic) \
776 { #magic, magic, sizeof(magic), fs::file_magic::magic }
780 { "coff_bigobj", coff_bigobj, sizeof(coff_bigobj), fs::file_magic::coff_object },
781 DEFINE(coff_import_library),
782 DEFINE(elf_relocatable),
783 DEFINE(macho_universal_binary),
784 DEFINE(macho_object),
785 DEFINE(macho_executable),
786 DEFINE(macho_fixed_virtual_memory_shared_lib),
788 DEFINE(macho_preload_executable),
789 DEFINE(macho_dynamically_linked_shared_lib),
790 DEFINE(macho_dynamic_linker),
791 DEFINE(macho_bundle),
792 DEFINE(macho_dynamically_linked_shared_lib_stub),
793 DEFINE(macho_dsym_companion),
794 DEFINE(macho_kext_bundle),
795 DEFINE(windows_resource)
799 // Create some files filled with magic.
800 for (type *i = types, *e = types + (sizeof(types) / sizeof(type)); i != e;
802 SmallString<128> file_pathname(TestDirectory);
803 path::append(file_pathname, i->filename);
805 raw_fd_ostream file(file_pathname, EC, sys::fs::F_None);
806 ASSERT_FALSE(file.has_error());
807 StringRef magic(i->magic_str, i->magic_str_len);
810 EXPECT_EQ(i->magic, fs::identify_magic(magic));
811 ASSERT_NO_ERROR(fs::remove(Twine(file_pathname)));
816 TEST_F(FileSystemTest, CarriageReturn) {
817 SmallString<128> FilePathname(TestDirectory);
819 path::append(FilePathname, "test");
822 raw_fd_ostream File(FilePathname, EC, sys::fs::F_Text);
827 auto Buf = MemoryBuffer::getFile(FilePathname.str());
828 EXPECT_TRUE((bool)Buf);
829 EXPECT_EQ(Buf.get()->getBuffer(), "\r\n");
833 raw_fd_ostream File(FilePathname, EC, sys::fs::F_None);
838 auto Buf = MemoryBuffer::getFile(FilePathname.str());
839 EXPECT_TRUE((bool)Buf);
840 EXPECT_EQ(Buf.get()->getBuffer(), "\n");
842 ASSERT_NO_ERROR(fs::remove(Twine(FilePathname)));
846 TEST_F(FileSystemTest, Resize) {
848 SmallString<64> TempPath;
849 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
850 ASSERT_NO_ERROR(fs::resize_file(FD, 123));
851 fs::file_status Status;
852 ASSERT_NO_ERROR(fs::status(FD, Status));
853 ASSERT_EQ(Status.getSize(), 123U);
856 TEST_F(FileSystemTest, FileMapping) {
857 // Create a temp file.
859 SmallString<64> TempPath;
861 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
862 unsigned Size = 4096;
863 ASSERT_NO_ERROR(fs::resize_file(FileDescriptor, Size));
865 // Map in temp file and add some content
867 StringRef Val("hello there");
869 fs::mapped_file_region mfr(FileDescriptor,
870 fs::mapped_file_region::readwrite, Size, 0, EC);
872 std::copy(Val.begin(), Val.end(), mfr.data());
873 // Explicitly add a 0.
874 mfr.data()[Val.size()] = 0;
878 // Map it back in read-only
880 EC = fs::openFileForRead(Twine(TempPath), FD);
882 fs::mapped_file_region mfr(FD, fs::mapped_file_region::readonly, Size, 0, EC);
886 EXPECT_EQ(StringRef(mfr.const_data()), Val);
889 fs::mapped_file_region m(FD, fs::mapped_file_region::readonly, Size, 0, EC);
891 ASSERT_EQ(close(FD), 0);
894 TEST(Support, NormalizePath) {
895 #if defined(LLVM_ON_WIN32)
896 #define EXPECT_PATH_IS(path__, windows__, not_windows__) \
897 EXPECT_EQ(path__, windows__);
899 #define EXPECT_PATH_IS(path__, windows__, not_windows__) \
900 EXPECT_EQ(path__, not_windows__);
903 SmallString<64> Path1("a");
904 SmallString<64> Path2("a/b");
905 SmallString<64> Path3("a\\b");
906 SmallString<64> Path4("a\\\\b");
907 SmallString<64> Path5("\\a");
908 SmallString<64> Path6("a\\");
911 EXPECT_PATH_IS(Path1, "a", "a");
914 EXPECT_PATH_IS(Path2, "a\\b", "a/b");
917 EXPECT_PATH_IS(Path3, "a\\b", "a/b");
920 EXPECT_PATH_IS(Path4, "a\\\\b", "a\\\\b");
923 EXPECT_PATH_IS(Path5, "\\a", "/a");
926 EXPECT_PATH_IS(Path6, "a\\", "a/");
928 #undef EXPECT_PATH_IS
931 TEST(Support, RemoveLeadingDotSlash) {
932 StringRef Path1("././/foolz/wat");
933 StringRef Path2("./////");
935 Path1 = path::remove_leading_dotslash(Path1);
936 EXPECT_EQ(Path1, "foolz/wat");
937 Path2 = path::remove_leading_dotslash(Path2);
938 EXPECT_EQ(Path2, "");
941 static std::string remove_dots(StringRef path,
942 bool remove_dot_dot) {
943 SmallString<256> buffer(path);
944 path::remove_dots(buffer, remove_dot_dot);
948 TEST(Support, RemoveDots) {
949 #if defined(LLVM_ON_WIN32)
950 EXPECT_EQ("foolz\\wat", remove_dots(".\\.\\\\foolz\\wat", false));
951 EXPECT_EQ("", remove_dots(".\\\\\\\\\\", false));
953 EXPECT_EQ("a\\..\\b\\c", remove_dots(".\\a\\..\\b\\c", false));
954 EXPECT_EQ("b\\c", remove_dots(".\\a\\..\\b\\c", true));
955 EXPECT_EQ("c", remove_dots(".\\.\\c", true));
957 SmallString<64> Path1(".\\.\\c");
958 EXPECT_TRUE(path::remove_dots(Path1, true));
959 EXPECT_EQ("c", Path1);
961 EXPECT_EQ("foolz/wat", remove_dots("././/foolz/wat", false));
962 EXPECT_EQ("", remove_dots("./////", false));
964 EXPECT_EQ("a/../b/c", remove_dots("./a/../b/c", false));
965 EXPECT_EQ("b/c", remove_dots("./a/../b/c", true));
966 EXPECT_EQ("c", remove_dots("././c", true));
968 SmallString<64> Path1("././c");
969 EXPECT_TRUE(path::remove_dots(Path1, true));
970 EXPECT_EQ("c", Path1);
974 TEST(Support, ReplacePathPrefix) {
975 SmallString<64> Path1("/foo");
976 SmallString<64> Path2("/old/foo");
977 SmallString<64> OldPrefix("/old");
978 SmallString<64> NewPrefix("/new");
979 SmallString<64> NewPrefix2("/longernew");
980 SmallString<64> EmptyPrefix("");
982 SmallString<64> Path = Path1;
983 path::replace_path_prefix(Path, OldPrefix, NewPrefix);
984 EXPECT_EQ(Path, "/foo");
986 path::replace_path_prefix(Path, OldPrefix, NewPrefix);
987 EXPECT_EQ(Path, "/new/foo");
989 path::replace_path_prefix(Path, OldPrefix, NewPrefix2);
990 EXPECT_EQ(Path, "/longernew/foo");
992 path::replace_path_prefix(Path, EmptyPrefix, NewPrefix);
993 EXPECT_EQ(Path, "/new/foo");
995 path::replace_path_prefix(Path, OldPrefix, EmptyPrefix);
996 EXPECT_EQ(Path, "/foo");
999 TEST_F(FileSystemTest, PathFromFD) {
1000 // Create a temp file.
1002 SmallString<64> TempPath;
1004 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
1006 // Make sure it exists.
1007 ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
1009 // Try to get the path from the file descriptor
1010 SmallString<64> ResultPath;
1011 std::error_code ErrorCode =
1012 fs::getPathFromOpenFD(FileDescriptor, ResultPath);
1014 // If we succeeded, check that the paths are the same (modulo case):
1016 // The paths returned by createTemporaryFile and getPathFromOpenFD
1017 // should reference the same file on disk.
1018 fs::UniqueID D1, D2;
1019 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), D1));
1020 ASSERT_NO_ERROR(fs::getUniqueID(Twine(ResultPath), D2));
1024 ::close(FileDescriptor);
1027 TEST_F(FileSystemTest, OpenFileForRead) {
1028 // Create a temp file.
1030 SmallString<64> TempPath;
1032 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
1034 // Make sure it exists.
1035 ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
1037 // Open the file for read
1038 int FileDescriptor2;
1039 SmallString<64> ResultPath;
1041 fs::openFileForRead(Twine(TempPath), FileDescriptor2, &ResultPath))
1043 // If we succeeded, check that the paths are the same (modulo case):
1044 if (!ResultPath.empty()) {
1045 // The paths returned by createTemporaryFile and getPathFromOpenFD
1046 // should reference the same file on disk.
1047 fs::UniqueID D1, D2;
1048 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), D1));
1049 ASSERT_NO_ERROR(fs::getUniqueID(Twine(ResultPath), D2));
1053 ::close(FileDescriptor);
1055 } // anonymous namespace