[Support] Add a version of fs::make_absolute with a custom CWD.
[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/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"
17
18 #ifdef LLVM_ON_WIN32
19 #include <windows.h>
20 #include <winerror.h>
21 #endif
22
23 #ifdef LLVM_ON_UNIX
24 #include <sys/stat.h>
25 #endif
26
27 using namespace llvm;
28 using namespace llvm::sys;
29
30 #define ASSERT_NO_ERROR(x)                                                     \
31   if (std::error_code ASSERT_NO_ERROR_ec = x) {                                \
32     SmallString<128> MessageStorage;                                           \
33     raw_svector_ostream Message(MessageStorage);                               \
34     Message << #x ": did not return errc::success.\n"                          \
35             << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n"          \
36             << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n";      \
37     GTEST_FATAL_FAILURE_(MessageStorage.c_str());                              \
38   } else {                                                                     \
39   }
40
41 namespace {
42
43 TEST(is_separator, Works) {
44   EXPECT_TRUE(path::is_separator('/'));
45   EXPECT_FALSE(path::is_separator('\0'));
46   EXPECT_FALSE(path::is_separator('-'));
47   EXPECT_FALSE(path::is_separator(' '));
48
49 #ifdef LLVM_ON_WIN32
50   EXPECT_TRUE(path::is_separator('\\'));
51 #else
52   EXPECT_FALSE(path::is_separator('\\'));
53 #endif
54 }
55
56 TEST(Support, Path) {
57   SmallVector<StringRef, 40> paths;
58   paths.push_back("");
59   paths.push_back(".");
60   paths.push_back("..");
61   paths.push_back("foo");
62   paths.push_back("/");
63   paths.push_back("/foo");
64   paths.push_back("foo/");
65   paths.push_back("/foo/");
66   paths.push_back("foo/bar");
67   paths.push_back("/foo/bar");
68   paths.push_back("//net");
69   paths.push_back("//net/foo");
70   paths.push_back("///foo///");
71   paths.push_back("///foo///bar");
72   paths.push_back("/.");
73   paths.push_back("./");
74   paths.push_back("/..");
75   paths.push_back("../");
76   paths.push_back("foo/.");
77   paths.push_back("foo/..");
78   paths.push_back("foo/./");
79   paths.push_back("foo/./bar");
80   paths.push_back("foo/..");
81   paths.push_back("foo/../");
82   paths.push_back("foo/../bar");
83   paths.push_back("c:");
84   paths.push_back("c:/");
85   paths.push_back("c:foo");
86   paths.push_back("c:/foo");
87   paths.push_back("c:foo/");
88   paths.push_back("c:/foo/");
89   paths.push_back("c:/foo/bar");
90   paths.push_back("prn:");
91   paths.push_back("c:\\");
92   paths.push_back("c:foo");
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\\bar");
98
99   SmallVector<StringRef, 5> ComponentStack;
100   for (SmallVector<StringRef, 40>::const_iterator i = paths.begin(),
101                                                   e = paths.end();
102                                                   i != e;
103                                                   ++i) {
104     for (sys::path::const_iterator ci = sys::path::begin(*i),
105                                    ce = sys::path::end(*i);
106                                    ci != ce;
107                                    ++ci) {
108       ASSERT_FALSE(ci->empty());
109       ComponentStack.push_back(*ci);
110     }
111
112     for (sys::path::reverse_iterator ci = sys::path::rbegin(*i),
113                                      ce = sys::path::rend(*i);
114                                      ci != ce;
115                                      ++ci) {
116       ASSERT_TRUE(*ci == ComponentStack.back());
117       ComponentStack.pop_back();
118     }
119     ASSERT_TRUE(ComponentStack.empty());
120
121     path::has_root_path(*i);
122     path::root_path(*i);
123     path::has_root_name(*i);
124     path::root_name(*i);
125     path::has_root_directory(*i);
126     path::root_directory(*i);
127     path::has_parent_path(*i);
128     path::parent_path(*i);
129     path::has_filename(*i);
130     path::filename(*i);
131     path::has_stem(*i);
132     path::stem(*i);
133     path::has_extension(*i);
134     path::extension(*i);
135     path::is_absolute(*i);
136     path::is_relative(*i);
137
138     SmallString<128> temp_store;
139     temp_store = *i;
140     ASSERT_NO_ERROR(fs::make_absolute(temp_store));
141     temp_store = *i;
142     path::remove_filename(temp_store);
143
144     temp_store = *i;
145     path::replace_extension(temp_store, "ext");
146     StringRef filename(temp_store.begin(), temp_store.size()), stem, ext;
147     stem = path::stem(filename);
148     ext  = path::extension(filename);
149     EXPECT_EQ(*sys::path::rbegin(filename), (stem + ext).str());
150
151     path::native(*i, temp_store);
152   }
153
154   SmallString<32> Relative("foo.cpp");
155   ASSERT_NO_ERROR(sys::fs::make_absolute("/root", Relative));
156   ASSERT_EQ("/root/foo.cpp", Relative);
157 }
158
159 TEST(Support, RelativePathIterator) {
160   SmallString<64> Path(StringRef("c/d/e/foo.txt"));
161   typedef SmallVector<StringRef, 4> PathComponents;
162   PathComponents ExpectedPathComponents;
163   PathComponents ActualPathComponents;
164
165   StringRef(Path).split(ExpectedPathComponents, '/');
166
167   for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
168        ++I) {
169     ActualPathComponents.push_back(*I);
170   }
171
172   ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
173
174   for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
175     EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
176   }
177 }
178
179 TEST(Support, RelativePathDotIterator) {
180   SmallString<64> Path(StringRef(".c/.d/../."));
181   typedef SmallVector<StringRef, 4> PathComponents;
182   PathComponents ExpectedPathComponents;
183   PathComponents ActualPathComponents;
184
185   StringRef(Path).split(ExpectedPathComponents, '/');
186
187   for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
188        ++I) {
189     ActualPathComponents.push_back(*I);
190   }
191
192   ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
193
194   for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
195     EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
196   }
197 }
198
199 TEST(Support, AbsolutePathIterator) {
200   SmallString<64> Path(StringRef("/c/d/e/foo.txt"));
201   typedef SmallVector<StringRef, 4> PathComponents;
202   PathComponents ExpectedPathComponents;
203   PathComponents ActualPathComponents;
204
205   StringRef(Path).split(ExpectedPathComponents, '/');
206
207   // The root path will also be a component when iterating
208   ExpectedPathComponents[0] = "/";
209
210   for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
211        ++I) {
212     ActualPathComponents.push_back(*I);
213   }
214
215   ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
216
217   for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
218     EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
219   }
220 }
221
222 TEST(Support, AbsolutePathDotIterator) {
223   SmallString<64> Path(StringRef("/.c/.d/../."));
224   typedef SmallVector<StringRef, 4> PathComponents;
225   PathComponents ExpectedPathComponents;
226   PathComponents ActualPathComponents;
227
228   StringRef(Path).split(ExpectedPathComponents, '/');
229
230   // The root path will also be a component when iterating
231   ExpectedPathComponents[0] = "/";
232
233   for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
234        ++I) {
235     ActualPathComponents.push_back(*I);
236   }
237
238   ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
239
240   for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
241     EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
242   }
243 }
244
245 #ifdef LLVM_ON_WIN32
246 TEST(Support, AbsolutePathIteratorWin32) {
247   SmallString<64> Path(StringRef("c:\\c\\e\\foo.txt"));
248   typedef SmallVector<StringRef, 4> PathComponents;
249   PathComponents ExpectedPathComponents;
250   PathComponents ActualPathComponents;
251
252   StringRef(Path).split(ExpectedPathComponents, "\\");
253
254   // The root path (which comes after the drive name) will also be a component
255   // when iterating.
256   ExpectedPathComponents.insert(ExpectedPathComponents.begin()+1, "\\");
257
258   for (path::const_iterator I = path::begin(Path), E = path::end(Path); I != E;
259        ++I) {
260     ActualPathComponents.push_back(*I);
261   }
262
263   ASSERT_EQ(ExpectedPathComponents.size(), ActualPathComponents.size());
264
265   for (size_t i = 0; i <ExpectedPathComponents.size(); ++i) {
266     EXPECT_EQ(ExpectedPathComponents[i].str(), ActualPathComponents[i].str());
267   }
268 }
269 #endif // LLVM_ON_WIN32
270
271 TEST(Support, AbsolutePathIteratorEnd) {
272   // Trailing slashes are converted to '.' unless they are part of the root path.
273   SmallVector<StringRef, 4> Paths;
274   Paths.push_back("/foo/");
275   Paths.push_back("/foo//");
276   Paths.push_back("//net//");
277 #ifdef LLVM_ON_WIN32
278   Paths.push_back("c:\\\\");
279 #endif
280
281   for (StringRef Path : Paths) {
282     StringRef LastComponent = *path::rbegin(Path);
283     EXPECT_EQ(".", LastComponent);
284   }
285
286   SmallVector<StringRef, 3> RootPaths;
287   RootPaths.push_back("/");
288   RootPaths.push_back("//net/");
289 #ifdef LLVM_ON_WIN32
290   RootPaths.push_back("c:\\");
291 #endif
292
293   for (StringRef Path : RootPaths) {
294     StringRef LastComponent = *path::rbegin(Path);
295     EXPECT_EQ(1u, LastComponent.size());
296     EXPECT_TRUE(path::is_separator(LastComponent[0]));
297   }
298 }
299
300 TEST(Support, HomeDirectory) {
301 #ifdef LLVM_ON_UNIX
302   // This test only makes sense on Unix if $HOME is set.
303   if (::getenv("HOME")) {
304 #endif
305     SmallString<128> HomeDir;
306     EXPECT_TRUE(path::home_directory(HomeDir));
307     EXPECT_FALSE(HomeDir.empty());
308 #ifdef LLVM_ON_UNIX
309   }
310 #endif
311 }
312
313 class FileSystemTest : public testing::Test {
314 protected:
315   /// Unique temporary directory in which all created filesystem entities must
316   /// be placed. It is removed at the end of each test (must be empty).
317   SmallString<128> TestDirectory;
318
319   void SetUp() override {
320     ASSERT_NO_ERROR(
321         fs::createUniqueDirectory("file-system-test", TestDirectory));
322     // We don't care about this specific file.
323     errs() << "Test Directory: " << TestDirectory << '\n';
324     errs().flush();
325   }
326
327   void TearDown() override { ASSERT_NO_ERROR(fs::remove(TestDirectory.str())); }
328 };
329
330 TEST_F(FileSystemTest, Unique) {
331   // Create a temp file.
332   int FileDescriptor;
333   SmallString<64> TempPath;
334   ASSERT_NO_ERROR(
335       fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
336
337   // The same file should return an identical unique id.
338   fs::UniqueID F1, F2;
339   ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F1));
340   ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F2));
341   ASSERT_EQ(F1, F2);
342
343   // Different files should return different unique ids.
344   int FileDescriptor2;
345   SmallString<64> TempPath2;
346   ASSERT_NO_ERROR(
347       fs::createTemporaryFile("prefix", "temp", FileDescriptor2, TempPath2));
348
349   fs::UniqueID D;
350   ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D));
351   ASSERT_NE(D, F1);
352   ::close(FileDescriptor2);
353
354   ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
355
356   // Two paths representing the same file on disk should still provide the
357   // same unique id.  We can test this by making a hard link.
358   ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2)));
359   fs::UniqueID D2;
360   ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D2));
361   ASSERT_EQ(D2, F1);
362
363   ::close(FileDescriptor);
364
365   SmallString<128> Dir1;
366   ASSERT_NO_ERROR(
367      fs::createUniqueDirectory("dir1", Dir1));
368   ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F1));
369   ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F2));
370   ASSERT_EQ(F1, F2);
371
372   SmallString<128> Dir2;
373   ASSERT_NO_ERROR(
374      fs::createUniqueDirectory("dir2", Dir2));
375   ASSERT_NO_ERROR(fs::getUniqueID(Dir2.c_str(), F2));
376   ASSERT_NE(F1, F2);
377 }
378
379 TEST_F(FileSystemTest, TempFiles) {
380   // Create a temp file.
381   int FileDescriptor;
382   SmallString<64> TempPath;
383   ASSERT_NO_ERROR(
384       fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
385
386   // Make sure it exists.
387   ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
388
389   // Create another temp tile.
390   int FD2;
391   SmallString<64> TempPath2;
392   ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD2, TempPath2));
393   ASSERT_TRUE(TempPath2.endswith(".temp"));
394   ASSERT_NE(TempPath.str(), TempPath2.str());
395
396   fs::file_status A, B;
397   ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
398   ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
399   EXPECT_FALSE(fs::equivalent(A, B));
400
401   ::close(FD2);
402
403   // Remove Temp2.
404   ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
405   ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
406   ASSERT_EQ(fs::remove(Twine(TempPath2), false),
407             errc::no_such_file_or_directory);
408
409   std::error_code EC = fs::status(TempPath2.c_str(), B);
410   EXPECT_EQ(EC, errc::no_such_file_or_directory);
411   EXPECT_EQ(B.type(), fs::file_type::file_not_found);
412
413   // Make sure Temp2 doesn't exist.
414   ASSERT_EQ(fs::access(Twine(TempPath2), sys::fs::AccessMode::Exist),
415             errc::no_such_file_or_directory);
416
417   SmallString<64> TempPath3;
418   ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "", TempPath3));
419   ASSERT_FALSE(TempPath3.endswith("."));
420
421   // Create a hard link to Temp1.
422   ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2)));
423   bool equal;
424   ASSERT_NO_ERROR(fs::equivalent(Twine(TempPath), Twine(TempPath2), equal));
425   EXPECT_TRUE(equal);
426   ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
427   ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
428   EXPECT_TRUE(fs::equivalent(A, B));
429
430   // Remove Temp1.
431   ::close(FileDescriptor);
432   ASSERT_NO_ERROR(fs::remove(Twine(TempPath)));
433
434   // Remove the hard link.
435   ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
436
437   // Make sure Temp1 doesn't exist.
438   ASSERT_EQ(fs::access(Twine(TempPath), sys::fs::AccessMode::Exist),
439             errc::no_such_file_or_directory);
440
441 #ifdef LLVM_ON_WIN32
442   // Path name > 260 chars should get an error.
443   const char *Path270 =
444     "abcdefghijklmnopqrstuvwxyz9abcdefghijklmnopqrstuvwxyz8"
445     "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
446     "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
447     "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
448     "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
449   EXPECT_EQ(fs::createUniqueFile(Path270, FileDescriptor, TempPath),
450             errc::invalid_argument);
451   // Relative path < 247 chars, no problem.
452   const char *Path216 =
453     "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
454     "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
455     "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
456     "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
457   ASSERT_NO_ERROR(fs::createTemporaryFile(Path216, "", TempPath));
458   ASSERT_NO_ERROR(fs::remove(Twine(TempPath)));
459 #endif
460 }
461
462 TEST_F(FileSystemTest, CreateDir) {
463   ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
464   ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
465   ASSERT_EQ(fs::create_directory(Twine(TestDirectory) + "foo", false),
466             errc::file_exists);
467   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "foo"));
468
469 #ifdef LLVM_ON_UNIX
470   // Set a 0000 umask so that we can test our directory permissions.
471   mode_t OldUmask = ::umask(0000);
472
473   fs::file_status Status;
474   ASSERT_NO_ERROR(
475       fs::create_directory(Twine(TestDirectory) + "baz500", false,
476                            fs::perms::owner_read | fs::perms::owner_exe));
477   ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz500", Status));
478   ASSERT_EQ(Status.permissions() & fs::perms::all_all,
479             fs::perms::owner_read | fs::perms::owner_exe);
480   ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "baz777", false,
481                                        fs::perms::all_all));
482   ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz777", Status));
483   ASSERT_EQ(Status.permissions() & fs::perms::all_all, fs::perms::all_all);
484
485   // Restore umask to be safe.
486   ::umask(OldUmask);
487 #endif
488
489 #ifdef LLVM_ON_WIN32
490   // Prove that create_directories() can handle a pathname > 248 characters,
491   // which is the documented limit for CreateDirectory().
492   // (248 is MAX_PATH subtracting room for an 8.3 filename.)
493   // Generate a directory path guaranteed to fall into that range.
494   size_t TmpLen = TestDirectory.size();
495   const char *OneDir = "\\123456789";
496   size_t OneDirLen = strlen(OneDir);
497   ASSERT_LT(OneDirLen, 12U);
498   size_t NLevels = ((248 - TmpLen) / OneDirLen) + 1;
499   SmallString<260> LongDir(TestDirectory);
500   for (size_t I = 0; I < NLevels; ++I)
501     LongDir.append(OneDir);
502   ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir)));
503   ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir)));
504   ASSERT_EQ(fs::create_directories(Twine(LongDir), false),
505             errc::file_exists);
506   // Tidy up, "recursively" removing the directories.
507   StringRef ThisDir(LongDir);
508   for (size_t J = 0; J < NLevels; ++J) {
509     ASSERT_NO_ERROR(fs::remove(ThisDir));
510     ThisDir = path::parent_path(ThisDir);
511   }
512
513   // Similarly for a relative pathname.  Need to set the current directory to
514   // TestDirectory so that the one we create ends up in the right place.
515   char PreviousDir[260];
516   size_t PreviousDirLen = ::GetCurrentDirectoryA(260, PreviousDir);
517   ASSERT_GT(PreviousDirLen, 0U);
518   ASSERT_LT(PreviousDirLen, 260U);
519   ASSERT_NE(::SetCurrentDirectoryA(TestDirectory.c_str()), 0);
520   LongDir.clear();
521   // Generate a relative directory name with absolute length > 248.
522   size_t LongDirLen = 249 - TestDirectory.size();
523   LongDir.assign(LongDirLen, 'a');
524   ASSERT_NO_ERROR(fs::create_directory(Twine(LongDir)));
525   // While we're here, prove that .. and . handling works in these long paths.
526   const char *DotDotDirs = "\\..\\.\\b";
527   LongDir.append(DotDotDirs);
528   ASSERT_NO_ERROR(fs::create_directory("b"));
529   ASSERT_EQ(fs::create_directory(Twine(LongDir), false), errc::file_exists);
530   // And clean up.
531   ASSERT_NO_ERROR(fs::remove("b"));
532   ASSERT_NO_ERROR(fs::remove(
533     Twine(LongDir.substr(0, LongDir.size() - strlen(DotDotDirs)))));
534   ASSERT_NE(::SetCurrentDirectoryA(PreviousDir), 0);
535 #endif
536 }
537
538 TEST_F(FileSystemTest, DirectoryIteration) {
539   std::error_code ec;
540   for (fs::directory_iterator i(".", ec), e; i != e; i.increment(ec))
541     ASSERT_NO_ERROR(ec);
542
543   // Create a known hierarchy to recurse over.
544   ASSERT_NO_ERROR(
545       fs::create_directories(Twine(TestDirectory) + "/recursive/a0/aa1"));
546   ASSERT_NO_ERROR(
547       fs::create_directories(Twine(TestDirectory) + "/recursive/a0/ab1"));
548   ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) +
549                                          "/recursive/dontlookhere/da1"));
550   ASSERT_NO_ERROR(
551       fs::create_directories(Twine(TestDirectory) + "/recursive/z0/za1"));
552   ASSERT_NO_ERROR(
553       fs::create_directories(Twine(TestDirectory) + "/recursive/pop/p1"));
554   typedef std::vector<std::string> v_t;
555   v_t visited;
556   for (fs::recursive_directory_iterator i(Twine(TestDirectory)
557          + "/recursive", ec), e; i != e; i.increment(ec)){
558     ASSERT_NO_ERROR(ec);
559     if (path::filename(i->path()) == "p1") {
560       i.pop();
561       // FIXME: recursive_directory_iterator should be more robust.
562       if (i == e) break;
563     }
564     if (path::filename(i->path()) == "dontlookhere")
565       i.no_push();
566     visited.push_back(path::filename(i->path()));
567   }
568   v_t::const_iterator a0 = std::find(visited.begin(), visited.end(), "a0");
569   v_t::const_iterator aa1 = std::find(visited.begin(), visited.end(), "aa1");
570   v_t::const_iterator ab1 = std::find(visited.begin(), visited.end(), "ab1");
571   v_t::const_iterator dontlookhere = std::find(visited.begin(), visited.end(),
572                                                "dontlookhere");
573   v_t::const_iterator da1 = std::find(visited.begin(), visited.end(), "da1");
574   v_t::const_iterator z0 = std::find(visited.begin(), visited.end(), "z0");
575   v_t::const_iterator za1 = std::find(visited.begin(), visited.end(), "za1");
576   v_t::const_iterator pop = std::find(visited.begin(), visited.end(), "pop");
577   v_t::const_iterator p1 = std::find(visited.begin(), visited.end(), "p1");
578
579   // Make sure that each path was visited correctly.
580   ASSERT_NE(a0, visited.end());
581   ASSERT_NE(aa1, visited.end());
582   ASSERT_NE(ab1, visited.end());
583   ASSERT_NE(dontlookhere, visited.end());
584   ASSERT_EQ(da1, visited.end()); // Not visited.
585   ASSERT_NE(z0, visited.end());
586   ASSERT_NE(za1, visited.end());
587   ASSERT_NE(pop, visited.end());
588   ASSERT_EQ(p1, visited.end()); // Not visited.
589
590   // Make sure that parents were visited before children. No other ordering
591   // guarantees can be made across siblings.
592   ASSERT_LT(a0, aa1);
593   ASSERT_LT(a0, ab1);
594   ASSERT_LT(z0, za1);
595
596   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/aa1"));
597   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/ab1"));
598   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0"));
599   ASSERT_NO_ERROR(
600       fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere/da1"));
601   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere"));
602   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop/p1"));
603   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop"));
604   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0/za1"));
605   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0"));
606   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive"));
607 }
608
609 const char archive[] = "!<arch>\x0A";
610 const char bitcode[] = "\xde\xc0\x17\x0b";
611 const char coff_object[] = "\x00\x00......";
612 const char coff_bigobj[] = "\x00\x00\xff\xff\x00\x02......"
613     "\xc7\xa1\xba\xd1\xee\xba\xa9\x4b\xaf\x20\xfa\xf6\x6a\xa4\xdc\xb8";
614 const char coff_import_library[] = "\x00\x00\xff\xff....";
615 const char elf_relocatable[] = { 0x7f, 'E', 'L', 'F', 1, 2, 1, 0, 0,
616                                  0,    0,   0,   0,   0, 0, 0, 0, 1 };
617 const char macho_universal_binary[] = "\xca\xfe\xba\xbe...\0x00";
618 const char macho_object[] = "\xfe\xed\xfa\xce..........\x00\x01";
619 const char macho_executable[] = "\xfe\xed\xfa\xce..........\x00\x02";
620 const char macho_fixed_virtual_memory_shared_lib[] =
621     "\xfe\xed\xfa\xce..........\x00\x03";
622 const char macho_core[] = "\xfe\xed\xfa\xce..........\x00\x04";
623 const char macho_preload_executable[] = "\xfe\xed\xfa\xce..........\x00\x05";
624 const char macho_dynamically_linked_shared_lib[] =
625     "\xfe\xed\xfa\xce..........\x00\x06";
626 const char macho_dynamic_linker[] = "\xfe\xed\xfa\xce..........\x00\x07";
627 const char macho_bundle[] = "\xfe\xed\xfa\xce..........\x00\x08";
628 const char macho_dsym_companion[] = "\xfe\xed\xfa\xce..........\x00\x0a";
629 const char macho_kext_bundle[] = "\xfe\xed\xfa\xce..........\x00\x0b";
630 const char windows_resource[] = "\x00\x00\x00\x00\x020\x00\x00\x00\xff";
631 const char macho_dynamically_linked_shared_lib_stub[] =
632     "\xfe\xed\xfa\xce..........\x00\x09";
633
634 TEST_F(FileSystemTest, Magic) {
635   struct type {
636     const char *filename;
637     const char *magic_str;
638     size_t magic_str_len;
639     fs::file_magic magic;
640   } types[] = {
641 #define DEFINE(magic)                                           \
642     { #magic, magic, sizeof(magic), fs::file_magic::magic }
643     DEFINE(archive),
644     DEFINE(bitcode),
645     DEFINE(coff_object),
646     { "coff_bigobj", coff_bigobj, sizeof(coff_bigobj), fs::file_magic::coff_object },
647     DEFINE(coff_import_library),
648     DEFINE(elf_relocatable),
649     DEFINE(macho_universal_binary),
650     DEFINE(macho_object),
651     DEFINE(macho_executable),
652     DEFINE(macho_fixed_virtual_memory_shared_lib),
653     DEFINE(macho_core),
654     DEFINE(macho_preload_executable),
655     DEFINE(macho_dynamically_linked_shared_lib),
656     DEFINE(macho_dynamic_linker),
657     DEFINE(macho_bundle),
658     DEFINE(macho_dynamically_linked_shared_lib_stub),
659     DEFINE(macho_dsym_companion),
660     DEFINE(macho_kext_bundle),
661     DEFINE(windows_resource)
662 #undef DEFINE
663     };
664
665   // Create some files filled with magic.
666   for (type *i = types, *e = types + (sizeof(types) / sizeof(type)); i != e;
667                                                                      ++i) {
668     SmallString<128> file_pathname(TestDirectory);
669     path::append(file_pathname, i->filename);
670     std::error_code EC;
671     raw_fd_ostream file(file_pathname, EC, sys::fs::F_None);
672     ASSERT_FALSE(file.has_error());
673     StringRef magic(i->magic_str, i->magic_str_len);
674     file << magic;
675     file.close();
676     EXPECT_EQ(i->magic, fs::identify_magic(magic));
677     ASSERT_NO_ERROR(fs::remove(Twine(file_pathname)));
678   }
679 }
680
681 #ifdef LLVM_ON_WIN32
682 TEST_F(FileSystemTest, CarriageReturn) {
683   SmallString<128> FilePathname(TestDirectory);
684   std::error_code EC;
685   path::append(FilePathname, "test");
686
687   {
688     raw_fd_ostream File(FilePathname, EC, sys::fs::F_Text);
689     ASSERT_NO_ERROR(EC);
690     File << '\n';
691   }
692   {
693     auto Buf = MemoryBuffer::getFile(FilePathname.str());
694     EXPECT_TRUE((bool)Buf);
695     EXPECT_EQ(Buf.get()->getBuffer(), "\r\n");
696   }
697
698   {
699     raw_fd_ostream File(FilePathname, EC, sys::fs::F_None);
700     ASSERT_NO_ERROR(EC);
701     File << '\n';
702   }
703   {
704     auto Buf = MemoryBuffer::getFile(FilePathname.str());
705     EXPECT_TRUE((bool)Buf);
706     EXPECT_EQ(Buf.get()->getBuffer(), "\n");
707   }
708   ASSERT_NO_ERROR(fs::remove(Twine(FilePathname)));
709 }
710 #endif
711
712 TEST_F(FileSystemTest, Resize) {
713   int FD;
714   SmallString<64> TempPath;
715   ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
716   ASSERT_NO_ERROR(fs::resize_file(FD, 123));
717   fs::file_status Status;
718   ASSERT_NO_ERROR(fs::status(FD, Status));
719   ASSERT_EQ(Status.getSize(), 123U);
720 }
721
722 TEST_F(FileSystemTest, FileMapping) {
723   // Create a temp file.
724   int FileDescriptor;
725   SmallString<64> TempPath;
726   ASSERT_NO_ERROR(
727       fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
728   unsigned Size = 4096;
729   ASSERT_NO_ERROR(fs::resize_file(FileDescriptor, Size));
730
731   // Map in temp file and add some content
732   std::error_code EC;
733   StringRef Val("hello there");
734   {
735     fs::mapped_file_region mfr(FileDescriptor,
736                                fs::mapped_file_region::readwrite, Size, 0, EC);
737     ASSERT_NO_ERROR(EC);
738     std::copy(Val.begin(), Val.end(), mfr.data());
739     // Explicitly add a 0.
740     mfr.data()[Val.size()] = 0;
741     // Unmap temp file
742   }
743
744   // Map it back in read-only
745   int FD;
746   EC = fs::openFileForRead(Twine(TempPath), FD);
747   ASSERT_NO_ERROR(EC);
748   fs::mapped_file_region mfr(FD, fs::mapped_file_region::readonly, Size, 0, EC);
749   ASSERT_NO_ERROR(EC);
750
751   // Verify content
752   EXPECT_EQ(StringRef(mfr.const_data()), Val);
753
754   // Unmap temp file
755   fs::mapped_file_region m(FD, fs::mapped_file_region::readonly, Size, 0, EC);
756   ASSERT_NO_ERROR(EC);
757   ASSERT_EQ(close(FD), 0);
758 }
759
760 TEST(Support, NormalizePath) {
761 #if defined(LLVM_ON_WIN32)
762 #define EXPECT_PATH_IS(path__, windows__, not_windows__)                        \
763   EXPECT_EQ(path__, windows__);
764 #else
765 #define EXPECT_PATH_IS(path__, windows__, not_windows__)                        \
766   EXPECT_EQ(path__, not_windows__);
767 #endif
768
769   SmallString<64> Path1("a");
770   SmallString<64> Path2("a/b");
771   SmallString<64> Path3("a\\b");
772   SmallString<64> Path4("a\\\\b");
773   SmallString<64> Path5("\\a");
774   SmallString<64> Path6("a\\");
775
776   path::native(Path1);
777   EXPECT_PATH_IS(Path1, "a", "a");
778
779   path::native(Path2);
780   EXPECT_PATH_IS(Path2, "a\\b", "a/b");
781
782   path::native(Path3);
783   EXPECT_PATH_IS(Path3, "a\\b", "a/b");
784
785   path::native(Path4);
786   EXPECT_PATH_IS(Path4, "a\\\\b", "a\\\\b");
787
788   path::native(Path5);
789   EXPECT_PATH_IS(Path5, "\\a", "/a");
790
791   path::native(Path6);
792   EXPECT_PATH_IS(Path6, "a\\", "a/");
793
794 #undef EXPECT_PATH_IS
795 }
796
797 TEST(Support, RemoveLeadingDotSlash) {
798   StringRef Path1("././/foolz/wat");
799   StringRef Path2("./////");
800
801   Path1 = path::remove_leading_dotslash(Path1);
802   EXPECT_EQ(Path1, "foolz/wat");
803   Path2 = path::remove_leading_dotslash(Path2);
804   EXPECT_EQ(Path2, "");
805 }
806 } // anonymous namespace