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/ErrorHandling.h"
12 #include "llvm/Support/FileSystem.h"
13 #include "llvm/Support/MemoryBuffer.h"
14 #include "llvm/Support/raw_ostream.h"
15 #include "gtest/gtest.h"
18 using namespace llvm::sys;
20 #define ASSERT_NO_ERROR(x) \
21 if (error_code ASSERT_NO_ERROR_ec = x) { \
22 SmallString<128> MessageStorage; \
23 raw_svector_ostream Message(MessageStorage); \
24 Message << #x ": did not return errc::success.\n" \
25 << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n" \
26 << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \
27 GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \
32 TEST(is_separator, Works) {
33 EXPECT_TRUE(path::is_separator('/'));
34 EXPECT_FALSE(path::is_separator('\0'));
35 EXPECT_FALSE(path::is_separator('-'));
36 EXPECT_FALSE(path::is_separator(' '));
39 EXPECT_TRUE(path::is_separator('\\'));
41 EXPECT_FALSE(path::is_separator('\\'));
46 SmallVector<StringRef, 40> paths;
49 paths.push_back("..");
50 paths.push_back("foo");
52 paths.push_back("/foo");
53 paths.push_back("foo/");
54 paths.push_back("/foo/");
55 paths.push_back("foo/bar");
56 paths.push_back("/foo/bar");
57 paths.push_back("//net");
58 paths.push_back("//net/foo");
59 paths.push_back("///foo///");
60 paths.push_back("///foo///bar");
61 paths.push_back("/.");
62 paths.push_back("./");
63 paths.push_back("/..");
64 paths.push_back("../");
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/..");
70 paths.push_back("foo/../");
71 paths.push_back("foo/../bar");
72 paths.push_back("c:");
73 paths.push_back("c:/");
74 paths.push_back("c:foo");
75 paths.push_back("c:/foo");
76 paths.push_back("c:foo/");
77 paths.push_back("c:/foo/");
78 paths.push_back("c:/foo/bar");
79 paths.push_back("prn:");
80 paths.push_back("c:\\");
81 paths.push_back("c:foo");
82 paths.push_back("c:\\foo");
83 paths.push_back("c:foo\\");
84 paths.push_back("c:\\foo\\");
85 paths.push_back("c:\\foo/");
86 paths.push_back("c:/foo\\bar");
88 for (SmallVector<StringRef, 40>::const_iterator i = paths.begin(),
92 for (sys::path::const_iterator ci = sys::path::begin(*i),
93 ce = sys::path::end(*i);
96 ASSERT_FALSE(ci->empty());
99 #if 0 // Valgrind is whining about this.
100 outs() << " Reverse Iteration: [";
101 for (sys::path::reverse_iterator ci = sys::path::rbegin(*i),
102 ce = sys::path::rend(*i);
105 outs() << *ci << ',';
110 path::has_root_path(*i);
112 path::has_root_name(*i);
114 path::has_root_directory(*i);
115 path::root_directory(*i);
116 path::has_parent_path(*i);
117 path::parent_path(*i);
118 path::has_filename(*i);
122 path::has_extension(*i);
124 path::is_absolute(*i);
125 path::is_relative(*i);
127 SmallString<128> temp_store;
129 ASSERT_NO_ERROR(fs::make_absolute(temp_store));
131 path::remove_filename(temp_store);
134 path::replace_extension(temp_store, "ext");
135 StringRef filename(temp_store.begin(), temp_store.size()), stem, ext;
136 stem = path::stem(filename);
137 ext = path::extension(filename);
138 EXPECT_EQ(*(--sys::path::end(filename)), (stem + ext).str());
140 path::native(*i, temp_store);
144 TEST(Support, RelativePathIterator) {
145 SmallString<64> Path(StringRef("c/d/e/foo.txt"));
146 typedef SmallVector<StringRef, 4> PathComponents;
147 PathComponents ExpectedPathComponents;
148 PathComponents ActualPathComponents;
150 StringRef(Path).split(ExpectedPathComponents, "/");
152 for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
154 ActualPathComponents.push_back(*I);
157 ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
159 for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
160 EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
164 TEST(Support, AbsolutePathIterator) {
165 SmallString<64> Path(StringRef("/c/d/e/foo.txt"));
166 typedef SmallVector<StringRef, 4> PathComponents;
167 PathComponents ExpectedPathComponents;
168 PathComponents ActualPathComponents;
170 StringRef(Path).split(ExpectedPathComponents, "/");
172 // The root path will also be a component when iterating
173 ExpectedPathComponents[0] = "/";
175 for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
177 ActualPathComponents.push_back(*I);
180 ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
182 for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
183 EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
188 TEST(Support, AbsolutePathIteratorWin32) {
189 SmallString<64> Path(StringRef("c:\\c\\e\\foo.txt"));
190 typedef SmallVector<StringRef, 4> PathComponents;
191 PathComponents ExpectedPathComponents;
192 PathComponents ActualPathComponents;
194 StringRef(Path).split(ExpectedPathComponents, "\\");
196 // The root path (which comes after the drive name) will also be a component
198 ExpectedPathComponents.insert(ExpectedPathComponents.begin()+1, "\\");
200 for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
202 ActualPathComponents.push_back(*I);
205 ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
207 for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
208 EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
211 #endif // LLVM_ON_WIN32
213 TEST(Support, AbsolutePathIteratorEnd) {
214 // Trailing slashes are converted to '.' unless they are part of the root path.
215 SmallVector<StringRef, 4> Paths;
216 Paths.push_back("/foo/");
217 Paths.push_back("/foo//");
218 Paths.push_back("//net//");
220 Paths.push_back("c:\\\\");
223 for (StringRef Path : Paths) {
224 StringRef LastComponent = *--path::end(Path);
225 EXPECT_EQ(".", LastComponent);
228 SmallVector<StringRef, 3> RootPaths;
229 RootPaths.push_back("/");
230 RootPaths.push_back("//net/");
232 RootPaths.push_back("c:\\");
235 for (StringRef Path : RootPaths) {
236 StringRef LastComponent = *--path::end(Path);
237 EXPECT_EQ(1u, LastComponent.size());
238 EXPECT_TRUE(path::is_separator(LastComponent[0]));
242 TEST(Support, HomeDirectory) {
244 // This test only makes sense on Unix if $HOME is set.
245 if (::getenv("HOME")) {
247 SmallString<128> HomeDir;
248 EXPECT_TRUE(path::home_directory(HomeDir));
249 EXPECT_FALSE(HomeDir.empty());
255 class FileSystemTest : public testing::Test {
257 /// Unique temporary directory in which all created filesystem entities must
258 /// be placed. It is recursively removed at the end of each test.
259 SmallString<128> TestDirectory;
261 virtual void SetUp() {
263 fs::createUniqueDirectory("file-system-test", TestDirectory));
264 // We don't care about this specific file.
265 errs() << "Test Directory: " << TestDirectory << '\n';
269 virtual void TearDown() {
270 ASSERT_NO_ERROR(fs::remove(TestDirectory.str()));
274 TEST_F(FileSystemTest, Unique) {
275 // Create a temp file.
277 SmallString<64> TempPath;
279 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
281 // The same file should return an identical unique id.
283 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F1));
284 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F2));
287 // Different files should return different unique ids.
289 SmallString<64> TempPath2;
291 fs::createTemporaryFile("prefix", "temp", FileDescriptor2, TempPath2));
294 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D));
296 ::close(FileDescriptor2);
298 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
300 // Two paths representing the same file on disk should still provide the
301 // same unique id. We can test this by making a hard link.
302 ASSERT_NO_ERROR(fs::create_hard_link(Twine(TempPath), Twine(TempPath2)));
304 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D2));
307 ::close(FileDescriptor);
309 SmallString<128> Dir1;
311 fs::createUniqueDirectory("dir1", Dir1));
312 ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F1));
313 ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F2));
316 SmallString<128> Dir2;
318 fs::createUniqueDirectory("dir2", Dir2));
319 ASSERT_NO_ERROR(fs::getUniqueID(Dir2.c_str(), F2));
323 TEST_F(FileSystemTest, TempFiles) {
324 // Create a temp file.
326 SmallString<64> TempPath;
328 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
330 // Make sure it exists.
332 ASSERT_NO_ERROR(sys::fs::exists(Twine(TempPath), TempFileExists));
333 EXPECT_TRUE(TempFileExists);
335 // Create another temp tile.
337 SmallString<64> TempPath2;
338 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD2, TempPath2));
339 ASSERT_TRUE(TempPath2.endswith(".temp"));
340 ASSERT_NE(TempPath.str(), TempPath2.str());
342 fs::file_status A, B;
343 ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
344 ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
345 EXPECT_FALSE(fs::equivalent(A, B));
350 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
351 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
352 ASSERT_EQ(fs::remove(Twine(TempPath2), false),
353 errc::no_such_file_or_directory);
355 error_code EC = fs::status(TempPath2.c_str(), B);
356 EXPECT_EQ(EC, errc::no_such_file_or_directory);
357 EXPECT_EQ(B.type(), fs::file_type::file_not_found);
359 // Make sure Temp2 doesn't exist.
360 ASSERT_NO_ERROR(fs::exists(Twine(TempPath2), TempFileExists));
361 EXPECT_FALSE(TempFileExists);
363 SmallString<64> TempPath3;
364 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "", TempPath3));
365 ASSERT_FALSE(TempPath3.endswith("."));
367 // Create a hard link to Temp1.
368 ASSERT_NO_ERROR(fs::create_hard_link(Twine(TempPath), Twine(TempPath2)));
370 ASSERT_NO_ERROR(fs::equivalent(Twine(TempPath), Twine(TempPath2), equal));
372 ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
373 ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
374 EXPECT_TRUE(fs::equivalent(A, B));
377 ::close(FileDescriptor);
378 ASSERT_NO_ERROR(fs::remove(Twine(TempPath)));
380 // Remove the hard link.
381 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
383 // Make sure Temp1 doesn't exist.
384 ASSERT_NO_ERROR(fs::exists(Twine(TempPath), TempFileExists));
385 EXPECT_FALSE(TempFileExists);
388 // Path name > 260 chars should get an error.
389 const char *Path270 =
390 "abcdefghijklmnopqrstuvwxyz9abcdefghijklmnopqrstuvwxyz8"
391 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
392 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
393 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
394 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
395 EXPECT_EQ(fs::createUniqueFile(Twine(Path270), FileDescriptor, TempPath),
396 windows_error::path_not_found);
400 TEST_F(FileSystemTest, CreateDir) {
401 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
402 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
403 ASSERT_EQ(fs::create_directory(Twine(TestDirectory) + "foo", false),
405 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "foo"));
408 TEST_F(FileSystemTest, DirectoryIteration) {
410 for (fs::directory_iterator i(".", ec), e; i != e; i.increment(ec))
413 // Create a known hierarchy to recurse over.
415 fs::create_directories(Twine(TestDirectory) + "/recursive/a0/aa1"));
417 fs::create_directories(Twine(TestDirectory) + "/recursive/a0/ab1"));
418 ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) +
419 "/recursive/dontlookhere/da1"));
421 fs::create_directories(Twine(TestDirectory) + "/recursive/z0/za1"));
423 fs::create_directories(Twine(TestDirectory) + "/recursive/pop/p1"));
424 typedef std::vector<std::string> v_t;
426 for (fs::recursive_directory_iterator i(Twine(TestDirectory)
427 + "/recursive", ec), e; i != e; i.increment(ec)){
429 if (path::filename(i->path()) == "p1") {
431 // FIXME: recursive_directory_iterator should be more robust.
434 if (path::filename(i->path()) == "dontlookhere")
436 visited.push_back(path::filename(i->path()));
438 v_t::const_iterator a0 = std::find(visited.begin(), visited.end(), "a0");
439 v_t::const_iterator aa1 = std::find(visited.begin(), visited.end(), "aa1");
440 v_t::const_iterator ab1 = std::find(visited.begin(), visited.end(), "ab1");
441 v_t::const_iterator dontlookhere = std::find(visited.begin(), visited.end(),
443 v_t::const_iterator da1 = std::find(visited.begin(), visited.end(), "da1");
444 v_t::const_iterator z0 = std::find(visited.begin(), visited.end(), "z0");
445 v_t::const_iterator za1 = std::find(visited.begin(), visited.end(), "za1");
446 v_t::const_iterator pop = std::find(visited.begin(), visited.end(), "pop");
447 v_t::const_iterator p1 = std::find(visited.begin(), visited.end(), "p1");
449 // Make sure that each path was visited correctly.
450 ASSERT_NE(a0, visited.end());
451 ASSERT_NE(aa1, visited.end());
452 ASSERT_NE(ab1, visited.end());
453 ASSERT_NE(dontlookhere, visited.end());
454 ASSERT_EQ(da1, visited.end()); // Not visited.
455 ASSERT_NE(z0, visited.end());
456 ASSERT_NE(za1, visited.end());
457 ASSERT_NE(pop, visited.end());
458 ASSERT_EQ(p1, visited.end()); // Not visited.
460 // Make sure that parents were visited before children. No other ordering
461 // guarantees can be made across siblings.
466 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/aa1"));
467 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/ab1"));
468 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0"));
470 fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere/da1"));
471 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere"));
472 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop/p1"));
473 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop"));
474 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0/za1"));
475 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0"));
476 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive"));
479 const char archive[] = "!<arch>\x0A";
480 const char bitcode[] = "\xde\xc0\x17\x0b";
481 const char coff_object[] = "\x00\x00......";
482 const char coff_import_library[] = "\x00\x00\xff\xff....";
483 const char elf_relocatable[] = { 0x7f, 'E', 'L', 'F', 1, 2, 1, 0, 0,
484 0, 0, 0, 0, 0, 0, 0, 0, 1 };
485 const char macho_universal_binary[] = "\xca\xfe\xba\xbe...\0x00";
486 const char macho_object[] = "\xfe\xed\xfa\xce..........\x00\x01";
487 const char macho_executable[] = "\xfe\xed\xfa\xce..........\x00\x02";
488 const char macho_fixed_virtual_memory_shared_lib[] =
489 "\xfe\xed\xfa\xce..........\x00\x03";
490 const char macho_core[] = "\xfe\xed\xfa\xce..........\x00\x04";
491 const char macho_preload_executable[] = "\xfe\xed\xfa\xce..........\x00\x05";
492 const char macho_dynamically_linked_shared_lib[] =
493 "\xfe\xed\xfa\xce..........\x00\x06";
494 const char macho_dynamic_linker[] = "\xfe\xed\xfa\xce..........\x00\x07";
495 const char macho_bundle[] = "\xfe\xed\xfa\xce..........\x00\x08";
496 const char macho_dsym_companion[] = "\xfe\xed\xfa\xce..........\x00\x0a";
497 const char windows_resource[] = "\x00\x00\x00\x00\x020\x00\x00\x00\xff";
499 TEST_F(FileSystemTest, Magic) {
501 const char *filename;
502 const char *magic_str;
503 size_t magic_str_len;
504 fs::file_magic magic;
506 #define DEFINE(magic) \
507 { #magic, magic, sizeof(magic), fs::file_magic::magic }
511 DEFINE(coff_import_library),
512 DEFINE(elf_relocatable),
513 DEFINE(macho_universal_binary),
514 DEFINE(macho_object),
515 DEFINE(macho_executable),
516 DEFINE(macho_fixed_virtual_memory_shared_lib),
518 DEFINE(macho_preload_executable),
519 DEFINE(macho_dynamically_linked_shared_lib),
520 DEFINE(macho_dynamic_linker),
521 DEFINE(macho_bundle),
522 DEFINE(macho_dsym_companion),
523 DEFINE(windows_resource)
527 // Create some files filled with magic.
528 for (type *i = types, *e = types + (sizeof(types) / sizeof(type)); i != e;
530 SmallString<128> file_pathname(TestDirectory);
531 path::append(file_pathname, i->filename);
533 raw_fd_ostream file(file_pathname.c_str(), ErrMsg, sys::fs::F_None);
534 ASSERT_FALSE(file.has_error());
535 StringRef magic(i->magic_str, i->magic_str_len);
539 ASSERT_NO_ERROR(fs::has_magic(file_pathname.c_str(), magic, res));
541 EXPECT_EQ(i->magic, fs::identify_magic(magic));
542 ASSERT_NO_ERROR(fs::remove(Twine(file_pathname)));
547 TEST_F(FileSystemTest, CarriageReturn) {
548 SmallString<128> FilePathname(TestDirectory);
550 path::append(FilePathname, "test");
553 raw_fd_ostream File(FilePathname.c_str(), ErrMsg, sys::fs::F_Text);
554 EXPECT_EQ(ErrMsg, "");
558 std::unique_ptr<MemoryBuffer> Buf;
559 MemoryBuffer::getFile(FilePathname.c_str(), Buf);
560 EXPECT_EQ(Buf->getBuffer(), "\r\n");
564 raw_fd_ostream File(FilePathname.c_str(), ErrMsg, sys::fs::F_None);
565 EXPECT_EQ(ErrMsg, "");
569 std::unique_ptr<MemoryBuffer> Buf;
570 MemoryBuffer::getFile(FilePathname.c_str(), Buf);
571 EXPECT_EQ(Buf->getBuffer(), "\n");
573 ASSERT_NO_ERROR(fs::remove(Twine(FilePathname)));
577 TEST_F(FileSystemTest, FileMapping) {
578 // Create a temp file.
580 SmallString<64> TempPath;
582 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
583 // Map in temp file and add some content
585 StringRef Val("hello there");
587 fs::mapped_file_region mfr(FileDescriptor,
589 fs::mapped_file_region::readwrite,
594 std::copy(Val.begin(), Val.end(), mfr.data());
595 // Explicitly add a 0.
596 mfr.data()[Val.size()] = 0;
600 // Map it back in read-only
601 fs::mapped_file_region mfr(Twine(TempPath),
602 fs::mapped_file_region::readonly,
609 EXPECT_EQ(StringRef(mfr.const_data()), Val);
613 fs::mapped_file_region m(Twine(TempPath),
614 fs::mapped_file_region::readonly,
619 const char *Data = m.const_data();
620 fs::mapped_file_region mfrrv(std::move(m));
621 EXPECT_EQ(mfrrv.const_data(), Data);
623 } // anonymous namespace