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/Errc.h"
12 #include "llvm/Support/ErrorHandling.h"
13 #include "llvm/Support/FileSystem.h"
14 #include "llvm/Support/MemoryBuffer.h"
15 #include "llvm/Support/raw_ostream.h"
16 #include "gtest/gtest.h"
23 using namespace llvm::sys;
25 #define ASSERT_NO_ERROR(x) \
26 if (std::error_code ASSERT_NO_ERROR_ec = x) { \
27 SmallString<128> MessageStorage; \
28 raw_svector_ostream Message(MessageStorage); \
29 Message << #x ": did not return errc::success.\n" \
30 << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n" \
31 << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \
32 GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \
38 TEST(is_separator, Works) {
39 EXPECT_TRUE(path::is_separator('/'));
40 EXPECT_FALSE(path::is_separator('\0'));
41 EXPECT_FALSE(path::is_separator('-'));
42 EXPECT_FALSE(path::is_separator(' '));
45 EXPECT_TRUE(path::is_separator('\\'));
47 EXPECT_FALSE(path::is_separator('\\'));
52 SmallVector<StringRef, 40> paths;
55 paths.push_back("..");
56 paths.push_back("foo");
58 paths.push_back("/foo");
59 paths.push_back("foo/");
60 paths.push_back("/foo/");
61 paths.push_back("foo/bar");
62 paths.push_back("/foo/bar");
63 paths.push_back("//net");
64 paths.push_back("//net/foo");
65 paths.push_back("///foo///");
66 paths.push_back("///foo///bar");
67 paths.push_back("/.");
68 paths.push_back("./");
69 paths.push_back("/..");
70 paths.push_back("../");
71 paths.push_back("foo/.");
72 paths.push_back("foo/..");
73 paths.push_back("foo/./");
74 paths.push_back("foo/./bar");
75 paths.push_back("foo/..");
76 paths.push_back("foo/../");
77 paths.push_back("foo/../bar");
78 paths.push_back("c:");
79 paths.push_back("c:/");
80 paths.push_back("c:foo");
81 paths.push_back("c:/foo");
82 paths.push_back("c:foo/");
83 paths.push_back("c:/foo/");
84 paths.push_back("c:/foo/bar");
85 paths.push_back("prn:");
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/");
92 paths.push_back("c:/foo\\bar");
94 SmallVector<StringRef, 5> ComponentStack;
95 for (SmallVector<StringRef, 40>::const_iterator i = paths.begin(),
99 for (sys::path::const_iterator ci = sys::path::begin(*i),
100 ce = sys::path::end(*i);
103 ASSERT_FALSE(ci->empty());
104 ComponentStack.push_back(*ci);
107 for (sys::path::reverse_iterator ci = sys::path::rbegin(*i),
108 ce = sys::path::rend(*i);
111 ASSERT_TRUE(*ci == ComponentStack.back());
112 ComponentStack.pop_back();
114 ASSERT_TRUE(ComponentStack.empty());
116 path::has_root_path(*i);
118 path::has_root_name(*i);
120 path::has_root_directory(*i);
121 path::root_directory(*i);
122 path::has_parent_path(*i);
123 path::parent_path(*i);
124 path::has_filename(*i);
128 path::has_extension(*i);
130 path::is_absolute(*i);
131 path::is_relative(*i);
133 SmallString<128> temp_store;
135 ASSERT_NO_ERROR(fs::make_absolute(temp_store));
137 path::remove_filename(temp_store);
140 path::replace_extension(temp_store, "ext");
141 StringRef filename(temp_store.begin(), temp_store.size()), stem, ext;
142 stem = path::stem(filename);
143 ext = path::extension(filename);
144 EXPECT_EQ(*sys::path::rbegin(filename), (stem + ext).str());
146 path::native(*i, temp_store);
150 TEST(Support, RelativePathIterator) {
151 SmallString<64> Path(StringRef("c/d/e/foo.txt"));
152 typedef SmallVector<StringRef, 4> PathComponents;
153 PathComponents ExpectedPathComponents;
154 PathComponents ActualPathComponents;
156 StringRef(Path).split(ExpectedPathComponents, "/");
158 for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
160 ActualPathComponents.push_back(*I);
163 ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
165 for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
166 EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
170 TEST(Support, AbsolutePathIterator) {
171 SmallString<64> Path(StringRef("/c/d/e/foo.txt"));
172 typedef SmallVector<StringRef, 4> PathComponents;
173 PathComponents ExpectedPathComponents;
174 PathComponents ActualPathComponents;
176 StringRef(Path).split(ExpectedPathComponents, "/");
178 // The root path will also be a component when iterating
179 ExpectedPathComponents[0] = "/";
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());
194 TEST(Support, AbsolutePathIteratorWin32) {
195 SmallString<64> Path(StringRef("c:\\c\\e\\foo.txt"));
196 typedef SmallVector<StringRef, 4> PathComponents;
197 PathComponents ExpectedPathComponents;
198 PathComponents ActualPathComponents;
200 StringRef(Path).split(ExpectedPathComponents, "\\");
202 // The root path (which comes after the drive name) will also be a component
204 ExpectedPathComponents.insert(ExpectedPathComponents.begin()+1, "\\");
206 for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
208 ActualPathComponents.push_back(*I);
211 ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
213 for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
214 EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
217 #endif // LLVM_ON_WIN32
219 TEST(Support, AbsolutePathIteratorEnd) {
220 // Trailing slashes are converted to '.' unless they are part of the root path.
221 SmallVector<StringRef, 4> Paths;
222 Paths.push_back("/foo/");
223 Paths.push_back("/foo//");
224 Paths.push_back("//net//");
226 Paths.push_back("c:\\\\");
229 for (StringRef Path : Paths) {
230 StringRef LastComponent = *path::rbegin(Path);
231 EXPECT_EQ(".", LastComponent);
234 SmallVector<StringRef, 3> RootPaths;
235 RootPaths.push_back("/");
236 RootPaths.push_back("//net/");
238 RootPaths.push_back("c:\\");
241 for (StringRef Path : RootPaths) {
242 StringRef LastComponent = *path::rbegin(Path);
243 EXPECT_EQ(1u, LastComponent.size());
244 EXPECT_TRUE(path::is_separator(LastComponent[0]));
248 TEST(Support, HomeDirectory) {
250 // This test only makes sense on Unix if $HOME is set.
251 if (::getenv("HOME")) {
253 SmallString<128> HomeDir;
254 EXPECT_TRUE(path::home_directory(HomeDir));
255 EXPECT_FALSE(HomeDir.empty());
261 class FileSystemTest : public testing::Test {
263 /// Unique temporary directory in which all created filesystem entities must
264 /// be placed. It is recursively removed at the end of each test.
265 SmallString<128> TestDirectory;
267 virtual void SetUp() {
269 fs::createUniqueDirectory("file-system-test", TestDirectory));
270 // We don't care about this specific file.
271 errs() << "Test Directory: " << TestDirectory << '\n';
275 virtual void TearDown() {
276 ASSERT_NO_ERROR(fs::remove(TestDirectory.str()));
280 TEST_F(FileSystemTest, Unique) {
281 // Create a temp file.
283 SmallString<64> TempPath;
285 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
287 // The same file should return an identical unique id.
289 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F1));
290 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F2));
293 // Different files should return different unique ids.
295 SmallString<64> TempPath2;
297 fs::createTemporaryFile("prefix", "temp", FileDescriptor2, TempPath2));
300 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D));
302 ::close(FileDescriptor2);
304 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
306 // Two paths representing the same file on disk should still provide the
307 // same unique id. We can test this by making a hard link.
308 ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2)));
310 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D2));
313 ::close(FileDescriptor);
315 SmallString<128> Dir1;
317 fs::createUniqueDirectory("dir1", Dir1));
318 ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F1));
319 ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F2));
322 SmallString<128> Dir2;
324 fs::createUniqueDirectory("dir2", Dir2));
325 ASSERT_NO_ERROR(fs::getUniqueID(Dir2.c_str(), F2));
329 TEST_F(FileSystemTest, TempFiles) {
330 // Create a temp file.
332 SmallString<64> TempPath;
334 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
336 // Make sure it exists.
337 ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
339 // Create another temp tile.
341 SmallString<64> TempPath2;
342 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD2, TempPath2));
343 ASSERT_TRUE(TempPath2.endswith(".temp"));
344 ASSERT_NE(TempPath.str(), TempPath2.str());
346 fs::file_status A, B;
347 ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
348 ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
349 EXPECT_FALSE(fs::equivalent(A, B));
354 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
355 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
356 ASSERT_EQ(fs::remove(Twine(TempPath2), false),
357 errc::no_such_file_or_directory);
359 std::error_code EC = fs::status(TempPath2.c_str(), B);
360 EXPECT_EQ(EC, errc::no_such_file_or_directory);
361 EXPECT_EQ(B.type(), fs::file_type::file_not_found);
363 // Make sure Temp2 doesn't exist.
364 ASSERT_EQ(fs::access(Twine(TempPath2), sys::fs::AccessMode::Exist),
365 errc::no_such_file_or_directory);
367 SmallString<64> TempPath3;
368 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "", TempPath3));
369 ASSERT_FALSE(TempPath3.endswith("."));
371 // Create a hard link to Temp1.
372 ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2)));
374 ASSERT_NO_ERROR(fs::equivalent(Twine(TempPath), Twine(TempPath2), equal));
376 ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
377 ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
378 EXPECT_TRUE(fs::equivalent(A, B));
381 ::close(FileDescriptor);
382 ASSERT_NO_ERROR(fs::remove(Twine(TempPath)));
384 // Remove the hard link.
385 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
387 // Make sure Temp1 doesn't exist.
388 ASSERT_EQ(fs::access(Twine(TempPath), sys::fs::AccessMode::Exist),
389 errc::no_such_file_or_directory);
392 // Path name > 260 chars should get an error.
393 const char *Path270 =
394 "abcdefghijklmnopqrstuvwxyz9abcdefghijklmnopqrstuvwxyz8"
395 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
396 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
397 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
398 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
399 EXPECT_EQ(fs::createUniqueFile(Twine(Path270), FileDescriptor, TempPath),
400 errc::no_such_file_or_directory);
404 TEST_F(FileSystemTest, CreateDir) {
405 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
406 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
407 ASSERT_EQ(fs::create_directory(Twine(TestDirectory) + "foo", false),
409 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "foo"));
412 TEST_F(FileSystemTest, DirectoryIteration) {
414 for (fs::directory_iterator i(".", ec), e; i != e; i.increment(ec))
417 // Create a known hierarchy to recurse over.
419 fs::create_directories(Twine(TestDirectory) + "/recursive/a0/aa1"));
421 fs::create_directories(Twine(TestDirectory) + "/recursive/a0/ab1"));
422 ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) +
423 "/recursive/dontlookhere/da1"));
425 fs::create_directories(Twine(TestDirectory) + "/recursive/z0/za1"));
427 fs::create_directories(Twine(TestDirectory) + "/recursive/pop/p1"));
428 typedef std::vector<std::string> v_t;
430 for (fs::recursive_directory_iterator i(Twine(TestDirectory)
431 + "/recursive", ec), e; i != e; i.increment(ec)){
433 if (path::filename(i->path()) == "p1") {
435 // FIXME: recursive_directory_iterator should be more robust.
438 if (path::filename(i->path()) == "dontlookhere")
440 visited.push_back(path::filename(i->path()));
442 v_t::const_iterator a0 = std::find(visited.begin(), visited.end(), "a0");
443 v_t::const_iterator aa1 = std::find(visited.begin(), visited.end(), "aa1");
444 v_t::const_iterator ab1 = std::find(visited.begin(), visited.end(), "ab1");
445 v_t::const_iterator dontlookhere = std::find(visited.begin(), visited.end(),
447 v_t::const_iterator da1 = std::find(visited.begin(), visited.end(), "da1");
448 v_t::const_iterator z0 = std::find(visited.begin(), visited.end(), "z0");
449 v_t::const_iterator za1 = std::find(visited.begin(), visited.end(), "za1");
450 v_t::const_iterator pop = std::find(visited.begin(), visited.end(), "pop");
451 v_t::const_iterator p1 = std::find(visited.begin(), visited.end(), "p1");
453 // Make sure that each path was visited correctly.
454 ASSERT_NE(a0, visited.end());
455 ASSERT_NE(aa1, visited.end());
456 ASSERT_NE(ab1, visited.end());
457 ASSERT_NE(dontlookhere, visited.end());
458 ASSERT_EQ(da1, visited.end()); // Not visited.
459 ASSERT_NE(z0, visited.end());
460 ASSERT_NE(za1, visited.end());
461 ASSERT_NE(pop, visited.end());
462 ASSERT_EQ(p1, visited.end()); // Not visited.
464 // Make sure that parents were visited before children. No other ordering
465 // guarantees can be made across siblings.
470 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/aa1"));
471 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/ab1"));
472 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0"));
474 fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere/da1"));
475 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere"));
476 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop/p1"));
477 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop"));
478 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0/za1"));
479 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0"));
480 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive"));
483 const char archive[] = "!<arch>\x0A";
484 const char bitcode[] = "\xde\xc0\x17\x0b";
485 const char coff_object[] = "\x00\x00......";
486 const char coff_import_library[] = "\x00\x00\xff\xff....";
487 const char elf_relocatable[] = { 0x7f, 'E', 'L', 'F', 1, 2, 1, 0, 0,
488 0, 0, 0, 0, 0, 0, 0, 0, 1 };
489 const char macho_universal_binary[] = "\xca\xfe\xba\xbe...\0x00";
490 const char macho_object[] = "\xfe\xed\xfa\xce..........\x00\x01";
491 const char macho_executable[] = "\xfe\xed\xfa\xce..........\x00\x02";
492 const char macho_fixed_virtual_memory_shared_lib[] =
493 "\xfe\xed\xfa\xce..........\x00\x03";
494 const char macho_core[] = "\xfe\xed\xfa\xce..........\x00\x04";
495 const char macho_preload_executable[] = "\xfe\xed\xfa\xce..........\x00\x05";
496 const char macho_dynamically_linked_shared_lib[] =
497 "\xfe\xed\xfa\xce..........\x00\x06";
498 const char macho_dynamic_linker[] = "\xfe\xed\xfa\xce..........\x00\x07";
499 const char macho_bundle[] = "\xfe\xed\xfa\xce..........\x00\x08";
500 const char macho_dsym_companion[] = "\xfe\xed\xfa\xce..........\x00\x0a";
501 const char windows_resource[] = "\x00\x00\x00\x00\x020\x00\x00\x00\xff";
503 TEST_F(FileSystemTest, Magic) {
505 const char *filename;
506 const char *magic_str;
507 size_t magic_str_len;
508 fs::file_magic magic;
510 #define DEFINE(magic) \
511 { #magic, magic, sizeof(magic), fs::file_magic::magic }
515 DEFINE(coff_import_library),
516 DEFINE(elf_relocatable),
517 DEFINE(macho_universal_binary),
518 DEFINE(macho_object),
519 DEFINE(macho_executable),
520 DEFINE(macho_fixed_virtual_memory_shared_lib),
522 DEFINE(macho_preload_executable),
523 DEFINE(macho_dynamically_linked_shared_lib),
524 DEFINE(macho_dynamic_linker),
525 DEFINE(macho_bundle),
526 DEFINE(macho_dsym_companion),
527 DEFINE(windows_resource)
531 // Create some files filled with magic.
532 for (type *i = types, *e = types + (sizeof(types) / sizeof(type)); i != e;
534 SmallString<128> file_pathname(TestDirectory);
535 path::append(file_pathname, i->filename);
537 raw_fd_ostream file(file_pathname, EC, sys::fs::F_None);
538 ASSERT_FALSE(file.has_error());
539 StringRef magic(i->magic_str, i->magic_str_len);
542 EXPECT_EQ(i->magic, fs::identify_magic(magic));
543 ASSERT_NO_ERROR(fs::remove(Twine(file_pathname)));
548 TEST_F(FileSystemTest, CarriageReturn) {
549 SmallString<128> FilePathname(TestDirectory);
551 path::append(FilePathname, "test");
554 raw_fd_ostream File(FilePathname, EC, sys::fs::F_Text);
559 auto Buf = MemoryBuffer::getFile(FilePathname.str());
560 EXPECT_TRUE((bool)Buf);
561 EXPECT_EQ(Buf.get()->getBuffer(), "\r\n");
565 raw_fd_ostream File(FilePathname, EC, sys::fs::F_None);
570 auto Buf = MemoryBuffer::getFile(FilePathname.str());
571 EXPECT_TRUE((bool)Buf);
572 EXPECT_EQ(Buf.get()->getBuffer(), "\n");
574 ASSERT_NO_ERROR(fs::remove(Twine(FilePathname)));
578 TEST_F(FileSystemTest, FileMapping) {
579 // Create a temp file.
581 SmallString<64> TempPath;
583 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
584 // Map in temp file and add some content
586 StringRef Val("hello there");
588 fs::mapped_file_region mfr(FileDescriptor,
590 fs::mapped_file_region::readwrite,
595 std::copy(Val.begin(), Val.end(), mfr.data());
596 // Explicitly add a 0.
597 mfr.data()[Val.size()] = 0;
601 // Map it back in read-only
602 fs::mapped_file_region mfr(Twine(TempPath),
603 fs::mapped_file_region::readonly,
610 EXPECT_EQ(StringRef(mfr.const_data()), Val);
614 fs::mapped_file_region m(Twine(TempPath),
615 fs::mapped_file_region::readonly,
620 const char *Data = m.const_data();
621 fs::mapped_file_region mfrrv(std::move(m));
622 EXPECT_EQ(mfrrv.const_data(), Data);
625 TEST(Support, NormalizePath) {
626 #if defined(LLVM_ON_WIN32)
627 #define EXPECT_PATH_IS(path__, windows__, not_windows__) \
628 EXPECT_EQ(path__, windows__);
630 #define EXPECT_PATH_IS(path__, windows__, not_windows__) \
631 EXPECT_EQ(path__, not_windows__);
634 SmallString<64> Path1("a");
635 SmallString<64> Path2("a/b");
636 SmallString<64> Path3("a\\b");
637 SmallString<64> Path4("a\\\\b");
638 SmallString<64> Path5("\\a");
639 SmallString<64> Path6("a\\");
642 EXPECT_PATH_IS(Path1, "a", "a");
645 EXPECT_PATH_IS(Path2, "a\\b", "a/b");
648 EXPECT_PATH_IS(Path3, "a\\b", "a/b");
651 EXPECT_PATH_IS(Path4, "a\\\\b", "a\\\\b");
654 EXPECT_PATH_IS(Path5, "\\a", "/a");
657 EXPECT_PATH_IS(Path6, "a\\", "a/");
659 #undef EXPECT_PATH_IS
661 } // anonymous namespace