Path.cpp revision f4ab63f3d8efa70053786d8a0e57b3bf76ae4ee5
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/MemoryBuffer.h"
14#include "llvm/Support/raw_ostream.h"
15#include "gtest/gtest.h"
16
17using namespace llvm;
18using namespace llvm::sys;
19
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()); \
28  } else {}
29
30namespace {
31
32TEST(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(' '));
37
38#ifdef LLVM_ON_WIN32
39  EXPECT_TRUE(path::is_separator('\\'));
40#else
41  EXPECT_FALSE(path::is_separator('\\'));
42#endif
43}
44
45TEST(Support, Path) {
46  SmallVector<StringRef, 40> paths;
47  paths.push_back("");
48  paths.push_back(".");
49  paths.push_back("..");
50  paths.push_back("foo");
51  paths.push_back("/");
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");
87
88  for (SmallVector<StringRef, 40>::const_iterator i = paths.begin(),
89                                                  e = paths.end();
90                                                  i != e;
91                                                  ++i) {
92    for (sys::path::const_iterator ci = sys::path::begin(*i),
93                                   ce = sys::path::end(*i);
94                                   ci != ce;
95                                   ++ci) {
96      ASSERT_FALSE(ci->empty());
97    }
98
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);
103                                     ci != ce;
104                                     ++ci) {
105      outs() << *ci << ',';
106    }
107    outs() << "]\n";
108#endif
109
110    path::has_root_path(*i);
111    path::root_path(*i);
112    path::has_root_name(*i);
113    path::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);
119    path::filename(*i);
120    path::has_stem(*i);
121    path::stem(*i);
122    path::has_extension(*i);
123    path::extension(*i);
124    path::is_absolute(*i);
125    path::is_relative(*i);
126
127    SmallString<128> temp_store;
128    temp_store = *i;
129    ASSERT_NO_ERROR(fs::make_absolute(temp_store));
130    temp_store = *i;
131    path::remove_filename(temp_store);
132
133    temp_store = *i;
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());
139
140    path::native(*i, temp_store);
141  }
142}
143
144class FileSystemTest : public testing::Test {
145protected:
146  /// Unique temporary directory in which all created filesystem entities must
147  /// be placed. It is recursively removed at the end of each test.
148  SmallString<128> TestDirectory;
149
150  virtual void SetUp() {
151    ASSERT_NO_ERROR(
152        fs::createUniqueDirectory("file-system-test", TestDirectory));
153    // We don't care about this specific file.
154    errs() << "Test Directory: " << TestDirectory << '\n';
155    errs().flush();
156  }
157
158  virtual void TearDown() {
159    uint32_t removed;
160    ASSERT_NO_ERROR(fs::remove_all(TestDirectory.str(), removed));
161  }
162};
163
164TEST_F(FileSystemTest, Unique) {
165  // Create a temp file.
166  int FileDescriptor;
167  SmallString<64> TempPath;
168  ASSERT_NO_ERROR(
169      fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
170
171  // The same file should return an identical unique id.
172  fs::UniqueID F1, F2;
173  ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F1));
174  ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F2));
175  ASSERT_EQ(F1, F2);
176
177  // Different files should return different unique ids.
178  int FileDescriptor2;
179  SmallString<64> TempPath2;
180  ASSERT_NO_ERROR(
181      fs::createTemporaryFile("prefix", "temp", FileDescriptor2, TempPath2));
182
183  fs::UniqueID D;
184  ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D));
185  ASSERT_NE(D, F1);
186  ::close(FileDescriptor2);
187
188  ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
189
190  // Two paths representing the same file on disk should still provide the
191  // same unique id.  We can test this by making a hard link.
192  ASSERT_NO_ERROR(fs::create_hard_link(Twine(TempPath), Twine(TempPath2)));
193  fs::UniqueID D2;
194  ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D2));
195  ASSERT_EQ(D2, F1);
196
197  ::close(FileDescriptor);
198
199  SmallString<128> Dir1;
200  ASSERT_NO_ERROR(
201     fs::createUniqueDirectory("dir1", Dir1));
202  ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F1));
203  ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F2));
204  ASSERT_EQ(F1, F2);
205
206  SmallString<128> Dir2;
207  ASSERT_NO_ERROR(
208     fs::createUniqueDirectory("dir2", Dir2));
209  ASSERT_NO_ERROR(fs::getUniqueID(Dir2.c_str(), F2));
210  ASSERT_NE(F1, F2);
211}
212
213TEST_F(FileSystemTest, TempFiles) {
214  // Create a temp file.
215  int FileDescriptor;
216  SmallString<64> TempPath;
217  ASSERT_NO_ERROR(
218      fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
219
220  // Make sure it exists.
221  bool TempFileExists;
222  ASSERT_NO_ERROR(sys::fs::exists(Twine(TempPath), TempFileExists));
223  EXPECT_TRUE(TempFileExists);
224
225  // Create another temp tile.
226  int FD2;
227  SmallString<64> TempPath2;
228  ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD2, TempPath2));
229  ASSERT_TRUE(TempPath2.endswith(".temp"));
230  ASSERT_NE(TempPath.str(), TempPath2.str());
231
232  fs::file_status A, B;
233  ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
234  ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
235  EXPECT_FALSE(fs::equivalent(A, B));
236
237  ::close(FD2);
238
239  // Remove Temp2.
240  ASSERT_NO_ERROR(fs::remove(Twine(TempPath2), TempFileExists));
241  EXPECT_TRUE(TempFileExists);
242
243  // Make sure Temp2 doesn't exist.
244  ASSERT_NO_ERROR(fs::exists(Twine(TempPath2), TempFileExists));
245  EXPECT_FALSE(TempFileExists);
246
247  SmallString<64> TempPath3;
248  ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "", TempPath3));
249  ASSERT_FALSE(TempPath3.endswith("."));
250
251  // Create a hard link to Temp1.
252  ASSERT_NO_ERROR(fs::create_hard_link(Twine(TempPath), Twine(TempPath2)));
253  bool equal;
254  ASSERT_NO_ERROR(fs::equivalent(Twine(TempPath), Twine(TempPath2), equal));
255  EXPECT_TRUE(equal);
256  ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
257  ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
258  EXPECT_TRUE(fs::equivalent(A, B));
259
260  // Remove Temp1.
261  ::close(FileDescriptor);
262  ASSERT_NO_ERROR(fs::remove(Twine(TempPath), TempFileExists));
263  EXPECT_TRUE(TempFileExists);
264
265  // Remove the hard link.
266  ASSERT_NO_ERROR(fs::remove(Twine(TempPath2), TempFileExists));
267  EXPECT_TRUE(TempFileExists);
268
269  // Make sure Temp1 doesn't exist.
270  ASSERT_NO_ERROR(fs::exists(Twine(TempPath), TempFileExists));
271  EXPECT_FALSE(TempFileExists);
272
273#ifdef LLVM_ON_WIN32
274  // Path name > 260 chars should get an error.
275  const char *Path270 =
276    "abcdefghijklmnopqrstuvwxyz9abcdefghijklmnopqrstuvwxyz8"
277    "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
278    "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
279    "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
280    "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
281  EXPECT_EQ(fs::createUniqueFile(Twine(Path270), FileDescriptor, TempPath),
282            windows_error::path_not_found);
283#endif
284}
285
286TEST_F(FileSystemTest, DirectoryIteration) {
287  error_code ec;
288  for (fs::directory_iterator i(".", ec), e; i != e; i.increment(ec))
289    ASSERT_NO_ERROR(ec);
290
291  // Create a known hierarchy to recurse over.
292  bool existed;
293  ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory)
294                  + "/recursive/a0/aa1", existed));
295  ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory)
296                  + "/recursive/a0/ab1", existed));
297  ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory)
298                  + "/recursive/dontlookhere/da1", existed));
299  ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory)
300                  + "/recursive/z0/za1", existed));
301  ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory)
302                  + "/recursive/pop/p1", existed));
303  typedef std::vector<std::string> v_t;
304  v_t visited;
305  for (fs::recursive_directory_iterator i(Twine(TestDirectory)
306         + "/recursive", ec), e; i != e; i.increment(ec)){
307    ASSERT_NO_ERROR(ec);
308    if (path::filename(i->path()) == "p1") {
309      i.pop();
310      // FIXME: recursive_directory_iterator should be more robust.
311      if (i == e) break;
312    }
313    if (path::filename(i->path()) == "dontlookhere")
314      i.no_push();
315    visited.push_back(path::filename(i->path()));
316  }
317  v_t::const_iterator a0 = std::find(visited.begin(), visited.end(), "a0");
318  v_t::const_iterator aa1 = std::find(visited.begin(), visited.end(), "aa1");
319  v_t::const_iterator ab1 = std::find(visited.begin(), visited.end(), "ab1");
320  v_t::const_iterator dontlookhere = std::find(visited.begin(), visited.end(),
321                                               "dontlookhere");
322  v_t::const_iterator da1 = std::find(visited.begin(), visited.end(), "da1");
323  v_t::const_iterator z0 = std::find(visited.begin(), visited.end(), "z0");
324  v_t::const_iterator za1 = std::find(visited.begin(), visited.end(), "za1");
325  v_t::const_iterator pop = std::find(visited.begin(), visited.end(), "pop");
326  v_t::const_iterator p1 = std::find(visited.begin(), visited.end(), "p1");
327
328  // Make sure that each path was visited correctly.
329  ASSERT_NE(a0, visited.end());
330  ASSERT_NE(aa1, visited.end());
331  ASSERT_NE(ab1, visited.end());
332  ASSERT_NE(dontlookhere, visited.end());
333  ASSERT_EQ(da1, visited.end()); // Not visited.
334  ASSERT_NE(z0, visited.end());
335  ASSERT_NE(za1, visited.end());
336  ASSERT_NE(pop, visited.end());
337  ASSERT_EQ(p1, visited.end()); // Not visited.
338
339  // Make sure that parents were visited before children. No other ordering
340  // guarantees can be made across siblings.
341  ASSERT_LT(a0, aa1);
342  ASSERT_LT(a0, ab1);
343  ASSERT_LT(z0, za1);
344}
345
346const char elf[] = {0x7f, 'E', 'L', 'F', 1, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
347
348TEST_F(FileSystemTest, Magic) {
349  struct type {
350    const char *filename;
351    const char *magic_str;
352    size_t magic_str_len;
353    fs::file_magic magic;
354  } types [] = {
355    {"magic.archive", "!<arch>\x0A", 8, fs::file_magic::archive},
356    {"magic.elf", elf, sizeof(elf),
357     fs::file_magic::elf_relocatable}
358  };
359
360  // Create some files filled with magic.
361  for (type *i = types, *e = types + (sizeof(types) / sizeof(type)); i != e;
362                                                                     ++i) {
363    SmallString<128> file_pathname(TestDirectory);
364    path::append(file_pathname, i->filename);
365    std::string ErrMsg;
366    raw_fd_ostream file(file_pathname.c_str(), ErrMsg, sys::fs::F_Binary);
367    ASSERT_FALSE(file.has_error());
368    StringRef magic(i->magic_str, i->magic_str_len);
369    file << magic;
370    file.close();
371    bool res = false;
372    ASSERT_NO_ERROR(fs::has_magic(file_pathname.c_str(), magic, res));
373    EXPECT_TRUE(res);
374    EXPECT_EQ(i->magic, fs::identify_magic(magic));
375  }
376}
377
378#ifdef LLVM_ON_WIN32
379TEST_F(FileSystemTest, CarriageReturn) {
380  SmallString<128> FilePathname(TestDirectory);
381  std::string ErrMsg;
382  path::append(FilePathname, "test");
383
384  {
385    raw_fd_ostream File(FilePathname.c_str(), ErrMsg);
386    EXPECT_EQ(ErrMsg, "");
387    File << '\n';
388  }
389  {
390    OwningPtr<MemoryBuffer> Buf;
391    MemoryBuffer::getFile(FilePathname, Buf);
392    EXPECT_EQ(Buf->getBuffer(), "\r\n");
393  }
394
395  {
396    raw_fd_ostream File(FilePathname.c_str(), ErrMsg, sys::fs::F_Binary);
397    EXPECT_EQ(ErrMsg, "");
398    File << '\n';
399  }
400  {
401    OwningPtr<MemoryBuffer> Buf;
402    MemoryBuffer::getFile(FilePathname, Buf);
403    EXPECT_EQ(Buf->getBuffer(), "\n");
404  }
405}
406#endif
407
408TEST_F(FileSystemTest, FileMapping) {
409  // Create a temp file.
410  int FileDescriptor;
411  SmallString<64> TempPath;
412  ASSERT_NO_ERROR(
413      fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
414  // Map in temp file and add some content
415  error_code EC;
416  StringRef Val("hello there");
417  {
418    fs::mapped_file_region mfr(FileDescriptor,
419                               true,
420                               fs::mapped_file_region::readwrite,
421                               4096,
422                               0,
423                               EC);
424    ASSERT_NO_ERROR(EC);
425    std::copy(Val.begin(), Val.end(), mfr.data());
426    // Explicitly add a 0.
427    mfr.data()[Val.size()] = 0;
428    // Unmap temp file
429  }
430
431  // Map it back in read-only
432  fs::mapped_file_region mfr(Twine(TempPath),
433                             fs::mapped_file_region::readonly,
434                             0,
435                             0,
436                             EC);
437  ASSERT_NO_ERROR(EC);
438
439  // Verify content
440  EXPECT_EQ(StringRef(mfr.const_data()), Val);
441
442  // Unmap temp file
443
444#if LLVM_HAS_RVALUE_REFERENCES
445  fs::mapped_file_region m(Twine(TempPath),
446                             fs::mapped_file_region::readonly,
447                             0,
448                             0,
449                             EC);
450  ASSERT_NO_ERROR(EC);
451  const char *Data = m.const_data();
452  fs::mapped_file_region mfrrv(llvm_move(m));
453  EXPECT_EQ(mfrrv.const_data(), Data);
454#endif
455}
456} // anonymous namespace
457