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/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/ADT/Triple.h"
14 #include "llvm/BinaryFormat/Magic.h"
15 #include "llvm/Config/llvm-config.h"
16 #include "llvm/Support/ConvertUTF.h"
17 #include "llvm/Support/Errc.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/FileUtilities.h"
21 #include "llvm/Support/Host.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "gtest/gtest.h"
25 #include "gmock/gmock.h"
26
27 #ifdef _WIN32
28 #include "llvm/ADT/ArrayRef.h"
29 #include "llvm/Support/Chrono.h"
30 #include <windows.h>
31 #include <winerror.h>
32 #endif
33
34 #ifdef LLVM_ON_UNIX
35 #include <pwd.h>
36 #include <sys/stat.h>
37 #endif
38
39 using namespace llvm;
40 using namespace llvm::sys;
41
42 #define ASSERT_NO_ERROR(x) \
43 if (std::error_code ASSERT_NO_ERROR_ec = x) { \
44 SmallString<128> MessageStorage; \
45 raw_svector_ostream Message(MessageStorage); \
46 Message << #x ": did not return errc::success.\n" \
47 << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n" \
48 << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \
49 GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \
50 } else { \
51 }
52
53 #define ASSERT_ERROR(x) \
54 if (!x) { \
55 SmallString<128> MessageStorage; \
56 raw_svector_ostream Message(MessageStorage); \
57 Message << #x ": did not return a failure error code.\n"; \
58 GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \
59 }
60
61 namespace {
62
63 struct FileDescriptorCloser {
FileDescriptorCloser__anon88dfe2e80111::FileDescriptorCloser64 explicit FileDescriptorCloser(int FD) : FD(FD) {}
~FileDescriptorCloser__anon88dfe2e80111::FileDescriptorCloser65 ~FileDescriptorCloser() { ::close(FD); }
66 int FD;
67 };
68
TEST(is_separator,Works)69 TEST(is_separator, Works) {
70 EXPECT_TRUE(path::is_separator('/'));
71 EXPECT_FALSE(path::is_separator('\0'));
72 EXPECT_FALSE(path::is_separator('-'));
73 EXPECT_FALSE(path::is_separator(' '));
74
75 EXPECT_TRUE(path::is_separator('\\', path::Style::windows));
76 EXPECT_FALSE(path::is_separator('\\', path::Style::posix));
77
78 #ifdef _WIN32
79 EXPECT_TRUE(path::is_separator('\\'));
80 #else
81 EXPECT_FALSE(path::is_separator('\\'));
82 #endif
83 }
84
TEST(Support,Path)85 TEST(Support, Path) {
86 SmallVector<StringRef, 40> paths;
87 paths.push_back("");
88 paths.push_back(".");
89 paths.push_back("..");
90 paths.push_back("foo");
91 paths.push_back("/");
92 paths.push_back("/foo");
93 paths.push_back("foo/");
94 paths.push_back("/foo/");
95 paths.push_back("foo/bar");
96 paths.push_back("/foo/bar");
97 paths.push_back("//net");
98 paths.push_back("//net/");
99 paths.push_back("//net/foo");
100 paths.push_back("///foo///");
101 paths.push_back("///foo///bar");
102 paths.push_back("/.");
103 paths.push_back("./");
104 paths.push_back("/..");
105 paths.push_back("../");
106 paths.push_back("foo/.");
107 paths.push_back("foo/..");
108 paths.push_back("foo/./");
109 paths.push_back("foo/./bar");
110 paths.push_back("foo/..");
111 paths.push_back("foo/../");
112 paths.push_back("foo/../bar");
113 paths.push_back("c:");
114 paths.push_back("c:/");
115 paths.push_back("c:foo");
116 paths.push_back("c:/foo");
117 paths.push_back("c:foo/");
118 paths.push_back("c:/foo/");
119 paths.push_back("c:/foo/bar");
120 paths.push_back("prn:");
121 paths.push_back("c:\\");
122 paths.push_back("c:foo");
123 paths.push_back("c:\\foo");
124 paths.push_back("c:foo\\");
125 paths.push_back("c:\\foo\\");
126 paths.push_back("c:\\foo/");
127 paths.push_back("c:/foo\\bar");
128
129 for (SmallVector<StringRef, 40>::const_iterator i = paths.begin(),
130 e = paths.end();
131 i != e;
132 ++i) {
133 SCOPED_TRACE(*i);
134 SmallVector<StringRef, 5> ComponentStack;
135 for (sys::path::const_iterator ci = sys::path::begin(*i),
136 ce = sys::path::end(*i);
137 ci != ce;
138 ++ci) {
139 EXPECT_FALSE(ci->empty());
140 ComponentStack.push_back(*ci);
141 }
142
143 SmallVector<StringRef, 5> ReverseComponentStack;
144 for (sys::path::reverse_iterator ci = sys::path::rbegin(*i),
145 ce = sys::path::rend(*i);
146 ci != ce;
147 ++ci) {
148 EXPECT_FALSE(ci->empty());
149 ReverseComponentStack.push_back(*ci);
150 }
151 std::reverse(ReverseComponentStack.begin(), ReverseComponentStack.end());
152 EXPECT_THAT(ComponentStack, testing::ContainerEq(ReverseComponentStack));
153
154 // Crash test most of the API - since we're iterating over all of our paths
155 // here there isn't really anything reasonable to assert on in the results.
156 (void)path::has_root_path(*i);
157 (void)path::root_path(*i);
158 (void)path::has_root_name(*i);
159 (void)path::root_name(*i);
160 (void)path::has_root_directory(*i);
161 (void)path::root_directory(*i);
162 (void)path::has_parent_path(*i);
163 (void)path::parent_path(*i);
164 (void)path::has_filename(*i);
165 (void)path::filename(*i);
166 (void)path::has_stem(*i);
167 (void)path::stem(*i);
168 (void)path::has_extension(*i);
169 (void)path::extension(*i);
170 (void)path::is_absolute(*i);
171 (void)path::is_relative(*i);
172
173 SmallString<128> temp_store;
174 temp_store = *i;
175 ASSERT_NO_ERROR(fs::make_absolute(temp_store));
176 temp_store = *i;
177 path::remove_filename(temp_store);
178
179 temp_store = *i;
180 path::replace_extension(temp_store, "ext");
181 StringRef filename(temp_store.begin(), temp_store.size()), stem, ext;
182 stem = path::stem(filename);
183 ext = path::extension(filename);
184 EXPECT_EQ(*sys::path::rbegin(filename), (stem + ext).str());
185
186 path::native(*i, temp_store);
187 }
188
189 SmallString<32> Relative("foo.cpp");
190 ASSERT_NO_ERROR(sys::fs::make_absolute("/root", Relative));
191 Relative[5] = '/'; // Fix up windows paths.
192 ASSERT_EQ("/root/foo.cpp", Relative);
193 }
194
TEST(Support,FilenameParent)195 TEST(Support, FilenameParent) {
196 EXPECT_EQ("/", path::filename("/"));
197 EXPECT_EQ("", path::parent_path("/"));
198
199 EXPECT_EQ("\\", path::filename("c:\\", path::Style::windows));
200 EXPECT_EQ("c:", path::parent_path("c:\\", path::Style::windows));
201
202 EXPECT_EQ("/", path::filename("///"));
203 EXPECT_EQ("", path::parent_path("///"));
204
205 EXPECT_EQ("\\", path::filename("c:\\\\", path::Style::windows));
206 EXPECT_EQ("c:", path::parent_path("c:\\\\", path::Style::windows));
207
208 EXPECT_EQ("bar", path::filename("/foo/bar"));
209 EXPECT_EQ("/foo", path::parent_path("/foo/bar"));
210
211 EXPECT_EQ("foo", path::filename("/foo"));
212 EXPECT_EQ("/", path::parent_path("/foo"));
213
214 EXPECT_EQ("foo", path::filename("foo"));
215 EXPECT_EQ("", path::parent_path("foo"));
216
217 EXPECT_EQ(".", path::filename("foo/"));
218 EXPECT_EQ("foo", path::parent_path("foo/"));
219
220 EXPECT_EQ("//net", path::filename("//net"));
221 EXPECT_EQ("", path::parent_path("//net"));
222
223 EXPECT_EQ("/", path::filename("//net/"));
224 EXPECT_EQ("//net", path::parent_path("//net/"));
225
226 EXPECT_EQ("foo", path::filename("//net/foo"));
227 EXPECT_EQ("//net/", path::parent_path("//net/foo"));
228
229 // These checks are just to make sure we do something reasonable with the
230 // paths below. They are not meant to prescribe the one true interpretation of
231 // these paths. Other decompositions (e.g. "//" -> "" + "//") are also
232 // possible.
233 EXPECT_EQ("/", path::filename("//"));
234 EXPECT_EQ("", path::parent_path("//"));
235
236 EXPECT_EQ("\\", path::filename("\\\\", path::Style::windows));
237 EXPECT_EQ("", path::parent_path("\\\\", path::Style::windows));
238
239 EXPECT_EQ("\\", path::filename("\\\\\\", path::Style::windows));
240 EXPECT_EQ("", path::parent_path("\\\\\\", path::Style::windows));
241 }
242
243 static std::vector<StringRef>
GetComponents(StringRef Path,path::Style S=path::Style::native)244 GetComponents(StringRef Path, path::Style S = path::Style::native) {
245 return {path::begin(Path, S), path::end(Path)};
246 }
247
TEST(Support,PathIterator)248 TEST(Support, PathIterator) {
249 EXPECT_THAT(GetComponents("/foo"), testing::ElementsAre("/", "foo"));
250 EXPECT_THAT(GetComponents("/"), testing::ElementsAre("/"));
251 EXPECT_THAT(GetComponents("//"), testing::ElementsAre("/"));
252 EXPECT_THAT(GetComponents("///"), testing::ElementsAre("/"));
253 EXPECT_THAT(GetComponents("c/d/e/foo.txt"),
254 testing::ElementsAre("c", "d", "e", "foo.txt"));
255 EXPECT_THAT(GetComponents(".c/.d/../."),
256 testing::ElementsAre(".c", ".d", "..", "."));
257 EXPECT_THAT(GetComponents("/c/d/e/foo.txt"),
258 testing::ElementsAre("/", "c", "d", "e", "foo.txt"));
259 EXPECT_THAT(GetComponents("/.c/.d/../."),
260 testing::ElementsAre("/", ".c", ".d", "..", "."));
261 EXPECT_THAT(GetComponents("c:\\c\\e\\foo.txt", path::Style::windows),
262 testing::ElementsAre("c:", "\\", "c", "e", "foo.txt"));
263 EXPECT_THAT(GetComponents("//net/"), testing::ElementsAre("//net", "/"));
264 EXPECT_THAT(GetComponents("//net/c/foo.txt"),
265 testing::ElementsAre("//net", "/", "c", "foo.txt"));
266 }
267
TEST(Support,AbsolutePathIteratorEnd)268 TEST(Support, AbsolutePathIteratorEnd) {
269 // Trailing slashes are converted to '.' unless they are part of the root path.
270 SmallVector<std::pair<StringRef, path::Style>, 4> Paths;
271 Paths.emplace_back("/foo/", path::Style::native);
272 Paths.emplace_back("/foo//", path::Style::native);
273 Paths.emplace_back("//net/foo/", path::Style::native);
274 Paths.emplace_back("c:\\foo\\", path::Style::windows);
275
276 for (auto &Path : Paths) {
277 SCOPED_TRACE(Path.first);
278 StringRef LastComponent = *path::rbegin(Path.first, Path.second);
279 EXPECT_EQ(".", LastComponent);
280 }
281
282 SmallVector<std::pair<StringRef, path::Style>, 3> RootPaths;
283 RootPaths.emplace_back("/", path::Style::native);
284 RootPaths.emplace_back("//net/", path::Style::native);
285 RootPaths.emplace_back("c:\\", path::Style::windows);
286 RootPaths.emplace_back("//net//", path::Style::native);
287 RootPaths.emplace_back("c:\\\\", path::Style::windows);
288
289 for (auto &Path : RootPaths) {
290 SCOPED_TRACE(Path.first);
291 StringRef LastComponent = *path::rbegin(Path.first, Path.second);
292 EXPECT_EQ(1u, LastComponent.size());
293 EXPECT_TRUE(path::is_separator(LastComponent[0], Path.second));
294 }
295 }
296
TEST(Support,HomeDirectory)297 TEST(Support, HomeDirectory) {
298 std::string expected;
299 #ifdef _WIN32
300 if (wchar_t const *path = ::_wgetenv(L"USERPROFILE")) {
301 auto pathLen = ::wcslen(path);
302 ArrayRef<char> ref{reinterpret_cast<char const *>(path),
303 pathLen * sizeof(wchar_t)};
304 convertUTF16ToUTF8String(ref, expected);
305 }
306 #else
307 if (char const *path = ::getenv("HOME"))
308 expected = path;
309 #endif
310 // Do not try to test it if we don't know what to expect.
311 // On Windows we use something better than env vars.
312 if (!expected.empty()) {
313 SmallString<128> HomeDir;
314 auto status = path::home_directory(HomeDir);
315 EXPECT_TRUE(status);
316 EXPECT_EQ(expected, HomeDir);
317 }
318 }
319
320 #ifdef LLVM_ON_UNIX
TEST(Support,HomeDirectoryWithNoEnv)321 TEST(Support, HomeDirectoryWithNoEnv) {
322 std::string OriginalStorage;
323 char const *OriginalEnv = ::getenv("HOME");
324 if (OriginalEnv) {
325 // We're going to unset it, so make a copy and save a pointer to the copy
326 // so that we can reset it at the end of the test.
327 OriginalStorage = OriginalEnv;
328 OriginalEnv = OriginalStorage.c_str();
329 }
330
331 // Don't run the test if we have nothing to compare against.
332 struct passwd *pw = getpwuid(getuid());
333 if (!pw || !pw->pw_dir) return;
334
335 ::unsetenv("HOME");
336 EXPECT_EQ(nullptr, ::getenv("HOME"));
337 std::string PwDir = pw->pw_dir;
338
339 SmallString<128> HomeDir;
340 auto status = path::home_directory(HomeDir);
341 EXPECT_TRUE(status);
342 EXPECT_EQ(PwDir, HomeDir);
343
344 // Now put the environment back to its original state (meaning that if it was
345 // unset before, we don't reset it).
346 if (OriginalEnv) ::setenv("HOME", OriginalEnv, 1);
347 }
348 #endif
349
TEST(Support,UserCacheDirectory)350 TEST(Support, UserCacheDirectory) {
351 SmallString<13> CacheDir;
352 SmallString<20> CacheDir2;
353 auto Status = path::user_cache_directory(CacheDir, "");
354 EXPECT_TRUE(Status ^ CacheDir.empty());
355
356 if (Status) {
357 EXPECT_TRUE(path::user_cache_directory(CacheDir2, "")); // should succeed
358 EXPECT_EQ(CacheDir, CacheDir2); // and return same paths
359
360 EXPECT_TRUE(path::user_cache_directory(CacheDir, "A", "B", "file.c"));
361 auto It = path::rbegin(CacheDir);
362 EXPECT_EQ("file.c", *It);
363 EXPECT_EQ("B", *++It);
364 EXPECT_EQ("A", *++It);
365 auto ParentDir = *++It;
366
367 // Test Unicode: "<user_cache_dir>/(pi)r^2/aleth.0"
368 EXPECT_TRUE(path::user_cache_directory(CacheDir2, "\xCF\x80r\xC2\xB2",
369 "\xE2\x84\xB5.0"));
370 auto It2 = path::rbegin(CacheDir2);
371 EXPECT_EQ("\xE2\x84\xB5.0", *It2);
372 EXPECT_EQ("\xCF\x80r\xC2\xB2", *++It2);
373 auto ParentDir2 = *++It2;
374
375 EXPECT_EQ(ParentDir, ParentDir2);
376 }
377 }
378
TEST(Support,TempDirectory)379 TEST(Support, TempDirectory) {
380 SmallString<32> TempDir;
381 path::system_temp_directory(false, TempDir);
382 EXPECT_TRUE(!TempDir.empty());
383 TempDir.clear();
384 path::system_temp_directory(true, TempDir);
385 EXPECT_TRUE(!TempDir.empty());
386 }
387
388 #ifdef _WIN32
path2regex(std::string Path)389 static std::string path2regex(std::string Path) {
390 size_t Pos = 0;
391 while ((Pos = Path.find('\\', Pos)) != std::string::npos) {
392 Path.replace(Pos, 1, "\\\\");
393 Pos += 2;
394 }
395 return Path;
396 }
397
398 /// Helper for running temp dir test in separated process. See below.
399 #define EXPECT_TEMP_DIR(prepare, expected) \
400 EXPECT_EXIT( \
401 { \
402 prepare; \
403 SmallString<300> TempDir; \
404 path::system_temp_directory(true, TempDir); \
405 raw_os_ostream(std::cerr) << TempDir; \
406 std::exit(0); \
407 }, \
408 ::testing::ExitedWithCode(0), path2regex(expected))
409
TEST(SupportDeathTest,TempDirectoryOnWindows)410 TEST(SupportDeathTest, TempDirectoryOnWindows) {
411 // In this test we want to check how system_temp_directory responds to
412 // different values of specific env vars. To prevent corrupting env vars of
413 // the current process all checks are done in separated processes.
414 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"C:\\OtherFolder"), "C:\\OtherFolder");
415 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"C:/Unix/Path/Seperators"),
416 "C:\\Unix\\Path\\Seperators");
417 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"Local Path"), ".+\\Local Path$");
418 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"F:\\TrailingSep\\"), "F:\\TrailingSep");
419 EXPECT_TEMP_DIR(
420 _wputenv_s(L"TMP", L"C:\\2\x03C0r-\x00B5\x00B3\\\x2135\x2080"),
421 "C:\\2\xCF\x80r-\xC2\xB5\xC2\xB3\\\xE2\x84\xB5\xE2\x82\x80");
422
423 // Test $TMP empty, $TEMP set.
424 EXPECT_TEMP_DIR(
425 {
426 _wputenv_s(L"TMP", L"");
427 _wputenv_s(L"TEMP", L"C:\\Valid\\Path");
428 },
429 "C:\\Valid\\Path");
430
431 // All related env vars empty
432 EXPECT_TEMP_DIR(
433 {
434 _wputenv_s(L"TMP", L"");
435 _wputenv_s(L"TEMP", L"");
436 _wputenv_s(L"USERPROFILE", L"");
437 },
438 "C:\\Temp");
439
440 // Test evn var / path with 260 chars.
441 SmallString<270> Expected{"C:\\Temp\\AB\\123456789"};
442 while (Expected.size() < 260)
443 Expected.append("\\DirNameWith19Charss");
444 ASSERT_EQ(260U, Expected.size());
445 EXPECT_TEMP_DIR(_putenv_s("TMP", Expected.c_str()), Expected.c_str());
446 }
447 #endif
448
449 class FileSystemTest : public testing::Test {
450 protected:
451 /// Unique temporary directory in which all created filesystem entities must
452 /// be placed. It is removed at the end of each test (must be empty).
453 SmallString<128> TestDirectory;
454 SmallString<128> NonExistantFile;
455
SetUp()456 void SetUp() override {
457 ASSERT_NO_ERROR(
458 fs::createUniqueDirectory("file-system-test", TestDirectory));
459 // We don't care about this specific file.
460 errs() << "Test Directory: " << TestDirectory << '\n';
461 errs().flush();
462 NonExistantFile = TestDirectory;
463
464 // Even though this value is hardcoded, is a 128-bit GUID, so we should be
465 // guaranteed that this file will never exist.
466 sys::path::append(NonExistantFile, "1B28B495C16344CB9822E588CD4C3EF0");
467 }
468
TearDown()469 void TearDown() override { ASSERT_NO_ERROR(fs::remove(TestDirectory.str())); }
470 };
471
TEST_F(FileSystemTest,Unique)472 TEST_F(FileSystemTest, Unique) {
473 // Create a temp file.
474 int FileDescriptor;
475 SmallString<64> TempPath;
476 ASSERT_NO_ERROR(
477 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
478
479 // The same file should return an identical unique id.
480 fs::UniqueID F1, F2;
481 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F1));
482 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F2));
483 ASSERT_EQ(F1, F2);
484
485 // Different files should return different unique ids.
486 int FileDescriptor2;
487 SmallString<64> TempPath2;
488 ASSERT_NO_ERROR(
489 fs::createTemporaryFile("prefix", "temp", FileDescriptor2, TempPath2));
490
491 fs::UniqueID D;
492 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D));
493 ASSERT_NE(D, F1);
494 ::close(FileDescriptor2);
495
496 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
497
498 // Two paths representing the same file on disk should still provide the
499 // same unique id. We can test this by making a hard link.
500 ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2)));
501 fs::UniqueID D2;
502 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D2));
503 ASSERT_EQ(D2, F1);
504
505 ::close(FileDescriptor);
506
507 SmallString<128> Dir1;
508 ASSERT_NO_ERROR(
509 fs::createUniqueDirectory("dir1", Dir1));
510 ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F1));
511 ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F2));
512 ASSERT_EQ(F1, F2);
513
514 SmallString<128> Dir2;
515 ASSERT_NO_ERROR(
516 fs::createUniqueDirectory("dir2", Dir2));
517 ASSERT_NO_ERROR(fs::getUniqueID(Dir2.c_str(), F2));
518 ASSERT_NE(F1, F2);
519 ASSERT_NO_ERROR(fs::remove(Dir1));
520 ASSERT_NO_ERROR(fs::remove(Dir2));
521 ASSERT_NO_ERROR(fs::remove(TempPath2));
522 ASSERT_NO_ERROR(fs::remove(TempPath));
523 }
524
TEST_F(FileSystemTest,RealPath)525 TEST_F(FileSystemTest, RealPath) {
526 ASSERT_NO_ERROR(
527 fs::create_directories(Twine(TestDirectory) + "/test1/test2/test3"));
528 ASSERT_TRUE(fs::exists(Twine(TestDirectory) + "/test1/test2/test3"));
529
530 SmallString<64> RealBase;
531 SmallString<64> Expected;
532 SmallString<64> Actual;
533
534 // TestDirectory itself might be under a symlink or have been specified with
535 // a different case than the existing temp directory. In such cases real_path
536 // on the concatenated path will differ in the TestDirectory portion from
537 // how we specified it. Make sure to compare against the real_path of the
538 // TestDirectory, and not just the value of TestDirectory.
539 ASSERT_NO_ERROR(fs::real_path(TestDirectory, RealBase));
540 path::native(Twine(RealBase) + "/test1/test2", Expected);
541
542 ASSERT_NO_ERROR(fs::real_path(
543 Twine(TestDirectory) + "/././test1/../test1/test2/./test3/..", Actual));
544
545 EXPECT_EQ(Expected, Actual);
546
547 SmallString<64> HomeDir;
548 bool Result = llvm::sys::path::home_directory(HomeDir);
549 if (Result) {
550 ASSERT_NO_ERROR(fs::real_path(HomeDir, Expected));
551 ASSERT_NO_ERROR(fs::real_path("~", Actual, true));
552 EXPECT_EQ(Expected, Actual);
553 ASSERT_NO_ERROR(fs::real_path("~/", Actual, true));
554 EXPECT_EQ(Expected, Actual);
555 }
556
557 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/test1"));
558 }
559
560 #ifdef LLVM_ON_UNIX
TEST_F(FileSystemTest,RealPathNoReadPerm)561 TEST_F(FileSystemTest, RealPathNoReadPerm) {
562 SmallString<64> Expanded;
563
564 ASSERT_NO_ERROR(
565 fs::create_directories(Twine(TestDirectory) + "/noreadperm"));
566 ASSERT_TRUE(fs::exists(Twine(TestDirectory) + "/noreadperm"));
567
568 fs::setPermissions(Twine(TestDirectory) + "/noreadperm", fs::no_perms);
569 fs::setPermissions(Twine(TestDirectory) + "/noreadperm", fs::all_exe);
570
571 ASSERT_NO_ERROR(fs::real_path(Twine(TestDirectory) + "/noreadperm", Expanded,
572 false));
573
574 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/noreadperm"));
575 }
576 #endif
577
578
TEST_F(FileSystemTest,TempFileKeepDiscard)579 TEST_F(FileSystemTest, TempFileKeepDiscard) {
580 // We can keep then discard.
581 auto TempFileOrError = fs::TempFile::create(TestDirectory + "/test-%%%%");
582 ASSERT_TRUE((bool)TempFileOrError);
583 fs::TempFile File = std::move(*TempFileOrError);
584 ASSERT_FALSE((bool)File.keep(TestDirectory + "/keep"));
585 ASSERT_FALSE((bool)File.discard());
586 ASSERT_TRUE(fs::exists(TestDirectory + "/keep"));
587 ASSERT_NO_ERROR(fs::remove(TestDirectory + "/keep"));
588 }
589
TEST_F(FileSystemTest,TempFileDiscardDiscard)590 TEST_F(FileSystemTest, TempFileDiscardDiscard) {
591 // We can discard twice.
592 auto TempFileOrError = fs::TempFile::create(TestDirectory + "/test-%%%%");
593 ASSERT_TRUE((bool)TempFileOrError);
594 fs::TempFile File = std::move(*TempFileOrError);
595 ASSERT_FALSE((bool)File.discard());
596 ASSERT_FALSE((bool)File.discard());
597 ASSERT_FALSE(fs::exists(TestDirectory + "/keep"));
598 }
599
TEST_F(FileSystemTest,TempFiles)600 TEST_F(FileSystemTest, TempFiles) {
601 // Create a temp file.
602 int FileDescriptor;
603 SmallString<64> TempPath;
604 ASSERT_NO_ERROR(
605 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
606
607 // Make sure it exists.
608 ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
609
610 // Create another temp tile.
611 int FD2;
612 SmallString<64> TempPath2;
613 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD2, TempPath2));
614 ASSERT_TRUE(TempPath2.endswith(".temp"));
615 ASSERT_NE(TempPath.str(), TempPath2.str());
616
617 fs::file_status A, B;
618 ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
619 ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
620 EXPECT_FALSE(fs::equivalent(A, B));
621
622 ::close(FD2);
623
624 // Remove Temp2.
625 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
626 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
627 ASSERT_EQ(fs::remove(Twine(TempPath2), false),
628 errc::no_such_file_or_directory);
629
630 std::error_code EC = fs::status(TempPath2.c_str(), B);
631 EXPECT_EQ(EC, errc::no_such_file_or_directory);
632 EXPECT_EQ(B.type(), fs::file_type::file_not_found);
633
634 // Make sure Temp2 doesn't exist.
635 ASSERT_EQ(fs::access(Twine(TempPath2), sys::fs::AccessMode::Exist),
636 errc::no_such_file_or_directory);
637
638 SmallString<64> TempPath3;
639 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "", TempPath3));
640 ASSERT_FALSE(TempPath3.endswith("."));
641 FileRemover Cleanup3(TempPath3);
642
643 // Create a hard link to Temp1.
644 ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2)));
645 bool equal;
646 ASSERT_NO_ERROR(fs::equivalent(Twine(TempPath), Twine(TempPath2), equal));
647 EXPECT_TRUE(equal);
648 ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
649 ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
650 EXPECT_TRUE(fs::equivalent(A, B));
651
652 // Remove Temp1.
653 ::close(FileDescriptor);
654 ASSERT_NO_ERROR(fs::remove(Twine(TempPath)));
655
656 // Remove the hard link.
657 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
658
659 // Make sure Temp1 doesn't exist.
660 ASSERT_EQ(fs::access(Twine(TempPath), sys::fs::AccessMode::Exist),
661 errc::no_such_file_or_directory);
662
663 #ifdef _WIN32
664 // Path name > 260 chars should get an error.
665 const char *Path270 =
666 "abcdefghijklmnopqrstuvwxyz9abcdefghijklmnopqrstuvwxyz8"
667 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
668 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
669 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
670 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
671 EXPECT_EQ(fs::createUniqueFile(Path270, FileDescriptor, TempPath),
672 errc::invalid_argument);
673 // Relative path < 247 chars, no problem.
674 const char *Path216 =
675 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
676 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
677 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
678 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
679 ASSERT_NO_ERROR(fs::createTemporaryFile(Path216, "", TempPath));
680 ASSERT_NO_ERROR(fs::remove(Twine(TempPath)));
681 #endif
682 }
683
TEST_F(FileSystemTest,CreateDir)684 TEST_F(FileSystemTest, CreateDir) {
685 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
686 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
687 ASSERT_EQ(fs::create_directory(Twine(TestDirectory) + "foo", false),
688 errc::file_exists);
689 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "foo"));
690
691 #ifdef LLVM_ON_UNIX
692 // Set a 0000 umask so that we can test our directory permissions.
693 mode_t OldUmask = ::umask(0000);
694
695 fs::file_status Status;
696 ASSERT_NO_ERROR(
697 fs::create_directory(Twine(TestDirectory) + "baz500", false,
698 fs::perms::owner_read | fs::perms::owner_exe));
699 ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz500", Status));
700 ASSERT_EQ(Status.permissions() & fs::perms::all_all,
701 fs::perms::owner_read | fs::perms::owner_exe);
702 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "baz777", false,
703 fs::perms::all_all));
704 ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz777", Status));
705 ASSERT_EQ(Status.permissions() & fs::perms::all_all, fs::perms::all_all);
706
707 // Restore umask to be safe.
708 ::umask(OldUmask);
709 #endif
710
711 #ifdef _WIN32
712 // Prove that create_directories() can handle a pathname > 248 characters,
713 // which is the documented limit for CreateDirectory().
714 // (248 is MAX_PATH subtracting room for an 8.3 filename.)
715 // Generate a directory path guaranteed to fall into that range.
716 size_t TmpLen = TestDirectory.size();
717 const char *OneDir = "\\123456789";
718 size_t OneDirLen = strlen(OneDir);
719 ASSERT_LT(OneDirLen, 12U);
720 size_t NLevels = ((248 - TmpLen) / OneDirLen) + 1;
721 SmallString<260> LongDir(TestDirectory);
722 for (size_t I = 0; I < NLevels; ++I)
723 LongDir.append(OneDir);
724 ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir)));
725 ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir)));
726 ASSERT_EQ(fs::create_directories(Twine(LongDir), false),
727 errc::file_exists);
728 // Tidy up, "recursively" removing the directories.
729 StringRef ThisDir(LongDir);
730 for (size_t J = 0; J < NLevels; ++J) {
731 ASSERT_NO_ERROR(fs::remove(ThisDir));
732 ThisDir = path::parent_path(ThisDir);
733 }
734
735 // Also verify that paths with Unix separators are handled correctly.
736 std::string LongPathWithUnixSeparators(TestDirectory.str());
737 // Add at least one subdirectory to TestDirectory, and replace slashes with
738 // backslashes
739 do {
740 LongPathWithUnixSeparators.append("/DirNameWith19Charss");
741 } while (LongPathWithUnixSeparators.size() < 260);
742 std::replace(LongPathWithUnixSeparators.begin(),
743 LongPathWithUnixSeparators.end(),
744 '\\', '/');
745 ASSERT_NO_ERROR(fs::create_directories(Twine(LongPathWithUnixSeparators)));
746 // cleanup
747 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) +
748 "/DirNameWith19Charss"));
749
750 // Similarly for a relative pathname. Need to set the current directory to
751 // TestDirectory so that the one we create ends up in the right place.
752 char PreviousDir[260];
753 size_t PreviousDirLen = ::GetCurrentDirectoryA(260, PreviousDir);
754 ASSERT_GT(PreviousDirLen, 0U);
755 ASSERT_LT(PreviousDirLen, 260U);
756 ASSERT_NE(::SetCurrentDirectoryA(TestDirectory.c_str()), 0);
757 LongDir.clear();
758 // Generate a relative directory name with absolute length > 248.
759 size_t LongDirLen = 249 - TestDirectory.size();
760 LongDir.assign(LongDirLen, 'a');
761 ASSERT_NO_ERROR(fs::create_directory(Twine(LongDir)));
762 // While we're here, prove that .. and . handling works in these long paths.
763 const char *DotDotDirs = "\\..\\.\\b";
764 LongDir.append(DotDotDirs);
765 ASSERT_NO_ERROR(fs::create_directory("b"));
766 ASSERT_EQ(fs::create_directory(Twine(LongDir), false), errc::file_exists);
767 // And clean up.
768 ASSERT_NO_ERROR(fs::remove("b"));
769 ASSERT_NO_ERROR(fs::remove(
770 Twine(LongDir.substr(0, LongDir.size() - strlen(DotDotDirs)))));
771 ASSERT_NE(::SetCurrentDirectoryA(PreviousDir), 0);
772 #endif
773 }
774
TEST_F(FileSystemTest,DirectoryIteration)775 TEST_F(FileSystemTest, DirectoryIteration) {
776 std::error_code ec;
777 for (fs::directory_iterator i(".", ec), e; i != e; i.increment(ec))
778 ASSERT_NO_ERROR(ec);
779
780 // Create a known hierarchy to recurse over.
781 ASSERT_NO_ERROR(
782 fs::create_directories(Twine(TestDirectory) + "/recursive/a0/aa1"));
783 ASSERT_NO_ERROR(
784 fs::create_directories(Twine(TestDirectory) + "/recursive/a0/ab1"));
785 ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) +
786 "/recursive/dontlookhere/da1"));
787 ASSERT_NO_ERROR(
788 fs::create_directories(Twine(TestDirectory) + "/recursive/z0/za1"));
789 ASSERT_NO_ERROR(
790 fs::create_directories(Twine(TestDirectory) + "/recursive/pop/p1"));
791 typedef std::vector<std::string> v_t;
792 v_t visited;
793 for (fs::recursive_directory_iterator i(Twine(TestDirectory)
794 + "/recursive", ec), e; i != e; i.increment(ec)){
795 ASSERT_NO_ERROR(ec);
796 if (path::filename(i->path()) == "p1") {
797 i.pop();
798 // FIXME: recursive_directory_iterator should be more robust.
799 if (i == e) break;
800 }
801 if (path::filename(i->path()) == "dontlookhere")
802 i.no_push();
803 visited.push_back(path::filename(i->path()));
804 }
805 v_t::const_iterator a0 = find(visited, "a0");
806 v_t::const_iterator aa1 = find(visited, "aa1");
807 v_t::const_iterator ab1 = find(visited, "ab1");
808 v_t::const_iterator dontlookhere = find(visited, "dontlookhere");
809 v_t::const_iterator da1 = find(visited, "da1");
810 v_t::const_iterator z0 = find(visited, "z0");
811 v_t::const_iterator za1 = find(visited, "za1");
812 v_t::const_iterator pop = find(visited, "pop");
813 v_t::const_iterator p1 = find(visited, "p1");
814
815 // Make sure that each path was visited correctly.
816 ASSERT_NE(a0, visited.end());
817 ASSERT_NE(aa1, visited.end());
818 ASSERT_NE(ab1, visited.end());
819 ASSERT_NE(dontlookhere, visited.end());
820 ASSERT_EQ(da1, visited.end()); // Not visited.
821 ASSERT_NE(z0, visited.end());
822 ASSERT_NE(za1, visited.end());
823 ASSERT_NE(pop, visited.end());
824 ASSERT_EQ(p1, visited.end()); // Not visited.
825
826 // Make sure that parents were visited before children. No other ordering
827 // guarantees can be made across siblings.
828 ASSERT_LT(a0, aa1);
829 ASSERT_LT(a0, ab1);
830 ASSERT_LT(z0, za1);
831
832 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/aa1"));
833 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/ab1"));
834 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0"));
835 ASSERT_NO_ERROR(
836 fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere/da1"));
837 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere"));
838 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop/p1"));
839 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop"));
840 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0/za1"));
841 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0"));
842 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive"));
843
844 // Test recursive_directory_iterator level()
845 ASSERT_NO_ERROR(
846 fs::create_directories(Twine(TestDirectory) + "/reclevel/a/b/c"));
847 fs::recursive_directory_iterator I(Twine(TestDirectory) + "/reclevel", ec), E;
848 for (int l = 0; I != E; I.increment(ec), ++l) {
849 ASSERT_NO_ERROR(ec);
850 EXPECT_EQ(I.level(), l);
851 }
852 EXPECT_EQ(I, E);
853 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a/b/c"));
854 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a/b"));
855 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a"));
856 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel"));
857 }
858
859 #ifdef LLVM_ON_UNIX
TEST_F(FileSystemTest,BrokenSymlinkDirectoryIteration)860 TEST_F(FileSystemTest, BrokenSymlinkDirectoryIteration) {
861 // Create a known hierarchy to recurse over.
862 ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) + "/symlink"));
863 ASSERT_NO_ERROR(
864 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/a"));
865 ASSERT_NO_ERROR(
866 fs::create_directories(Twine(TestDirectory) + "/symlink/b/bb"));
867 ASSERT_NO_ERROR(
868 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/b/ba"));
869 ASSERT_NO_ERROR(
870 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/b/bc"));
871 ASSERT_NO_ERROR(
872 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/c"));
873 ASSERT_NO_ERROR(
874 fs::create_directories(Twine(TestDirectory) + "/symlink/d/dd/ddd"));
875 ASSERT_NO_ERROR(fs::create_link(Twine(TestDirectory) + "/symlink/d/dd",
876 Twine(TestDirectory) + "/symlink/d/da"));
877 ASSERT_NO_ERROR(
878 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/e"));
879
880 typedef std::vector<std::string> v_t;
881 v_t VisitedNonBrokenSymlinks;
882 v_t VisitedBrokenSymlinks;
883 std::error_code ec;
884
885 // Broken symbol links are expected to throw an error.
886 for (fs::directory_iterator i(Twine(TestDirectory) + "/symlink", ec), e;
887 i != e; i.increment(ec)) {
888 if (ec == std::make_error_code(std::errc::no_such_file_or_directory)) {
889 VisitedBrokenSymlinks.push_back(path::filename(i->path()));
890 continue;
891 }
892
893 ASSERT_NO_ERROR(ec);
894 VisitedNonBrokenSymlinks.push_back(path::filename(i->path()));
895 }
896 llvm::sort(VisitedNonBrokenSymlinks.begin(), VisitedNonBrokenSymlinks.end());
897 llvm::sort(VisitedBrokenSymlinks.begin(), VisitedBrokenSymlinks.end());
898 v_t ExpectedNonBrokenSymlinks = {"b", "d"};
899 ASSERT_EQ(ExpectedNonBrokenSymlinks.size(), VisitedNonBrokenSymlinks.size());
900 ASSERT_TRUE(std::equal(VisitedNonBrokenSymlinks.begin(),
901 VisitedNonBrokenSymlinks.end(),
902 ExpectedNonBrokenSymlinks.begin()));
903 VisitedNonBrokenSymlinks.clear();
904
905 v_t ExpectedBrokenSymlinks = {"a", "c", "e"};
906 ASSERT_EQ(ExpectedBrokenSymlinks.size(), VisitedBrokenSymlinks.size());
907 ASSERT_TRUE(std::equal(VisitedBrokenSymlinks.begin(),
908 VisitedBrokenSymlinks.end(),
909 ExpectedBrokenSymlinks.begin()));
910 VisitedBrokenSymlinks.clear();
911
912 // Broken symbol links are expected to throw an error.
913 for (fs::recursive_directory_iterator i(
914 Twine(TestDirectory) + "/symlink", ec), e; i != e; i.increment(ec)) {
915 if (ec == std::make_error_code(std::errc::no_such_file_or_directory)) {
916 VisitedBrokenSymlinks.push_back(path::filename(i->path()));
917 continue;
918 }
919
920 ASSERT_NO_ERROR(ec);
921 VisitedNonBrokenSymlinks.push_back(path::filename(i->path()));
922 }
923 llvm::sort(VisitedNonBrokenSymlinks.begin(), VisitedNonBrokenSymlinks.end());
924 llvm::sort(VisitedBrokenSymlinks.begin(), VisitedBrokenSymlinks.end());
925 ExpectedNonBrokenSymlinks = {"b", "bb", "d", "da", "dd", "ddd", "ddd"};
926 ASSERT_EQ(ExpectedNonBrokenSymlinks.size(), VisitedNonBrokenSymlinks.size());
927 ASSERT_TRUE(std::equal(VisitedNonBrokenSymlinks.begin(),
928 VisitedNonBrokenSymlinks.end(),
929 ExpectedNonBrokenSymlinks.begin()));
930 VisitedNonBrokenSymlinks.clear();
931
932 ExpectedBrokenSymlinks = {"a", "ba", "bc", "c", "e"};
933 ASSERT_EQ(ExpectedBrokenSymlinks.size(), VisitedBrokenSymlinks.size());
934 ASSERT_TRUE(std::equal(VisitedBrokenSymlinks.begin(),
935 VisitedBrokenSymlinks.end(),
936 ExpectedBrokenSymlinks.begin()));
937 VisitedBrokenSymlinks.clear();
938
939 for (fs::recursive_directory_iterator i(
940 Twine(TestDirectory) + "/symlink", ec, /*follow_symlinks=*/false), e;
941 i != e; i.increment(ec)) {
942 if (ec == std::make_error_code(std::errc::no_such_file_or_directory)) {
943 VisitedBrokenSymlinks.push_back(path::filename(i->path()));
944 continue;
945 }
946
947 ASSERT_NO_ERROR(ec);
948 VisitedNonBrokenSymlinks.push_back(path::filename(i->path()));
949 }
950 llvm::sort(VisitedNonBrokenSymlinks.begin(), VisitedNonBrokenSymlinks.end());
951 llvm::sort(VisitedBrokenSymlinks.begin(), VisitedBrokenSymlinks.end());
952 ExpectedNonBrokenSymlinks = {"a", "b", "ba", "bb", "bc", "c", "d", "da", "dd",
953 "ddd", "e"};
954 ASSERT_EQ(ExpectedNonBrokenSymlinks.size(), VisitedNonBrokenSymlinks.size());
955 ASSERT_TRUE(std::equal(VisitedNonBrokenSymlinks.begin(),
956 VisitedNonBrokenSymlinks.end(),
957 ExpectedNonBrokenSymlinks.begin()));
958 VisitedNonBrokenSymlinks.clear();
959
960 ExpectedBrokenSymlinks = {};
961 ASSERT_EQ(ExpectedBrokenSymlinks.size(), VisitedBrokenSymlinks.size());
962 ASSERT_TRUE(std::equal(VisitedBrokenSymlinks.begin(),
963 VisitedBrokenSymlinks.end(),
964 ExpectedBrokenSymlinks.begin()));
965 VisitedBrokenSymlinks.clear();
966
967 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/symlink"));
968 }
969 #endif
970
TEST_F(FileSystemTest,Remove)971 TEST_F(FileSystemTest, Remove) {
972 SmallString<64> BaseDir;
973 SmallString<64> Paths[4];
974 int fds[4];
975 ASSERT_NO_ERROR(fs::createUniqueDirectory("fs_remove", BaseDir));
976
977 ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir) + "/foo/bar/baz"));
978 ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir) + "/foo/bar/buzz"));
979 ASSERT_NO_ERROR(fs::createUniqueFile(
980 Twine(BaseDir) + "/foo/bar/baz/%%%%%%.tmp", fds[0], Paths[0]));
981 ASSERT_NO_ERROR(fs::createUniqueFile(
982 Twine(BaseDir) + "/foo/bar/baz/%%%%%%.tmp", fds[1], Paths[1]));
983 ASSERT_NO_ERROR(fs::createUniqueFile(
984 Twine(BaseDir) + "/foo/bar/buzz/%%%%%%.tmp", fds[2], Paths[2]));
985 ASSERT_NO_ERROR(fs::createUniqueFile(
986 Twine(BaseDir) + "/foo/bar/buzz/%%%%%%.tmp", fds[3], Paths[3]));
987
988 for (int fd : fds)
989 ::close(fd);
990
991 EXPECT_TRUE(fs::exists(Twine(BaseDir) + "/foo/bar/baz"));
992 EXPECT_TRUE(fs::exists(Twine(BaseDir) + "/foo/bar/buzz"));
993 EXPECT_TRUE(fs::exists(Paths[0]));
994 EXPECT_TRUE(fs::exists(Paths[1]));
995 EXPECT_TRUE(fs::exists(Paths[2]));
996 EXPECT_TRUE(fs::exists(Paths[3]));
997
998 ASSERT_NO_ERROR(fs::remove_directories("D:/footest"));
999
1000 ASSERT_NO_ERROR(fs::remove_directories(BaseDir));
1001 ASSERT_FALSE(fs::exists(BaseDir));
1002 }
1003
1004 #ifdef _WIN32
TEST_F(FileSystemTest,CarriageReturn)1005 TEST_F(FileSystemTest, CarriageReturn) {
1006 SmallString<128> FilePathname(TestDirectory);
1007 std::error_code EC;
1008 path::append(FilePathname, "test");
1009
1010 {
1011 raw_fd_ostream File(FilePathname, EC, sys::fs::F_Text);
1012 ASSERT_NO_ERROR(EC);
1013 File << '\n';
1014 }
1015 {
1016 auto Buf = MemoryBuffer::getFile(FilePathname.str());
1017 EXPECT_TRUE((bool)Buf);
1018 EXPECT_EQ(Buf.get()->getBuffer(), "\r\n");
1019 }
1020
1021 {
1022 raw_fd_ostream File(FilePathname, EC, sys::fs::F_None);
1023 ASSERT_NO_ERROR(EC);
1024 File << '\n';
1025 }
1026 {
1027 auto Buf = MemoryBuffer::getFile(FilePathname.str());
1028 EXPECT_TRUE((bool)Buf);
1029 EXPECT_EQ(Buf.get()->getBuffer(), "\n");
1030 }
1031 ASSERT_NO_ERROR(fs::remove(Twine(FilePathname)));
1032 }
1033 #endif
1034
TEST_F(FileSystemTest,Resize)1035 TEST_F(FileSystemTest, Resize) {
1036 int FD;
1037 SmallString<64> TempPath;
1038 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1039 ASSERT_NO_ERROR(fs::resize_file(FD, 123));
1040 fs::file_status Status;
1041 ASSERT_NO_ERROR(fs::status(FD, Status));
1042 ASSERT_EQ(Status.getSize(), 123U);
1043 ::close(FD);
1044 ASSERT_NO_ERROR(fs::remove(TempPath));
1045 }
1046
TEST_F(FileSystemTest,MD5)1047 TEST_F(FileSystemTest, MD5) {
1048 int FD;
1049 SmallString<64> TempPath;
1050 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1051 StringRef Data("abcdefghijklmnopqrstuvwxyz");
1052 ASSERT_EQ(write(FD, Data.data(), Data.size()), static_cast<ssize_t>(Data.size()));
1053 lseek(FD, 0, SEEK_SET);
1054 auto Hash = fs::md5_contents(FD);
1055 ::close(FD);
1056 ASSERT_NO_ERROR(Hash.getError());
1057
1058 EXPECT_STREQ("c3fcd3d76192e4007dfb496cca67e13b", Hash->digest().c_str());
1059 }
1060
TEST_F(FileSystemTest,FileMapping)1061 TEST_F(FileSystemTest, FileMapping) {
1062 // Create a temp file.
1063 int FileDescriptor;
1064 SmallString<64> TempPath;
1065 ASSERT_NO_ERROR(
1066 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
1067 unsigned Size = 4096;
1068 ASSERT_NO_ERROR(fs::resize_file(FileDescriptor, Size));
1069
1070 // Map in temp file and add some content
1071 std::error_code EC;
1072 StringRef Val("hello there");
1073 {
1074 fs::mapped_file_region mfr(FileDescriptor,
1075 fs::mapped_file_region::readwrite, Size, 0, EC);
1076 ASSERT_NO_ERROR(EC);
1077 std::copy(Val.begin(), Val.end(), mfr.data());
1078 // Explicitly add a 0.
1079 mfr.data()[Val.size()] = 0;
1080 // Unmap temp file
1081 }
1082 ASSERT_EQ(close(FileDescriptor), 0);
1083
1084 // Map it back in read-only
1085 {
1086 int FD;
1087 EC = fs::openFileForRead(Twine(TempPath), FD);
1088 ASSERT_NO_ERROR(EC);
1089 fs::mapped_file_region mfr(FD, fs::mapped_file_region::readonly, Size, 0, EC);
1090 ASSERT_NO_ERROR(EC);
1091
1092 // Verify content
1093 EXPECT_EQ(StringRef(mfr.const_data()), Val);
1094
1095 // Unmap temp file
1096 fs::mapped_file_region m(FD, fs::mapped_file_region::readonly, Size, 0, EC);
1097 ASSERT_NO_ERROR(EC);
1098 ASSERT_EQ(close(FD), 0);
1099 }
1100 ASSERT_NO_ERROR(fs::remove(TempPath));
1101 }
1102
TEST(Support,NormalizePath)1103 TEST(Support, NormalizePath) {
1104 using TestTuple = std::tuple<const char *, const char *, const char *>;
1105 std::vector<TestTuple> Tests;
1106 Tests.emplace_back("a", "a", "a");
1107 Tests.emplace_back("a/b", "a\\b", "a/b");
1108 Tests.emplace_back("a\\b", "a\\b", "a/b");
1109 Tests.emplace_back("a\\\\b", "a\\\\b", "a\\\\b");
1110 Tests.emplace_back("\\a", "\\a", "/a");
1111 Tests.emplace_back("a\\", "a\\", "a/");
1112
1113 for (auto &T : Tests) {
1114 SmallString<64> Win(std::get<0>(T));
1115 SmallString<64> Posix(Win);
1116 path::native(Win, path::Style::windows);
1117 path::native(Posix, path::Style::posix);
1118 EXPECT_EQ(std::get<1>(T), Win);
1119 EXPECT_EQ(std::get<2>(T), Posix);
1120 }
1121
1122 #if defined(_WIN32)
1123 SmallString<64> PathHome;
1124 path::home_directory(PathHome);
1125
1126 const char *Path7a = "~/aaa";
1127 SmallString<64> Path7(Path7a);
1128 path::native(Path7);
1129 EXPECT_TRUE(Path7.endswith("\\aaa"));
1130 EXPECT_TRUE(Path7.startswith(PathHome));
1131 EXPECT_EQ(Path7.size(), PathHome.size() + strlen(Path7a + 1));
1132
1133 const char *Path8a = "~";
1134 SmallString<64> Path8(Path8a);
1135 path::native(Path8);
1136 EXPECT_EQ(Path8, PathHome);
1137
1138 const char *Path9a = "~aaa";
1139 SmallString<64> Path9(Path9a);
1140 path::native(Path9);
1141 EXPECT_EQ(Path9, "~aaa");
1142
1143 const char *Path10a = "aaa/~/b";
1144 SmallString<64> Path10(Path10a);
1145 path::native(Path10);
1146 EXPECT_EQ(Path10, "aaa\\~\\b");
1147 #endif
1148 }
1149
TEST(Support,RemoveLeadingDotSlash)1150 TEST(Support, RemoveLeadingDotSlash) {
1151 StringRef Path1("././/foolz/wat");
1152 StringRef Path2("./////");
1153
1154 Path1 = path::remove_leading_dotslash(Path1);
1155 EXPECT_EQ(Path1, "foolz/wat");
1156 Path2 = path::remove_leading_dotslash(Path2);
1157 EXPECT_EQ(Path2, "");
1158 }
1159
remove_dots(StringRef path,bool remove_dot_dot,path::Style style)1160 static std::string remove_dots(StringRef path, bool remove_dot_dot,
1161 path::Style style) {
1162 SmallString<256> buffer(path);
1163 path::remove_dots(buffer, remove_dot_dot, style);
1164 return buffer.str();
1165 }
1166
TEST(Support,RemoveDots)1167 TEST(Support, RemoveDots) {
1168 EXPECT_EQ("foolz\\wat",
1169 remove_dots(".\\.\\\\foolz\\wat", false, path::Style::windows));
1170 EXPECT_EQ("", remove_dots(".\\\\\\\\\\", false, path::Style::windows));
1171
1172 EXPECT_EQ("a\\..\\b\\c",
1173 remove_dots(".\\a\\..\\b\\c", false, path::Style::windows));
1174 EXPECT_EQ("b\\c", remove_dots(".\\a\\..\\b\\c", true, path::Style::windows));
1175 EXPECT_EQ("c", remove_dots(".\\.\\c", true, path::Style::windows));
1176 EXPECT_EQ("..\\a\\c",
1177 remove_dots("..\\a\\b\\..\\c", true, path::Style::windows));
1178 EXPECT_EQ("..\\..\\a\\c",
1179 remove_dots("..\\..\\a\\b\\..\\c", true, path::Style::windows));
1180
1181 SmallString<64> Path1(".\\.\\c");
1182 EXPECT_TRUE(path::remove_dots(Path1, true, path::Style::windows));
1183 EXPECT_EQ("c", Path1);
1184
1185 EXPECT_EQ("foolz/wat",
1186 remove_dots("././/foolz/wat", false, path::Style::posix));
1187 EXPECT_EQ("", remove_dots("./////", false, path::Style::posix));
1188
1189 EXPECT_EQ("a/../b/c", remove_dots("./a/../b/c", false, path::Style::posix));
1190 EXPECT_EQ("b/c", remove_dots("./a/../b/c", true, path::Style::posix));
1191 EXPECT_EQ("c", remove_dots("././c", true, path::Style::posix));
1192 EXPECT_EQ("../a/c", remove_dots("../a/b/../c", true, path::Style::posix));
1193 EXPECT_EQ("../../a/c",
1194 remove_dots("../../a/b/../c", true, path::Style::posix));
1195 EXPECT_EQ("/a/c", remove_dots("/../../a/c", true, path::Style::posix));
1196 EXPECT_EQ("/a/c",
1197 remove_dots("/../a/b//../././/c", true, path::Style::posix));
1198
1199 SmallString<64> Path2("././c");
1200 EXPECT_TRUE(path::remove_dots(Path2, true, path::Style::posix));
1201 EXPECT_EQ("c", Path2);
1202 }
1203
TEST(Support,ReplacePathPrefix)1204 TEST(Support, ReplacePathPrefix) {
1205 SmallString<64> Path1("/foo");
1206 SmallString<64> Path2("/old/foo");
1207 SmallString<64> OldPrefix("/old");
1208 SmallString<64> NewPrefix("/new");
1209 SmallString<64> NewPrefix2("/longernew");
1210 SmallString<64> EmptyPrefix("");
1211
1212 SmallString<64> Path = Path1;
1213 path::replace_path_prefix(Path, OldPrefix, NewPrefix);
1214 EXPECT_EQ(Path, "/foo");
1215 Path = Path2;
1216 path::replace_path_prefix(Path, OldPrefix, NewPrefix);
1217 EXPECT_EQ(Path, "/new/foo");
1218 Path = Path2;
1219 path::replace_path_prefix(Path, OldPrefix, NewPrefix2);
1220 EXPECT_EQ(Path, "/longernew/foo");
1221 Path = Path1;
1222 path::replace_path_prefix(Path, EmptyPrefix, NewPrefix);
1223 EXPECT_EQ(Path, "/new/foo");
1224 Path = Path2;
1225 path::replace_path_prefix(Path, OldPrefix, EmptyPrefix);
1226 EXPECT_EQ(Path, "/foo");
1227 }
1228
TEST_F(FileSystemTest,OpenFileForRead)1229 TEST_F(FileSystemTest, OpenFileForRead) {
1230 // Create a temp file.
1231 int FileDescriptor;
1232 SmallString<64> TempPath;
1233 ASSERT_NO_ERROR(
1234 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
1235 FileRemover Cleanup(TempPath);
1236
1237 // Make sure it exists.
1238 ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
1239
1240 // Open the file for read
1241 int FileDescriptor2;
1242 SmallString<64> ResultPath;
1243 ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath), FileDescriptor2,
1244 fs::OF_None, &ResultPath))
1245
1246 // If we succeeded, check that the paths are the same (modulo case):
1247 if (!ResultPath.empty()) {
1248 // The paths returned by createTemporaryFile and getPathFromOpenFD
1249 // should reference the same file on disk.
1250 fs::UniqueID D1, D2;
1251 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), D1));
1252 ASSERT_NO_ERROR(fs::getUniqueID(Twine(ResultPath), D2));
1253 ASSERT_EQ(D1, D2);
1254 }
1255 ::close(FileDescriptor);
1256 ::close(FileDescriptor2);
1257
1258 #ifdef _WIN32
1259 // Since Windows Vista, file access time is not updated by default.
1260 // This is instead updated manually by openFileForRead.
1261 // https://blogs.technet.microsoft.com/filecab/2006/11/07/disabling-last-access-time-in-windows-vista-to-improve-ntfs-performance/
1262 // This part of the unit test is Windows specific as the updating of
1263 // access times can be disabled on Linux using /etc/fstab.
1264
1265 // Set access time to UNIX epoch.
1266 ASSERT_NO_ERROR(sys::fs::openFileForWrite(Twine(TempPath), FileDescriptor,
1267 fs::CD_OpenExisting));
1268 TimePoint<> Epoch(std::chrono::milliseconds(0));
1269 ASSERT_NO_ERROR(fs::setLastModificationAndAccessTime(FileDescriptor, Epoch));
1270 ::close(FileDescriptor);
1271
1272 // Open the file and ensure access time is updated, when forced.
1273 ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath), FileDescriptor,
1274 fs::OF_UpdateAtime, &ResultPath));
1275
1276 sys::fs::file_status Status;
1277 ASSERT_NO_ERROR(sys::fs::status(FileDescriptor, Status));
1278 auto FileAccessTime = Status.getLastAccessedTime();
1279
1280 ASSERT_NE(Epoch, FileAccessTime);
1281 ::close(FileDescriptor);
1282
1283 // Ideally this test would include a case when ATime is not forced to update,
1284 // however the expected behaviour will differ depending on the configuration
1285 // of the Windows file system.
1286 #endif
1287 }
1288
createFileWithData(const Twine & Path,bool ShouldExistBefore,fs::CreationDisposition Disp,StringRef Data)1289 static void createFileWithData(const Twine &Path, bool ShouldExistBefore,
1290 fs::CreationDisposition Disp, StringRef Data) {
1291 int FD;
1292 ASSERT_EQ(ShouldExistBefore, fs::exists(Path));
1293 ASSERT_NO_ERROR(fs::openFileForWrite(Path, FD, Disp));
1294 FileDescriptorCloser Closer(FD);
1295 ASSERT_TRUE(fs::exists(Path));
1296
1297 ASSERT_EQ(Data.size(), (size_t)write(FD, Data.data(), Data.size()));
1298 }
1299
verifyFileContents(const Twine & Path,StringRef Contents)1300 static void verifyFileContents(const Twine &Path, StringRef Contents) {
1301 auto Buffer = MemoryBuffer::getFile(Path);
1302 ASSERT_TRUE((bool)Buffer);
1303 StringRef Data = Buffer.get()->getBuffer();
1304 ASSERT_EQ(Data, Contents);
1305 }
1306
TEST_F(FileSystemTest,CreateNew)1307 TEST_F(FileSystemTest, CreateNew) {
1308 int FD;
1309 Optional<FileDescriptorCloser> Closer;
1310
1311 // Succeeds if the file does not exist.
1312 ASSERT_FALSE(fs::exists(NonExistantFile));
1313 ASSERT_NO_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateNew));
1314 ASSERT_TRUE(fs::exists(NonExistantFile));
1315
1316 FileRemover Cleanup(NonExistantFile);
1317 Closer.emplace(FD);
1318
1319 // And creates a file of size 0.
1320 sys::fs::file_status Status;
1321 ASSERT_NO_ERROR(sys::fs::status(FD, Status));
1322 EXPECT_EQ(0ULL, Status.getSize());
1323
1324 // Close this first, before trying to re-open the file.
1325 Closer.reset();
1326
1327 // But fails if the file does exist.
1328 ASSERT_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateNew));
1329 }
1330
TEST_F(FileSystemTest,CreateAlways)1331 TEST_F(FileSystemTest, CreateAlways) {
1332 int FD;
1333 Optional<FileDescriptorCloser> Closer;
1334
1335 // Succeeds if the file does not exist.
1336 ASSERT_FALSE(fs::exists(NonExistantFile));
1337 ASSERT_NO_ERROR(
1338 fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateAlways));
1339
1340 Closer.emplace(FD);
1341
1342 ASSERT_TRUE(fs::exists(NonExistantFile));
1343
1344 FileRemover Cleanup(NonExistantFile);
1345
1346 // And creates a file of size 0.
1347 uint64_t FileSize;
1348 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1349 ASSERT_EQ(0ULL, FileSize);
1350
1351 // If we write some data to it re-create it with CreateAlways, it succeeds and
1352 // truncates to 0 bytes.
1353 ASSERT_EQ(4, write(FD, "Test", 4));
1354
1355 Closer.reset();
1356
1357 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1358 ASSERT_EQ(4ULL, FileSize);
1359
1360 ASSERT_NO_ERROR(
1361 fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateAlways));
1362 Closer.emplace(FD);
1363 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1364 ASSERT_EQ(0ULL, FileSize);
1365 }
1366
TEST_F(FileSystemTest,OpenExisting)1367 TEST_F(FileSystemTest, OpenExisting) {
1368 int FD;
1369
1370 // Fails if the file does not exist.
1371 ASSERT_FALSE(fs::exists(NonExistantFile));
1372 ASSERT_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_OpenExisting));
1373 ASSERT_FALSE(fs::exists(NonExistantFile));
1374
1375 // Make a dummy file now so that we can try again when the file does exist.
1376 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1377 FileRemover Cleanup(NonExistantFile);
1378 uint64_t FileSize;
1379 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1380 ASSERT_EQ(4ULL, FileSize);
1381
1382 // If we re-create it with different data, it overwrites rather than
1383 // appending.
1384 createFileWithData(NonExistantFile, true, fs::CD_OpenExisting, "Buzz");
1385 verifyFileContents(NonExistantFile, "Buzz");
1386 }
1387
TEST_F(FileSystemTest,OpenAlways)1388 TEST_F(FileSystemTest, OpenAlways) {
1389 // Succeeds if the file does not exist.
1390 createFileWithData(NonExistantFile, false, fs::CD_OpenAlways, "Fizz");
1391 FileRemover Cleanup(NonExistantFile);
1392 uint64_t FileSize;
1393 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1394 ASSERT_EQ(4ULL, FileSize);
1395
1396 // Now re-open it and write again, verifying the contents get over-written.
1397 createFileWithData(NonExistantFile, true, fs::CD_OpenAlways, "Bu");
1398 verifyFileContents(NonExistantFile, "Buzz");
1399 }
1400
TEST_F(FileSystemTest,AppendSetsCorrectFileOffset)1401 TEST_F(FileSystemTest, AppendSetsCorrectFileOffset) {
1402 fs::CreationDisposition Disps[] = {fs::CD_CreateAlways, fs::CD_OpenAlways,
1403 fs::CD_OpenExisting};
1404
1405 // Write some data and re-open it with every possible disposition (this is a
1406 // hack that shouldn't work, but is left for compatibility. F_Append
1407 // overrides
1408 // the specified disposition.
1409 for (fs::CreationDisposition Disp : Disps) {
1410 int FD;
1411 Optional<FileDescriptorCloser> Closer;
1412
1413 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1414
1415 FileRemover Cleanup(NonExistantFile);
1416
1417 uint64_t FileSize;
1418 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1419 ASSERT_EQ(4ULL, FileSize);
1420 ASSERT_NO_ERROR(
1421 fs::openFileForWrite(NonExistantFile, FD, Disp, fs::OF_Append));
1422 Closer.emplace(FD);
1423 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1424 ASSERT_EQ(4ULL, FileSize);
1425
1426 ASSERT_EQ(4, write(FD, "Buzz", 4));
1427 Closer.reset();
1428
1429 verifyFileContents(NonExistantFile, "FizzBuzz");
1430 }
1431 }
1432
verifyRead(int FD,StringRef Data,bool ShouldSucceed)1433 static void verifyRead(int FD, StringRef Data, bool ShouldSucceed) {
1434 std::vector<char> Buffer;
1435 Buffer.resize(Data.size());
1436 int Result = ::read(FD, Buffer.data(), Buffer.size());
1437 if (ShouldSucceed) {
1438 ASSERT_EQ((size_t)Result, Data.size());
1439 ASSERT_EQ(Data, StringRef(Buffer.data(), Buffer.size()));
1440 } else {
1441 ASSERT_EQ(-1, Result);
1442 ASSERT_EQ(EBADF, errno);
1443 }
1444 }
1445
verifyWrite(int FD,StringRef Data,bool ShouldSucceed)1446 static void verifyWrite(int FD, StringRef Data, bool ShouldSucceed) {
1447 int Result = ::write(FD, Data.data(), Data.size());
1448 if (ShouldSucceed)
1449 ASSERT_EQ((size_t)Result, Data.size());
1450 else {
1451 ASSERT_EQ(-1, Result);
1452 ASSERT_EQ(EBADF, errno);
1453 }
1454 }
1455
TEST_F(FileSystemTest,ReadOnlyFileCantWrite)1456 TEST_F(FileSystemTest, ReadOnlyFileCantWrite) {
1457 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1458 FileRemover Cleanup(NonExistantFile);
1459
1460 int FD;
1461 ASSERT_NO_ERROR(fs::openFileForRead(NonExistantFile, FD));
1462 FileDescriptorCloser Closer(FD);
1463
1464 verifyWrite(FD, "Buzz", false);
1465 verifyRead(FD, "Fizz", true);
1466 }
1467
TEST_F(FileSystemTest,WriteOnlyFileCantRead)1468 TEST_F(FileSystemTest, WriteOnlyFileCantRead) {
1469 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1470 FileRemover Cleanup(NonExistantFile);
1471
1472 int FD;
1473 ASSERT_NO_ERROR(
1474 fs::openFileForWrite(NonExistantFile, FD, fs::CD_OpenExisting));
1475 FileDescriptorCloser Closer(FD);
1476 verifyRead(FD, "Fizz", false);
1477 verifyWrite(FD, "Buzz", true);
1478 }
1479
TEST_F(FileSystemTest,ReadWriteFileCanReadOrWrite)1480 TEST_F(FileSystemTest, ReadWriteFileCanReadOrWrite) {
1481 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1482 FileRemover Cleanup(NonExistantFile);
1483
1484 int FD;
1485 ASSERT_NO_ERROR(fs::openFileForReadWrite(NonExistantFile, FD,
1486 fs::CD_OpenExisting, fs::OF_None));
1487 FileDescriptorCloser Closer(FD);
1488 verifyRead(FD, "Fizz", true);
1489 verifyWrite(FD, "Buzz", true);
1490 }
1491
TEST_F(FileSystemTest,set_current_path)1492 TEST_F(FileSystemTest, set_current_path) {
1493 SmallString<128> path;
1494
1495 ASSERT_NO_ERROR(fs::current_path(path));
1496 ASSERT_NE(TestDirectory, path);
1497
1498 struct RestorePath {
1499 SmallString<128> path;
1500 RestorePath(const SmallString<128> &path) : path(path) {}
1501 ~RestorePath() { fs::set_current_path(path); }
1502 } restore_path(path);
1503
1504 ASSERT_NO_ERROR(fs::set_current_path(TestDirectory));
1505
1506 ASSERT_NO_ERROR(fs::current_path(path));
1507
1508 fs::UniqueID D1, D2;
1509 ASSERT_NO_ERROR(fs::getUniqueID(TestDirectory, D1));
1510 ASSERT_NO_ERROR(fs::getUniqueID(path, D2));
1511 ASSERT_EQ(D1, D2) << "D1: " << TestDirectory << "\nD2: " << path;
1512 }
1513
TEST_F(FileSystemTest,permissions)1514 TEST_F(FileSystemTest, permissions) {
1515 int FD;
1516 SmallString<64> TempPath;
1517 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1518 FileRemover Cleanup(TempPath);
1519
1520 // Make sure it exists.
1521 ASSERT_TRUE(fs::exists(Twine(TempPath)));
1522
1523 auto CheckPermissions = [&](fs::perms Expected) {
1524 ErrorOr<fs::perms> Actual = fs::getPermissions(TempPath);
1525 return Actual && *Actual == Expected;
1526 };
1527
1528 std::error_code NoError;
1529 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_all), NoError);
1530 EXPECT_TRUE(CheckPermissions(fs::all_all));
1531
1532 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read | fs::all_exe), NoError);
1533 EXPECT_TRUE(CheckPermissions(fs::all_read | fs::all_exe));
1534
1535 #if defined(_WIN32)
1536 fs::perms ReadOnly = fs::all_read | fs::all_exe;
1537 EXPECT_EQ(fs::setPermissions(TempPath, fs::no_perms), NoError);
1538 EXPECT_TRUE(CheckPermissions(ReadOnly));
1539
1540 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_read), NoError);
1541 EXPECT_TRUE(CheckPermissions(ReadOnly));
1542
1543 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_write), NoError);
1544 EXPECT_TRUE(CheckPermissions(fs::all_all));
1545
1546 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_exe), NoError);
1547 EXPECT_TRUE(CheckPermissions(ReadOnly));
1548
1549 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_all), NoError);
1550 EXPECT_TRUE(CheckPermissions(fs::all_all));
1551
1552 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_read), NoError);
1553 EXPECT_TRUE(CheckPermissions(ReadOnly));
1554
1555 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_write), NoError);
1556 EXPECT_TRUE(CheckPermissions(fs::all_all));
1557
1558 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_exe), NoError);
1559 EXPECT_TRUE(CheckPermissions(ReadOnly));
1560
1561 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_all), NoError);
1562 EXPECT_TRUE(CheckPermissions(fs::all_all));
1563
1564 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_read), NoError);
1565 EXPECT_TRUE(CheckPermissions(ReadOnly));
1566
1567 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_write), NoError);
1568 EXPECT_TRUE(CheckPermissions(fs::all_all));
1569
1570 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_exe), NoError);
1571 EXPECT_TRUE(CheckPermissions(ReadOnly));
1572
1573 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_all), NoError);
1574 EXPECT_TRUE(CheckPermissions(fs::all_all));
1575
1576 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read), NoError);
1577 EXPECT_TRUE(CheckPermissions(ReadOnly));
1578
1579 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_write), NoError);
1580 EXPECT_TRUE(CheckPermissions(fs::all_all));
1581
1582 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_exe), NoError);
1583 EXPECT_TRUE(CheckPermissions(ReadOnly));
1584
1585 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe), NoError);
1586 EXPECT_TRUE(CheckPermissions(ReadOnly));
1587
1588 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_gid_on_exe), NoError);
1589 EXPECT_TRUE(CheckPermissions(ReadOnly));
1590
1591 EXPECT_EQ(fs::setPermissions(TempPath, fs::sticky_bit), NoError);
1592 EXPECT_TRUE(CheckPermissions(ReadOnly));
1593
1594 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe |
1595 fs::set_gid_on_exe |
1596 fs::sticky_bit),
1597 NoError);
1598 EXPECT_TRUE(CheckPermissions(ReadOnly));
1599
1600 EXPECT_EQ(fs::setPermissions(TempPath, ReadOnly | fs::set_uid_on_exe |
1601 fs::set_gid_on_exe |
1602 fs::sticky_bit),
1603 NoError);
1604 EXPECT_TRUE(CheckPermissions(ReadOnly));
1605
1606 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms), NoError);
1607 EXPECT_TRUE(CheckPermissions(fs::all_all));
1608 #else
1609 EXPECT_EQ(fs::setPermissions(TempPath, fs::no_perms), NoError);
1610 EXPECT_TRUE(CheckPermissions(fs::no_perms));
1611
1612 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_read), NoError);
1613 EXPECT_TRUE(CheckPermissions(fs::owner_read));
1614
1615 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_write), NoError);
1616 EXPECT_TRUE(CheckPermissions(fs::owner_write));
1617
1618 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_exe), NoError);
1619 EXPECT_TRUE(CheckPermissions(fs::owner_exe));
1620
1621 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_all), NoError);
1622 EXPECT_TRUE(CheckPermissions(fs::owner_all));
1623
1624 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_read), NoError);
1625 EXPECT_TRUE(CheckPermissions(fs::group_read));
1626
1627 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_write), NoError);
1628 EXPECT_TRUE(CheckPermissions(fs::group_write));
1629
1630 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_exe), NoError);
1631 EXPECT_TRUE(CheckPermissions(fs::group_exe));
1632
1633 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_all), NoError);
1634 EXPECT_TRUE(CheckPermissions(fs::group_all));
1635
1636 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_read), NoError);
1637 EXPECT_TRUE(CheckPermissions(fs::others_read));
1638
1639 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_write), NoError);
1640 EXPECT_TRUE(CheckPermissions(fs::others_write));
1641
1642 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_exe), NoError);
1643 EXPECT_TRUE(CheckPermissions(fs::others_exe));
1644
1645 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_all), NoError);
1646 EXPECT_TRUE(CheckPermissions(fs::others_all));
1647
1648 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read), NoError);
1649 EXPECT_TRUE(CheckPermissions(fs::all_read));
1650
1651 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_write), NoError);
1652 EXPECT_TRUE(CheckPermissions(fs::all_write));
1653
1654 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_exe), NoError);
1655 EXPECT_TRUE(CheckPermissions(fs::all_exe));
1656
1657 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe), NoError);
1658 EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe));
1659
1660 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_gid_on_exe), NoError);
1661 EXPECT_TRUE(CheckPermissions(fs::set_gid_on_exe));
1662
1663 // Modern BSDs require root to set the sticky bit on files.
1664 #if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__)
1665 EXPECT_EQ(fs::setPermissions(TempPath, fs::sticky_bit), NoError);
1666 EXPECT_TRUE(CheckPermissions(fs::sticky_bit));
1667
1668 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe |
1669 fs::set_gid_on_exe |
1670 fs::sticky_bit),
1671 NoError);
1672 EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe | fs::set_gid_on_exe |
1673 fs::sticky_bit));
1674
1675 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read | fs::set_uid_on_exe |
1676 fs::set_gid_on_exe |
1677 fs::sticky_bit),
1678 NoError);
1679 EXPECT_TRUE(CheckPermissions(fs::all_read | fs::set_uid_on_exe |
1680 fs::set_gid_on_exe | fs::sticky_bit));
1681
1682 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms), NoError);
1683 EXPECT_TRUE(CheckPermissions(fs::all_perms));
1684 #endif // !FreeBSD && !NetBSD && !OpenBSD
1685
1686 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms & ~fs::sticky_bit),
1687 NoError);
1688 EXPECT_TRUE(CheckPermissions(fs::all_perms & ~fs::sticky_bit));
1689 #endif
1690 }
1691
1692 } // anonymous namespace
1693