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