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"
29 using namespace llvm::sys;
31 #define ASSERT_NO_ERROR(x) \
32 if (std::error_code ASSERT_NO_ERROR_ec = x) { \
33 SmallString<128> MessageStorage; \
34 raw_svector_ostream Message(MessageStorage); \
35 Message << #x ": did not return errc::success.\n" \
36 << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n" \
37 << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \
38 GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \
44 TEST(is_separator, Works) {
45 EXPECT_TRUE(path::is_separator('/'));
46 EXPECT_FALSE(path::is_separator('\0'));
47 EXPECT_FALSE(path::is_separator('-'));
48 EXPECT_FALSE(path::is_separator(' '));
51 EXPECT_TRUE(path::is_separator('\\'));
53 EXPECT_FALSE(path::is_separator('\\'));
58 SmallVector<StringRef, 40> paths;
61 paths.push_back("..");
62 paths.push_back("foo");
64 paths.push_back("/foo");
65 paths.push_back("foo/");
66 paths.push_back("/foo/");
67 paths.push_back("foo/bar");
68 paths.push_back("/foo/bar");
69 paths.push_back("//net");
70 paths.push_back("//net/foo");
71 paths.push_back("///foo///");
72 paths.push_back("///foo///bar");
73 paths.push_back("/.");
74 paths.push_back("./");
75 paths.push_back("/..");
76 paths.push_back("../");
77 paths.push_back("foo/.");
78 paths.push_back("foo/..");
79 paths.push_back("foo/./");
80 paths.push_back("foo/./bar");
81 paths.push_back("foo/..");
82 paths.push_back("foo/../");
83 paths.push_back("foo/../bar");
84 paths.push_back("c:");
85 paths.push_back("c:/");
86 paths.push_back("c:foo");
87 paths.push_back("c:/foo");
88 paths.push_back("c:foo/");
89 paths.push_back("c:/foo/");
90 paths.push_back("c:/foo/bar");
91 paths.push_back("prn:");
92 paths.push_back("c:\\");
93 paths.push_back("c:foo");
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\\bar");
100 SmallVector<StringRef, 5> ComponentStack;
101 for (SmallVector<StringRef, 40>::const_iterator i = paths.begin(),
105 for (sys::path::const_iterator ci = sys::path::begin(*i),
106 ce = sys::path::end(*i);
109 ASSERT_FALSE(ci->empty());
110 ComponentStack.push_back(*ci);
113 for (sys::path::reverse_iterator ci = sys::path::rbegin(*i),
114 ce = sys::path::rend(*i);
117 ASSERT_TRUE(*ci == ComponentStack.back());
118 ComponentStack.pop_back();
120 ASSERT_TRUE(ComponentStack.empty());
122 path::has_root_path(*i);
124 path::has_root_name(*i);
126 path::has_root_directory(*i);
127 path::root_directory(*i);
128 path::has_parent_path(*i);
129 path::parent_path(*i);
130 path::has_filename(*i);
134 path::has_extension(*i);
136 path::is_absolute(*i);
137 path::is_relative(*i);
139 SmallString<128> temp_store;
141 ASSERT_NO_ERROR(fs::make_absolute(temp_store));
143 path::remove_filename(temp_store);
146 path::replace_extension(temp_store, "ext");
147 StringRef filename(temp_store.begin(), temp_store.size()), stem, ext;
148 stem = path::stem(filename);
149 ext = path::extension(filename);
150 EXPECT_EQ(*sys::path::rbegin(filename), (stem + ext).str());
152 path::native(*i, temp_store);
155 SmallString<32> Relative("foo.cpp");
156 ASSERT_NO_ERROR(sys::fs::make_absolute("/root", Relative));
157 Relative[5] = '/'; // Fix up windows paths.
158 ASSERT_EQ("/root/foo.cpp", Relative);
161 TEST(Support, RelativePathIterator) {
162 SmallString<64> Path(StringRef("c/d/e/foo.txt"));
163 typedef SmallVector<StringRef, 4> PathComponents;
164 PathComponents ExpectedPathComponents;
165 PathComponents ActualPathComponents;
167 StringRef(Path).split(ExpectedPathComponents, '/');
169 for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
171 ActualPathComponents.push_back(*I);
174 ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
176 for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
177 EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
181 TEST(Support, RelativePathDotIterator) {
182 SmallString<64> Path(StringRef(".c/.d/../."));
183 typedef SmallVector<StringRef, 4> PathComponents;
184 PathComponents ExpectedPathComponents;
185 PathComponents ActualPathComponents;
187 StringRef(Path).split(ExpectedPathComponents, '/');
189 for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
191 ActualPathComponents.push_back(*I);
194 ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
196 for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
197 EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
201 TEST(Support, AbsolutePathIterator) {
202 SmallString<64> Path(StringRef("/c/d/e/foo.txt"));
203 typedef SmallVector<StringRef, 4> PathComponents;
204 PathComponents ExpectedPathComponents;
205 PathComponents ActualPathComponents;
207 StringRef(Path).split(ExpectedPathComponents, '/');
209 // The root path will also be a component when iterating
210 ExpectedPathComponents[0] = "/";
212 for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
214 ActualPathComponents.push_back(*I);
217 ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
219 for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
220 EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
224 TEST(Support, AbsolutePathDotIterator) {
225 SmallString<64> Path(StringRef("/.c/.d/../."));
226 typedef SmallVector<StringRef, 4> PathComponents;
227 PathComponents ExpectedPathComponents;
228 PathComponents ActualPathComponents;
230 StringRef(Path).split(ExpectedPathComponents, '/');
232 // The root path will also be a component when iterating
233 ExpectedPathComponents[0] = "/";
235 for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
237 ActualPathComponents.push_back(*I);
240 ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
242 for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
243 EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
248 TEST(Support, AbsolutePathIteratorWin32) {
249 SmallString<64> Path(StringRef("c:\\c\\e\\foo.txt"));
250 typedef SmallVector<StringRef, 4> PathComponents;
251 PathComponents ExpectedPathComponents;
252 PathComponents ActualPathComponents;
254 StringRef(Path).split(ExpectedPathComponents, "\\");
256 // The root path (which comes after the drive name) will also be a component
258 ExpectedPathComponents.insert(ExpectedPathComponents.begin()+1, "\\");
260 for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
262 ActualPathComponents.push_back(*I);
265 ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
267 for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
268 EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
271 #endif // LLVM_ON_WIN32
273 TEST(Support, AbsolutePathIteratorEnd) {
274 // Trailing slashes are converted to '.' unless they are part of the root path.
275 SmallVector<StringRef, 4> Paths;
276 Paths.push_back("/foo/");
277 Paths.push_back("/foo//");
278 Paths.push_back("//net//");
280 Paths.push_back("c:\\\\");
283 for (StringRef Path : Paths) {
284 StringRef LastComponent = *path::rbegin(Path);
285 EXPECT_EQ(".", LastComponent);
288 SmallVector<StringRef, 3> RootPaths;
289 RootPaths.push_back("/");
290 RootPaths.push_back("//net/");
292 RootPaths.push_back("c:\\");
295 for (StringRef Path : RootPaths) {
296 StringRef LastComponent = *path::rbegin(Path);
297 EXPECT_EQ(1u, LastComponent.size());
298 EXPECT_TRUE(path::is_separator(LastComponent[0]));
302 TEST(Support, HomeDirectory) {
303 std::string expected;
305 if (wchar_t const *path = ::_wgetenv(L"USERPROFILE")) {
306 auto pathLen = ::wcslen(path);
307 ArrayRef<char> ref{reinterpret_cast<char const *>(path),
308 pathLen * sizeof(wchar_t)};
309 convertUTF16ToUTF8String(ref, expected);
312 if (char const *path = ::getenv("HOME"))
315 // Do not try to test it if we don't know what to expect.
316 // On Windows we use something better than env vars.
317 if (!expected.empty()) {
318 SmallString<128> HomeDir;
319 auto status = path::home_directory(HomeDir);
321 EXPECT_EQ(expected, HomeDir);
325 TEST(Support, UserCacheDirectory) {
326 SmallString<13> CacheDir;
327 SmallString<20> CacheDir2;
328 auto Status = path::user_cache_directory(CacheDir, "");
329 EXPECT_TRUE(Status ^ CacheDir.empty());
332 EXPECT_TRUE(path::user_cache_directory(CacheDir2, "")); // should succeed
333 EXPECT_EQ(CacheDir, CacheDir2); // and return same paths
335 EXPECT_TRUE(path::user_cache_directory(CacheDir, "A", "B", "file.c"));
336 auto It = path::rbegin(CacheDir);
337 EXPECT_EQ("file.c", *It);
338 EXPECT_EQ("B", *++It);
339 EXPECT_EQ("A", *++It);
340 auto ParentDir = *++It;
342 // Test Unicode: "<user_cache_dir>/(pi)r^2/aleth.0"
343 EXPECT_TRUE(path::user_cache_directory(CacheDir2, "\xCF\x80r\xC2\xB2",
345 auto It2 = path::rbegin(CacheDir2);
346 EXPECT_EQ("\xE2\x84\xB5.0", *It2);
347 EXPECT_EQ("\xCF\x80r\xC2\xB2", *++It2);
348 auto ParentDir2 = *++It2;
350 EXPECT_EQ(ParentDir, ParentDir2);
354 TEST(Support, TempDirectory) {
355 SmallString<32> TempDir;
356 path::system_temp_directory(false, TempDir);
357 EXPECT_TRUE(!TempDir.empty());
359 path::system_temp_directory(true, TempDir);
360 EXPECT_TRUE(!TempDir.empty());
364 static std::string path2regex(std::string Path) {
366 while ((Pos = Path.find('\\', Pos)) != std::string::npos) {
367 Path.replace(Pos, 1, "\\\\");
373 /// Helper for running temp dir test in separated process. See below.
374 #define EXPECT_TEMP_DIR(prepare, expected) \
378 SmallString<300> TempDir; \
379 path::system_temp_directory(true, TempDir); \
380 raw_os_ostream(std::cerr) << TempDir; \
383 ::testing::ExitedWithCode(0), path2regex(expected))
385 TEST(SupportDeathTest, TempDirectoryOnWindows) {
386 // In this test we want to check how system_temp_directory responds to
387 // different values of specific env vars. To prevent corrupting env vars of
388 // the current process all checks are done in separated processes.
389 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"C:\\OtherFolder"), "C:\\OtherFolder");
390 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"C:/Unix/Path/Seperators"),
391 "C:\\Unix\\Path\\Seperators");
392 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"Local Path"), ".+\\Local Path$");
393 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"F:\\TrailingSep\\"), "F:\\TrailingSep");
395 _wputenv_s(L"TMP", L"C:\\2\x03C0r-\x00B5\x00B3\\\x2135\x2080"),
396 "C:\\2\xCF\x80r-\xC2\xB5\xC2\xB3\\\xE2\x84\xB5\xE2\x82\x80");
398 // Test $TMP empty, $TEMP set.
401 _wputenv_s(L"TMP", L"");
402 _wputenv_s(L"TEMP", L"C:\\Valid\\Path");
406 // All related env vars empty
409 _wputenv_s(L"TMP", L"");
410 _wputenv_s(L"TEMP", L"");
411 _wputenv_s(L"USERPROFILE", L"");
415 // Test evn var / path with 260 chars.
416 SmallString<270> Expected{"C:\\Temp\\AB\\123456789"};
417 while (Expected.size() < 260)
418 Expected.append("\\DirNameWith19Charss");
419 ASSERT_EQ(260, Expected.size());
420 EXPECT_TEMP_DIR(_putenv_s("TMP", Expected.c_str()), Expected.c_str());
424 class FileSystemTest : public testing::Test {
426 /// Unique temporary directory in which all created filesystem entities must
427 /// be placed. It is removed at the end of each test (must be empty).
428 SmallString<128> TestDirectory;
430 void SetUp() override {
432 fs::createUniqueDirectory("file-system-test", TestDirectory));
433 // We don't care about this specific file.
434 errs() << "Test Directory: " << TestDirectory << '\n';
438 void TearDown() override { ASSERT_NO_ERROR(fs::remove(TestDirectory.str())); }
441 TEST_F(FileSystemTest, Unique) {
442 // Create a temp file.
444 SmallString<64> TempPath;
446 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
448 // The same file should return an identical unique id.
450 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F1));
451 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F2));
454 // Different files should return different unique ids.
456 SmallString<64> TempPath2;
458 fs::createTemporaryFile("prefix", "temp", FileDescriptor2, TempPath2));
461 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D));
463 ::close(FileDescriptor2);
465 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
467 // Two paths representing the same file on disk should still provide the
468 // same unique id. We can test this by making a hard link.
469 ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2)));
471 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D2));
474 ::close(FileDescriptor);
476 SmallString<128> Dir1;
478 fs::createUniqueDirectory("dir1", Dir1));
479 ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F1));
480 ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F2));
483 SmallString<128> Dir2;
485 fs::createUniqueDirectory("dir2", Dir2));
486 ASSERT_NO_ERROR(fs::getUniqueID(Dir2.c_str(), F2));
490 TEST_F(FileSystemTest, TempFiles) {
491 // Create a temp file.
493 SmallString<64> TempPath;
495 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
497 // Make sure it exists.
498 ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
500 // Create another temp tile.
502 SmallString<64> TempPath2;
503 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD2, TempPath2));
504 ASSERT_TRUE(TempPath2.endswith(".temp"));
505 ASSERT_NE(TempPath.str(), TempPath2.str());
507 fs::file_status A, B;
508 ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
509 ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
510 EXPECT_FALSE(fs::equivalent(A, B));
515 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
516 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
517 ASSERT_EQ(fs::remove(Twine(TempPath2), false),
518 errc::no_such_file_or_directory);
520 std::error_code EC = fs::status(TempPath2.c_str(), B);
521 EXPECT_EQ(EC, errc::no_such_file_or_directory);
522 EXPECT_EQ(B.type(), fs::file_type::file_not_found);
524 // Make sure Temp2 doesn't exist.
525 ASSERT_EQ(fs::access(Twine(TempPath2), sys::fs::AccessMode::Exist),
526 errc::no_such_file_or_directory);
528 SmallString<64> TempPath3;
529 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "", TempPath3));
530 ASSERT_FALSE(TempPath3.endswith("."));
532 // Create a hard link to Temp1.
533 ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2)));
535 ASSERT_NO_ERROR(fs::equivalent(Twine(TempPath), Twine(TempPath2), equal));
537 ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
538 ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
539 EXPECT_TRUE(fs::equivalent(A, B));
542 ::close(FileDescriptor);
543 ASSERT_NO_ERROR(fs::remove(Twine(TempPath)));
545 // Remove the hard link.
546 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
548 // Make sure Temp1 doesn't exist.
549 ASSERT_EQ(fs::access(Twine(TempPath), sys::fs::AccessMode::Exist),
550 errc::no_such_file_or_directory);
553 // Path name > 260 chars should get an error.
554 const char *Path270 =
555 "abcdefghijklmnopqrstuvwxyz9abcdefghijklmnopqrstuvwxyz8"
556 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
557 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
558 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
559 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
560 EXPECT_EQ(fs::createUniqueFile(Path270, FileDescriptor, TempPath),
561 errc::invalid_argument);
562 // Relative path < 247 chars, no problem.
563 const char *Path216 =
564 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
565 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
566 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
567 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
568 ASSERT_NO_ERROR(fs::createTemporaryFile(Path216, "", TempPath));
569 ASSERT_NO_ERROR(fs::remove(Twine(TempPath)));
573 TEST_F(FileSystemTest, CreateDir) {
574 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
575 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
576 ASSERT_EQ(fs::create_directory(Twine(TestDirectory) + "foo", false),
578 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "foo"));
581 // Set a 0000 umask so that we can test our directory permissions.
582 mode_t OldUmask = ::umask(0000);
584 fs::file_status Status;
586 fs::create_directory(Twine(TestDirectory) + "baz500", false,
587 fs::perms::owner_read | fs::perms::owner_exe));
588 ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz500", Status));
589 ASSERT_EQ(Status.permissions() & fs::perms::all_all,
590 fs::perms::owner_read | fs::perms::owner_exe);
591 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "baz777", false,
592 fs::perms::all_all));
593 ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz777", Status));
594 ASSERT_EQ(Status.permissions() & fs::perms::all_all, fs::perms::all_all);
596 // Restore umask to be safe.
601 // Prove that create_directories() can handle a pathname > 248 characters,
602 // which is the documented limit for CreateDirectory().
603 // (248 is MAX_PATH subtracting room for an 8.3 filename.)
604 // Generate a directory path guaranteed to fall into that range.
605 size_t TmpLen = TestDirectory.size();
606 const char *OneDir = "\\123456789";
607 size_t OneDirLen = strlen(OneDir);
608 ASSERT_LT(OneDirLen, 12U);
609 size_t NLevels = ((248 - TmpLen) / OneDirLen) + 1;
610 SmallString<260> LongDir(TestDirectory);
611 for (size_t I = 0; I < NLevels; ++I)
612 LongDir.append(OneDir);
613 ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir)));
614 ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir)));
615 ASSERT_EQ(fs::create_directories(Twine(LongDir), false),
617 // Tidy up, "recursively" removing the directories.
618 StringRef ThisDir(LongDir);
619 for (size_t J = 0; J < NLevels; ++J) {
620 ASSERT_NO_ERROR(fs::remove(ThisDir));
621 ThisDir = path::parent_path(ThisDir);
624 // Similarly for a relative pathname. Need to set the current directory to
625 // TestDirectory so that the one we create ends up in the right place.
626 char PreviousDir[260];
627 size_t PreviousDirLen = ::GetCurrentDirectoryA(260, PreviousDir);
628 ASSERT_GT(PreviousDirLen, 0U);
629 ASSERT_LT(PreviousDirLen, 260U);
630 ASSERT_NE(::SetCurrentDirectoryA(TestDirectory.c_str()), 0);
632 // Generate a relative directory name with absolute length > 248.
633 size_t LongDirLen = 249 - TestDirectory.size();
634 LongDir.assign(LongDirLen, 'a');
635 ASSERT_NO_ERROR(fs::create_directory(Twine(LongDir)));
636 // While we're here, prove that .. and . handling works in these long paths.
637 const char *DotDotDirs = "\\..\\.\\b";
638 LongDir.append(DotDotDirs);
639 ASSERT_NO_ERROR(fs::create_directory("b"));
640 ASSERT_EQ(fs::create_directory(Twine(LongDir), false), errc::file_exists);
642 ASSERT_NO_ERROR(fs::remove("b"));
643 ASSERT_NO_ERROR(fs::remove(
644 Twine(LongDir.substr(0, LongDir.size() - strlen(DotDotDirs)))));
645 ASSERT_NE(::SetCurrentDirectoryA(PreviousDir), 0);
649 TEST_F(FileSystemTest, DirectoryIteration) {
651 for (fs::directory_iterator i(".", ec), e; i != e; i.increment(ec))
654 // Create a known hierarchy to recurse over.
656 fs::create_directories(Twine(TestDirectory) + "/recursive/a0/aa1"));
658 fs::create_directories(Twine(TestDirectory) + "/recursive/a0/ab1"));
659 ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) +
660 "/recursive/dontlookhere/da1"));
662 fs::create_directories(Twine(TestDirectory) + "/recursive/z0/za1"));
664 fs::create_directories(Twine(TestDirectory) + "/recursive/pop/p1"));
665 typedef std::vector<std::string> v_t;
667 for (fs::recursive_directory_iterator i(Twine(TestDirectory)
668 + "/recursive", ec), e; i != e; i.increment(ec)){
670 if (path::filename(i->path()) == "p1") {
672 // FIXME: recursive_directory_iterator should be more robust.
675 if (path::filename(i->path()) == "dontlookhere")
677 visited.push_back(path::filename(i->path()));
679 v_t::const_iterator a0 = std::find(visited.begin(), visited.end(), "a0");
680 v_t::const_iterator aa1 = std::find(visited.begin(), visited.end(), "aa1");
681 v_t::const_iterator ab1 = std::find(visited.begin(), visited.end(), "ab1");
682 v_t::const_iterator dontlookhere = std::find(visited.begin(), visited.end(),
684 v_t::const_iterator da1 = std::find(visited.begin(), visited.end(), "da1");
685 v_t::const_iterator z0 = std::find(visited.begin(), visited.end(), "z0");
686 v_t::const_iterator za1 = std::find(visited.begin(), visited.end(), "za1");
687 v_t::const_iterator pop = std::find(visited.begin(), visited.end(), "pop");
688 v_t::const_iterator p1 = std::find(visited.begin(), visited.end(), "p1");
690 // Make sure that each path was visited correctly.
691 ASSERT_NE(a0, visited.end());
692 ASSERT_NE(aa1, visited.end());
693 ASSERT_NE(ab1, visited.end());
694 ASSERT_NE(dontlookhere, visited.end());
695 ASSERT_EQ(da1, visited.end()); // Not visited.
696 ASSERT_NE(z0, visited.end());
697 ASSERT_NE(za1, visited.end());
698 ASSERT_NE(pop, visited.end());
699 ASSERT_EQ(p1, visited.end()); // Not visited.
701 // Make sure that parents were visited before children. No other ordering
702 // guarantees can be made across siblings.
707 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/aa1"));
708 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/ab1"));
709 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0"));
711 fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere/da1"));
712 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere"));
713 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop/p1"));
714 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop"));
715 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0/za1"));
716 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0"));
717 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive"));
720 const char archive[] = "!<arch>\x0A";
721 const char bitcode[] = "\xde\xc0\x17\x0b";
722 const char coff_object[] = "\x00\x00......";
723 const char coff_bigobj[] = "\x00\x00\xff\xff\x00\x02......"
724 "\xc7\xa1\xba\xd1\xee\xba\xa9\x4b\xaf\x20\xfa\xf6\x6a\xa4\xdc\xb8";
725 const char coff_import_library[] = "\x00\x00\xff\xff....";
726 const char elf_relocatable[] = { 0x7f, 'E', 'L', 'F', 1, 2, 1, 0, 0,
727 0, 0, 0, 0, 0, 0, 0, 0, 1 };
728 const char macho_universal_binary[] = "\xca\xfe\xba\xbe...\0x00";
729 const char macho_object[] = "\xfe\xed\xfa\xce..........\x00\x01";
730 const char macho_executable[] = "\xfe\xed\xfa\xce..........\x00\x02";
731 const char macho_fixed_virtual_memory_shared_lib[] =
732 "\xfe\xed\xfa\xce..........\x00\x03";
733 const char macho_core[] = "\xfe\xed\xfa\xce..........\x00\x04";
734 const char macho_preload_executable[] = "\xfe\xed\xfa\xce..........\x00\x05";
735 const char macho_dynamically_linked_shared_lib[] =
736 "\xfe\xed\xfa\xce..........\x00\x06";
737 const char macho_dynamic_linker[] = "\xfe\xed\xfa\xce..........\x00\x07";
738 const char macho_bundle[] = "\xfe\xed\xfa\xce..........\x00\x08";
739 const char macho_dsym_companion[] = "\xfe\xed\xfa\xce..........\x00\x0a";
740 const char macho_kext_bundle[] = "\xfe\xed\xfa\xce..........\x00\x0b";
741 const char windows_resource[] = "\x00\x00\x00\x00\x020\x00\x00\x00\xff";
742 const char macho_dynamically_linked_shared_lib_stub[] =
743 "\xfe\xed\xfa\xce..........\x00\x09";
745 TEST_F(FileSystemTest, Magic) {
747 const char *filename;
748 const char *magic_str;
749 size_t magic_str_len;
750 fs::file_magic magic;
752 #define DEFINE(magic) \
753 { #magic, magic, sizeof(magic), fs::file_magic::magic }
757 { "coff_bigobj", coff_bigobj, sizeof(coff_bigobj), fs::file_magic::coff_object },
758 DEFINE(coff_import_library),
759 DEFINE(elf_relocatable),
760 DEFINE(macho_universal_binary),
761 DEFINE(macho_object),
762 DEFINE(macho_executable),
763 DEFINE(macho_fixed_virtual_memory_shared_lib),
765 DEFINE(macho_preload_executable),
766 DEFINE(macho_dynamically_linked_shared_lib),
767 DEFINE(macho_dynamic_linker),
768 DEFINE(macho_bundle),
769 DEFINE(macho_dynamically_linked_shared_lib_stub),
770 DEFINE(macho_dsym_companion),
771 DEFINE(macho_kext_bundle),
772 DEFINE(windows_resource)
776 // Create some files filled with magic.
777 for (type *i = types, *e = types + (sizeof(types) / sizeof(type)); i != e;
779 SmallString<128> file_pathname(TestDirectory);
780 path::append(file_pathname, i->filename);
782 raw_fd_ostream file(file_pathname, EC, sys::fs::F_None);
783 ASSERT_FALSE(file.has_error());
784 StringRef magic(i->magic_str, i->magic_str_len);
787 EXPECT_EQ(i->magic, fs::identify_magic(magic));
788 ASSERT_NO_ERROR(fs::remove(Twine(file_pathname)));
793 TEST_F(FileSystemTest, CarriageReturn) {
794 SmallString<128> FilePathname(TestDirectory);
796 path::append(FilePathname, "test");
799 raw_fd_ostream File(FilePathname, EC, sys::fs::F_Text);
804 auto Buf = MemoryBuffer::getFile(FilePathname.str());
805 EXPECT_TRUE((bool)Buf);
806 EXPECT_EQ(Buf.get()->getBuffer(), "\r\n");
810 raw_fd_ostream File(FilePathname, EC, sys::fs::F_None);
815 auto Buf = MemoryBuffer::getFile(FilePathname.str());
816 EXPECT_TRUE((bool)Buf);
817 EXPECT_EQ(Buf.get()->getBuffer(), "\n");
819 ASSERT_NO_ERROR(fs::remove(Twine(FilePathname)));
823 TEST_F(FileSystemTest, Resize) {
825 SmallString<64> TempPath;
826 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
827 ASSERT_NO_ERROR(fs::resize_file(FD, 123));
828 fs::file_status Status;
829 ASSERT_NO_ERROR(fs::status(FD, Status));
830 ASSERT_EQ(Status.getSize(), 123U);
833 TEST_F(FileSystemTest, FileMapping) {
834 // Create a temp file.
836 SmallString<64> TempPath;
838 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
839 unsigned Size = 4096;
840 ASSERT_NO_ERROR(fs::resize_file(FileDescriptor, Size));
842 // Map in temp file and add some content
844 StringRef Val("hello there");
846 fs::mapped_file_region mfr(FileDescriptor,
847 fs::mapped_file_region::readwrite, Size, 0, EC);
849 std::copy(Val.begin(), Val.end(), mfr.data());
850 // Explicitly add a 0.
851 mfr.data()[Val.size()] = 0;
855 // Map it back in read-only
857 EC = fs::openFileForRead(Twine(TempPath), FD);
859 fs::mapped_file_region mfr(FD, fs::mapped_file_region::readonly, Size, 0, EC);
863 EXPECT_EQ(StringRef(mfr.const_data()), Val);
866 fs::mapped_file_region m(FD, fs::mapped_file_region::readonly, Size, 0, EC);
868 ASSERT_EQ(close(FD), 0);
871 TEST(Support, NormalizePath) {
872 #if defined(LLVM_ON_WIN32)
873 #define EXPECT_PATH_IS(path__, windows__, not_windows__) \
874 EXPECT_EQ(path__, windows__);
876 #define EXPECT_PATH_IS(path__, windows__, not_windows__) \
877 EXPECT_EQ(path__, not_windows__);
880 SmallString<64> Path1("a");
881 SmallString<64> Path2("a/b");
882 SmallString<64> Path3("a\\b");
883 SmallString<64> Path4("a\\\\b");
884 SmallString<64> Path5("\\a");
885 SmallString<64> Path6("a\\");
888 EXPECT_PATH_IS(Path1, "a", "a");
891 EXPECT_PATH_IS(Path2, "a\\b", "a/b");
894 EXPECT_PATH_IS(Path3, "a\\b", "a/b");
897 EXPECT_PATH_IS(Path4, "a\\\\b", "a\\\\b");
900 EXPECT_PATH_IS(Path5, "\\a", "/a");
903 EXPECT_PATH_IS(Path6, "a\\", "a/");
905 #undef EXPECT_PATH_IS
908 TEST(Support, RemoveLeadingDotSlash) {
909 StringRef Path1("././/foolz/wat");
910 StringRef Path2("./////");
912 Path1 = path::remove_leading_dotslash(Path1);
913 EXPECT_EQ(Path1, "foolz/wat");
914 Path2 = path::remove_leading_dotslash(Path2);
915 EXPECT_EQ(Path2, "");
918 static std::string remove_dots(StringRef path,
919 bool remove_dot_dot) {
920 SmallString<256> buffer(path);
921 path::remove_dots(buffer, remove_dot_dot);
925 TEST(Support, RemoveDots) {
926 #if defined(LLVM_ON_WIN32)
927 EXPECT_EQ("foolz\\wat", remove_dots(".\\.\\\\foolz\\wat", false));
928 EXPECT_EQ("", remove_dots(".\\\\\\\\\\", false));
930 EXPECT_EQ("a\\..\\b\\c", remove_dots(".\\a\\..\\b\\c", false));
931 EXPECT_EQ("b\\c", remove_dots(".\\a\\..\\b\\c", true));
932 EXPECT_EQ("c", remove_dots(".\\.\\c", true));
934 SmallString<64> Path1(".\\.\\c");
935 EXPECT_TRUE(path::remove_dots(Path1, true));
936 EXPECT_EQ("c", Path1);
938 EXPECT_EQ("foolz/wat", remove_dots("././/foolz/wat", false));
939 EXPECT_EQ("", remove_dots("./////", false));
941 EXPECT_EQ("a/../b/c", remove_dots("./a/../b/c", false));
942 EXPECT_EQ("b/c", remove_dots("./a/../b/c", true));
943 EXPECT_EQ("c", remove_dots("././c", true));
945 SmallString<64> Path1("././c");
946 EXPECT_TRUE(path::remove_dots(Path1, true));
947 EXPECT_EQ("c", Path1);
950 } // anonymous namespace