Fix windows build.
[oota-llvm.git] / unittests / Support / Path.cpp
1 //===- llvm/unittest/Support/Path.cpp - Path tests ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/Support/Path.h"
11 #include "llvm/Support/ErrorHandling.h"
12 #include "llvm/Support/FileSystem.h"
13 #include "llvm/Support/raw_ostream.h"
14 #include "gtest/gtest.h"
15
16 using namespace llvm;
17 using namespace llvm::sys;
18
19 #define ASSERT_NO_ERROR(x) \
20   if (error_code ASSERT_NO_ERROR_ec = x) { \
21     SmallString<128> MessageStorage; \
22     raw_svector_ostream Message(MessageStorage); \
23     Message << #x ": did not return errc::success.\n" \
24             << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n" \
25             << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \
26     GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \
27   } else {}
28
29 namespace {
30
31 TEST(is_separator, Works) {
32   EXPECT_TRUE(path::is_separator('/'));
33   EXPECT_FALSE(path::is_separator('\0'));
34   EXPECT_FALSE(path::is_separator('-'));
35   EXPECT_FALSE(path::is_separator(' '));
36
37 #ifdef LLVM_ON_WIN32
38   EXPECT_TRUE(path::is_separator('\\'));
39 #else
40   EXPECT_FALSE(path::is_separator('\\'));
41 #endif
42 }
43
44 TEST(Support, Path) {
45   SmallVector<StringRef, 40> paths;
46   paths.push_back("");
47   paths.push_back(".");
48   paths.push_back("..");
49   paths.push_back("foo");
50   paths.push_back("/");
51   paths.push_back("/foo");
52   paths.push_back("foo/");
53   paths.push_back("/foo/");
54   paths.push_back("foo/bar");
55   paths.push_back("/foo/bar");
56   paths.push_back("//net");
57   paths.push_back("//net/foo");
58   paths.push_back("///foo///");
59   paths.push_back("///foo///bar");
60   paths.push_back("/.");
61   paths.push_back("./");
62   paths.push_back("/..");
63   paths.push_back("../");
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/..");
69   paths.push_back("foo/../");
70   paths.push_back("foo/../bar");
71   paths.push_back("c:");
72   paths.push_back("c:/");
73   paths.push_back("c:foo");
74   paths.push_back("c:/foo");
75   paths.push_back("c:foo/");
76   paths.push_back("c:/foo/");
77   paths.push_back("c:/foo/bar");
78   paths.push_back("prn:");
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/");
85   paths.push_back("c:/foo\\bar");
86
87   for (SmallVector<StringRef, 40>::const_iterator i = paths.begin(),
88                                                   e = paths.end();
89                                                   i != e;
90                                                   ++i) {
91     for (sys::path::const_iterator ci = sys::path::begin(*i),
92                                    ce = sys::path::end(*i);
93                                    ci != ce;
94                                    ++ci) {
95       ASSERT_FALSE(ci->empty());
96     }
97
98 #if 0 // Valgrind is whining about this.
99     outs() << "    Reverse Iteration: [";
100     for (sys::path::reverse_iterator ci = sys::path::rbegin(*i),
101                                      ce = sys::path::rend(*i);
102                                      ci != ce;
103                                      ++ci) {
104       outs() << *ci << ',';
105     }
106     outs() << "]\n";
107 #endif
108
109     path::has_root_path(*i);
110     path::root_path(*i);
111     path::has_root_name(*i);
112     path::root_name(*i);
113     path::has_root_directory(*i);
114     path::root_directory(*i);
115     path::has_parent_path(*i);
116     path::parent_path(*i);
117     path::has_filename(*i);
118     path::filename(*i);
119     path::has_stem(*i);
120     path::stem(*i);
121     path::has_extension(*i);
122     path::extension(*i);
123     path::is_absolute(*i);
124     path::is_relative(*i);
125
126     SmallString<128> temp_store;
127     temp_store = *i;
128     ASSERT_NO_ERROR(fs::make_absolute(temp_store));
129     temp_store = *i;
130     path::remove_filename(temp_store);
131
132     temp_store = *i;
133     path::replace_extension(temp_store, "ext");
134     StringRef filename(temp_store.begin(), temp_store.size()), stem, ext;
135     stem = path::stem(filename);
136     ext  = path::extension(filename);
137     EXPECT_EQ(*(--sys::path::end(filename)), (stem + ext).str());
138
139     path::native(*i, temp_store);
140   }
141 }
142
143 class FileSystemTest : public testing::Test {
144 protected:
145   /// Unique temporary directory in which all created filesystem entities must
146   /// be placed. It is recursively removed at the end of each test.
147   SmallString<128> TestDirectory;
148
149   virtual void SetUp() {
150     ASSERT_NO_ERROR(
151         fs::createUniqueDirectory("file-system-test", TestDirectory));
152     // We don't care about this specific file.
153     errs() << "Test Directory: " << TestDirectory << '\n';
154     errs().flush();
155   }
156
157   virtual void TearDown() {
158     uint32_t removed;
159     ASSERT_NO_ERROR(fs::remove_all(TestDirectory.str(), removed));
160   }
161 };
162
163 TEST_F(FileSystemTest, Unique) {
164   // Create a temp file.
165   int FileDescriptor;
166   SmallString<64> TempPath;
167   ASSERT_NO_ERROR(
168       fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
169
170   // The same file should return an identical unique id.
171   uint64_t F1, F2;
172   ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F1));
173   ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F2));
174   ASSERT_EQ(F1, F2);
175
176   // Different files should return different unique ids.
177   int FileDescriptor2;
178   SmallString<64> TempPath2;
179   ASSERT_NO_ERROR(
180       fs::createTemporaryFile("prefix", "temp", FileDescriptor2, TempPath2));
181
182   uint64_t D;
183   ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D));
184   ASSERT_NE(D, F1);
185   ::close(FileDescriptor2);
186
187   ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
188
189   // Two paths representing the same file on disk should still provide the
190   // same unique id.  We can test this by making a hard link.
191   ASSERT_NO_ERROR(fs::create_hard_link(Twine(TempPath), Twine(TempPath2)));
192   uint64_t D2;
193   ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D2));
194   ASSERT_EQ(D2, F1);
195
196   ::close(FileDescriptor);
197 }
198
199 TEST_F(FileSystemTest, TempFiles) {
200   // Create a temp file.
201   int FileDescriptor;
202   SmallString<64> TempPath;
203   ASSERT_NO_ERROR(
204       fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
205
206   // Make sure it exists.
207   bool TempFileExists;
208   ASSERT_NO_ERROR(sys::fs::exists(Twine(TempPath), TempFileExists));
209   EXPECT_TRUE(TempFileExists);
210
211   // Create another temp tile.
212   int FD2;
213   SmallString<64> TempPath2;
214   ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD2, TempPath2));
215   ASSERT_NE(TempPath.str(), TempPath2.str());
216
217   fs::file_status A, B;
218   ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
219   ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
220   EXPECT_FALSE(fs::equivalent(A, B));
221
222   // Try to copy the first to the second.
223   EXPECT_EQ(
224     fs::copy_file(Twine(TempPath), Twine(TempPath2)), errc::file_exists);
225
226   ::close(FD2);
227   // Try again with the proper options.
228   ASSERT_NO_ERROR(fs::copy_file(Twine(TempPath), Twine(TempPath2),
229                                 fs::copy_option::overwrite_if_exists));
230   // Remove Temp2.
231   ASSERT_NO_ERROR(fs::remove(Twine(TempPath2), TempFileExists));
232   EXPECT_TRUE(TempFileExists);
233
234   // Make sure Temp2 doesn't exist.
235   ASSERT_NO_ERROR(fs::exists(Twine(TempPath2), TempFileExists));
236   EXPECT_FALSE(TempFileExists);
237
238   // Create a hard link to Temp1.
239   ASSERT_NO_ERROR(fs::create_hard_link(Twine(TempPath), Twine(TempPath2)));
240   bool equal;
241   ASSERT_NO_ERROR(fs::equivalent(Twine(TempPath), Twine(TempPath2), equal));
242   EXPECT_TRUE(equal);
243   ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
244   ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
245   EXPECT_TRUE(fs::equivalent(A, B));
246
247   // Remove Temp1.
248   ::close(FileDescriptor);
249   ASSERT_NO_ERROR(fs::remove(Twine(TempPath), TempFileExists));
250   EXPECT_TRUE(TempFileExists);
251
252   // Remove the hard link.
253   ASSERT_NO_ERROR(fs::remove(Twine(TempPath2), TempFileExists));
254   EXPECT_TRUE(TempFileExists);
255
256   // Make sure Temp1 doesn't exist.
257   ASSERT_NO_ERROR(fs::exists(Twine(TempPath), TempFileExists));
258   EXPECT_FALSE(TempFileExists);
259
260 #ifdef LLVM_ON_WIN32
261   // Path name > 260 chars should get an error.
262   const char *Path270 =
263     "abcdefghijklmnopqrstuvwxyz9abcdefghijklmnopqrstuvwxyz8"
264     "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
265     "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
266     "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
267     "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
268   EXPECT_EQ(fs::createUniqueFile(Twine(Path270), FileDescriptor, TempPath),
269             windows_error::path_not_found);
270 #endif
271 }
272
273 TEST_F(FileSystemTest, DirectoryIteration) {
274   error_code ec;
275   for (fs::directory_iterator i(".", ec), e; i != e; i.increment(ec))
276     ASSERT_NO_ERROR(ec);
277
278   // Create a known hierarchy to recurse over.
279   bool existed;
280   ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory)
281                   + "/recursive/a0/aa1", existed));
282   ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory)
283                   + "/recursive/a0/ab1", existed));
284   ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory)
285                   + "/recursive/dontlookhere/da1", existed));
286   ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory)
287                   + "/recursive/z0/za1", existed));
288   ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory)
289                   + "/recursive/pop/p1", existed));
290   typedef std::vector<std::string> v_t;
291   v_t visited;
292   for (fs::recursive_directory_iterator i(Twine(TestDirectory)
293          + "/recursive", ec), e; i != e; i.increment(ec)){
294     ASSERT_NO_ERROR(ec);
295     if (path::filename(i->path()) == "p1") {
296       i.pop();
297       // FIXME: recursive_directory_iterator should be more robust.
298       if (i == e) break;
299     }
300     if (path::filename(i->path()) == "dontlookhere")
301       i.no_push();
302     visited.push_back(path::filename(i->path()));
303   }
304   v_t::const_iterator a0 = std::find(visited.begin(), visited.end(), "a0");
305   v_t::const_iterator aa1 = std::find(visited.begin(), visited.end(), "aa1");
306   v_t::const_iterator ab1 = std::find(visited.begin(), visited.end(), "ab1");
307   v_t::const_iterator dontlookhere = std::find(visited.begin(), visited.end(),
308                                                "dontlookhere");
309   v_t::const_iterator da1 = std::find(visited.begin(), visited.end(), "da1");
310   v_t::const_iterator z0 = std::find(visited.begin(), visited.end(), "z0");
311   v_t::const_iterator za1 = std::find(visited.begin(), visited.end(), "za1");
312   v_t::const_iterator pop = std::find(visited.begin(), visited.end(), "pop");
313   v_t::const_iterator p1 = std::find(visited.begin(), visited.end(), "p1");
314
315   // Make sure that each path was visited correctly.
316   ASSERT_NE(a0, visited.end());
317   ASSERT_NE(aa1, visited.end());
318   ASSERT_NE(ab1, visited.end());
319   ASSERT_NE(dontlookhere, visited.end());
320   ASSERT_EQ(da1, visited.end()); // Not visited.
321   ASSERT_NE(z0, visited.end());
322   ASSERT_NE(za1, visited.end());
323   ASSERT_NE(pop, visited.end());
324   ASSERT_EQ(p1, visited.end()); // Not visited.
325
326   // Make sure that parents were visited before children. No other ordering
327   // guarantees can be made across siblings.
328   ASSERT_LT(a0, aa1);
329   ASSERT_LT(a0, ab1);
330   ASSERT_LT(z0, za1);
331 }
332
333 const char elf[] = {0x7f, 'E', 'L', 'F', 1, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
334
335 TEST_F(FileSystemTest, Magic) {
336   struct type {
337     const char *filename;
338     const char *magic_str;
339     size_t magic_str_len;
340     fs::file_magic magic;
341   } types [] = {
342     {"magic.archive", "!<arch>\x0A", 8, fs::file_magic::archive},
343     {"magic.elf", elf, sizeof(elf),
344      fs::file_magic::elf_relocatable}
345   };
346
347   // Create some files filled with magic.
348   for (type *i = types, *e = types + (sizeof(types) / sizeof(type)); i != e;
349                                                                      ++i) {
350     SmallString<128> file_pathname(TestDirectory);
351     path::append(file_pathname, i->filename);
352     std::string ErrMsg;
353     raw_fd_ostream file(file_pathname.c_str(), ErrMsg,
354                         raw_fd_ostream::F_Binary);
355     ASSERT_FALSE(file.has_error());
356     StringRef magic(i->magic_str, i->magic_str_len);
357     file << magic;
358     file.close();
359     bool res = false;
360     ASSERT_NO_ERROR(fs::has_magic(file_pathname.c_str(), magic, res));
361     EXPECT_TRUE(res);
362     EXPECT_EQ(i->magic, fs::identify_magic(magic));
363   }
364 }
365
366 #if !defined(_WIN32) // FIXME: Win32 has different permission schema.
367 TEST_F(FileSystemTest, Permissions) {
368   // Create a temp file.
369   int FileDescriptor;
370   SmallString<64> TempPath;
371   ASSERT_NO_ERROR(
372       fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
373
374   // Mark file as read-only
375   const fs::perms AllWrite = fs::owner_write|fs::group_write|fs::others_write;
376   ASSERT_NO_ERROR(fs::permissions(Twine(TempPath), fs::remove_perms|AllWrite));
377  
378   // Verify file is read-only
379   fs::file_status Status;
380   ASSERT_NO_ERROR(fs::status(Twine(TempPath), Status));
381   bool AnyWriteBits = (Status.permissions() & AllWrite);
382   EXPECT_FALSE(AnyWriteBits);
383   
384   // Mark file as read-write
385   ASSERT_NO_ERROR(fs::permissions(Twine(TempPath), fs::add_perms|AllWrite));
386   
387   // Verify file is read-write
388   ASSERT_NO_ERROR(fs::status(Twine(TempPath), Status));
389   AnyWriteBits = (Status.permissions() & AllWrite);
390   EXPECT_TRUE(AnyWriteBits);
391 }
392 #endif
393
394 TEST_F(FileSystemTest, FileMapping) {
395   // Create a temp file.
396   int FileDescriptor;
397   SmallString<64> TempPath;
398   ASSERT_NO_ERROR(
399       fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
400   // Map in temp file and add some content
401   error_code EC;
402   StringRef Val("hello there");
403   {
404     fs::mapped_file_region mfr(FileDescriptor,
405                                true,
406                                fs::mapped_file_region::readwrite,
407                                4096,
408                                0,
409                                EC);
410     ASSERT_NO_ERROR(EC);
411     std::copy(Val.begin(), Val.end(), mfr.data());
412     // Explicitly add a 0.
413     mfr.data()[Val.size()] = 0;
414     // Unmap temp file
415   }
416   
417   // Map it back in read-only
418   fs::mapped_file_region mfr(Twine(TempPath),
419                              fs::mapped_file_region::readonly,
420                              0,
421                              0,
422                              EC);
423   ASSERT_NO_ERROR(EC);
424   
425   // Verify content
426   EXPECT_EQ(StringRef(mfr.const_data()), Val);
427   
428   // Unmap temp file
429
430 #if LLVM_HAS_RVALUE_REFERENCES
431   fs::mapped_file_region m(Twine(TempPath),
432                              fs::mapped_file_region::readonly,
433                              0,
434                              0,
435                              EC);
436   ASSERT_NO_ERROR(EC);
437   const char *Data = m.const_data();
438   fs::mapped_file_region mfrrv(llvm_move(m));
439   EXPECT_EQ(mfrrv.const_data(), Data);
440 #endif
441 }
442 } // anonymous namespace