[Alignment][NFC] Use Align with TargetLowering::setMinFunctionAlignment
[llvm-core.git] / unittests / Support / Path.cpp
blob9de46a689cd728301e3bb17ae66e7e4ff121f2ac
1 //===- llvm/unittest/Support/Path.cpp - Path tests ------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Support/Path.h"
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ADT/ScopeExit.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 "llvm/Testing/Support/Error.h"
25 #include "gmock/gmock.h"
26 #include "gtest/gtest.h"
28 #ifdef _WIN32
29 #include "llvm/ADT/ArrayRef.h"
30 #include "llvm/Support/Chrono.h"
31 #include <windows.h>
32 #include <winerror.h>
33 #endif
35 #ifdef LLVM_ON_UNIX
36 #include <pwd.h>
37 #include <sys/stat.h>
38 #endif
40 using namespace llvm;
41 using namespace llvm::sys;
43 #define ASSERT_NO_ERROR(x) \
44 if (std::error_code ASSERT_NO_ERROR_ec = x) { \
45 SmallString<128> MessageStorage; \
46 raw_svector_ostream Message(MessageStorage); \
47 Message << #x ": did not return errc::success.\n" \
48 << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n" \
49 << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \
50 GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \
51 } else { \
54 #define ASSERT_ERROR(x) \
55 if (!x) { \
56 SmallString<128> MessageStorage; \
57 raw_svector_ostream Message(MessageStorage); \
58 Message << #x ": did not return a failure error code.\n"; \
59 GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \
62 namespace {
64 struct FileDescriptorCloser {
65 explicit FileDescriptorCloser(int FD) : FD(FD) {}
66 ~FileDescriptorCloser() { ::close(FD); }
67 int FD;
70 TEST(is_separator, Works) {
71 EXPECT_TRUE(path::is_separator('/'));
72 EXPECT_FALSE(path::is_separator('\0'));
73 EXPECT_FALSE(path::is_separator('-'));
74 EXPECT_FALSE(path::is_separator(' '));
76 EXPECT_TRUE(path::is_separator('\\', path::Style::windows));
77 EXPECT_FALSE(path::is_separator('\\', path::Style::posix));
79 #ifdef _WIN32
80 EXPECT_TRUE(path::is_separator('\\'));
81 #else
82 EXPECT_FALSE(path::is_separator('\\'));
83 #endif
86 TEST(Support, Path) {
87 SmallVector<StringRef, 40> paths;
88 paths.push_back("");
89 paths.push_back(".");
90 paths.push_back("..");
91 paths.push_back("foo");
92 paths.push_back("/");
93 paths.push_back("/foo");
94 paths.push_back("foo/");
95 paths.push_back("/foo/");
96 paths.push_back("foo/bar");
97 paths.push_back("/foo/bar");
98 paths.push_back("//net");
99 paths.push_back("//net/");
100 paths.push_back("//net/foo");
101 paths.push_back("///foo///");
102 paths.push_back("///foo///bar");
103 paths.push_back("/.");
104 paths.push_back("./");
105 paths.push_back("/..");
106 paths.push_back("../");
107 paths.push_back("foo/.");
108 paths.push_back("foo/..");
109 paths.push_back("foo/./");
110 paths.push_back("foo/./bar");
111 paths.push_back("foo/..");
112 paths.push_back("foo/../");
113 paths.push_back("foo/../bar");
114 paths.push_back("c:");
115 paths.push_back("c:/");
116 paths.push_back("c:foo");
117 paths.push_back("c:/foo");
118 paths.push_back("c:foo/");
119 paths.push_back("c:/foo/");
120 paths.push_back("c:/foo/bar");
121 paths.push_back("prn:");
122 paths.push_back("c:\\");
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/");
128 paths.push_back("c:/foo\\bar");
130 for (SmallVector<StringRef, 40>::const_iterator i = paths.begin(),
131 e = paths.end();
132 i != e;
133 ++i) {
134 SCOPED_TRACE(*i);
135 SmallVector<StringRef, 5> ComponentStack;
136 for (sys::path::const_iterator ci = sys::path::begin(*i),
137 ce = sys::path::end(*i);
138 ci != ce;
139 ++ci) {
140 EXPECT_FALSE(ci->empty());
141 ComponentStack.push_back(*ci);
144 SmallVector<StringRef, 5> ReverseComponentStack;
145 for (sys::path::reverse_iterator ci = sys::path::rbegin(*i),
146 ce = sys::path::rend(*i);
147 ci != ce;
148 ++ci) {
149 EXPECT_FALSE(ci->empty());
150 ReverseComponentStack.push_back(*ci);
152 std::reverse(ReverseComponentStack.begin(), ReverseComponentStack.end());
153 EXPECT_THAT(ComponentStack, testing::ContainerEq(ReverseComponentStack));
155 // Crash test most of the API - since we're iterating over all of our paths
156 // here there isn't really anything reasonable to assert on in the results.
157 (void)path::has_root_path(*i);
158 (void)path::root_path(*i);
159 (void)path::has_root_name(*i);
160 (void)path::root_name(*i);
161 (void)path::has_root_directory(*i);
162 (void)path::root_directory(*i);
163 (void)path::has_parent_path(*i);
164 (void)path::parent_path(*i);
165 (void)path::has_filename(*i);
166 (void)path::filename(*i);
167 (void)path::has_stem(*i);
168 (void)path::stem(*i);
169 (void)path::has_extension(*i);
170 (void)path::extension(*i);
171 (void)path::is_absolute(*i);
172 (void)path::is_relative(*i);
174 SmallString<128> temp_store;
175 temp_store = *i;
176 ASSERT_NO_ERROR(fs::make_absolute(temp_store));
177 temp_store = *i;
178 path::remove_filename(temp_store);
180 temp_store = *i;
181 path::replace_extension(temp_store, "ext");
182 StringRef filename(temp_store.begin(), temp_store.size()), stem, ext;
183 stem = path::stem(filename);
184 ext = path::extension(filename);
185 EXPECT_EQ(*sys::path::rbegin(filename), (stem + ext).str());
187 path::native(*i, temp_store);
191 SmallString<32> Relative("foo.cpp");
192 sys::fs::make_absolute("/root", Relative);
193 Relative[5] = '/'; // Fix up windows paths.
194 ASSERT_EQ("/root/foo.cpp", Relative);
198 SmallString<32> Relative("foo.cpp");
199 sys::fs::make_absolute("//root", Relative);
200 Relative[6] = '/'; // Fix up windows paths.
201 ASSERT_EQ("//root/foo.cpp", Relative);
205 TEST(Support, FilenameParent) {
206 EXPECT_EQ("/", path::filename("/"));
207 EXPECT_EQ("", path::parent_path("/"));
209 EXPECT_EQ("\\", path::filename("c:\\", path::Style::windows));
210 EXPECT_EQ("c:", path::parent_path("c:\\", path::Style::windows));
212 EXPECT_EQ("/", path::filename("///"));
213 EXPECT_EQ("", path::parent_path("///"));
215 EXPECT_EQ("\\", path::filename("c:\\\\", path::Style::windows));
216 EXPECT_EQ("c:", path::parent_path("c:\\\\", path::Style::windows));
218 EXPECT_EQ("bar", path::filename("/foo/bar"));
219 EXPECT_EQ("/foo", path::parent_path("/foo/bar"));
221 EXPECT_EQ("foo", path::filename("/foo"));
222 EXPECT_EQ("/", path::parent_path("/foo"));
224 EXPECT_EQ("foo", path::filename("foo"));
225 EXPECT_EQ("", path::parent_path("foo"));
227 EXPECT_EQ(".", path::filename("foo/"));
228 EXPECT_EQ("foo", path::parent_path("foo/"));
230 EXPECT_EQ("//net", path::filename("//net"));
231 EXPECT_EQ("", path::parent_path("//net"));
233 EXPECT_EQ("/", path::filename("//net/"));
234 EXPECT_EQ("//net", path::parent_path("//net/"));
236 EXPECT_EQ("foo", path::filename("//net/foo"));
237 EXPECT_EQ("//net/", path::parent_path("//net/foo"));
239 // These checks are just to make sure we do something reasonable with the
240 // paths below. They are not meant to prescribe the one true interpretation of
241 // these paths. Other decompositions (e.g. "//" -> "" + "//") are also
242 // possible.
243 EXPECT_EQ("/", path::filename("//"));
244 EXPECT_EQ("", path::parent_path("//"));
246 EXPECT_EQ("\\", path::filename("\\\\", path::Style::windows));
247 EXPECT_EQ("", path::parent_path("\\\\", path::Style::windows));
249 EXPECT_EQ("\\", path::filename("\\\\\\", path::Style::windows));
250 EXPECT_EQ("", path::parent_path("\\\\\\", path::Style::windows));
253 static std::vector<StringRef>
254 GetComponents(StringRef Path, path::Style S = path::Style::native) {
255 return {path::begin(Path, S), path::end(Path)};
258 TEST(Support, PathIterator) {
259 EXPECT_THAT(GetComponents("/foo"), testing::ElementsAre("/", "foo"));
260 EXPECT_THAT(GetComponents("/"), testing::ElementsAre("/"));
261 EXPECT_THAT(GetComponents("//"), testing::ElementsAre("/"));
262 EXPECT_THAT(GetComponents("///"), testing::ElementsAre("/"));
263 EXPECT_THAT(GetComponents("c/d/e/foo.txt"),
264 testing::ElementsAre("c", "d", "e", "foo.txt"));
265 EXPECT_THAT(GetComponents(".c/.d/../."),
266 testing::ElementsAre(".c", ".d", "..", "."));
267 EXPECT_THAT(GetComponents("/c/d/e/foo.txt"),
268 testing::ElementsAre("/", "c", "d", "e", "foo.txt"));
269 EXPECT_THAT(GetComponents("/.c/.d/../."),
270 testing::ElementsAre("/", ".c", ".d", "..", "."));
271 EXPECT_THAT(GetComponents("c:\\c\\e\\foo.txt", path::Style::windows),
272 testing::ElementsAre("c:", "\\", "c", "e", "foo.txt"));
273 EXPECT_THAT(GetComponents("//net/"), testing::ElementsAre("//net", "/"));
274 EXPECT_THAT(GetComponents("//net/c/foo.txt"),
275 testing::ElementsAre("//net", "/", "c", "foo.txt"));
278 TEST(Support, AbsolutePathIteratorEnd) {
279 // Trailing slashes are converted to '.' unless they are part of the root path.
280 SmallVector<std::pair<StringRef, path::Style>, 4> Paths;
281 Paths.emplace_back("/foo/", path::Style::native);
282 Paths.emplace_back("/foo//", path::Style::native);
283 Paths.emplace_back("//net/foo/", path::Style::native);
284 Paths.emplace_back("c:\\foo\\", path::Style::windows);
286 for (auto &Path : Paths) {
287 SCOPED_TRACE(Path.first);
288 StringRef LastComponent = *path::rbegin(Path.first, Path.second);
289 EXPECT_EQ(".", LastComponent);
292 SmallVector<std::pair<StringRef, path::Style>, 3> RootPaths;
293 RootPaths.emplace_back("/", path::Style::native);
294 RootPaths.emplace_back("//net/", path::Style::native);
295 RootPaths.emplace_back("c:\\", path::Style::windows);
296 RootPaths.emplace_back("//net//", path::Style::native);
297 RootPaths.emplace_back("c:\\\\", path::Style::windows);
299 for (auto &Path : RootPaths) {
300 SCOPED_TRACE(Path.first);
301 StringRef LastComponent = *path::rbegin(Path.first, Path.second);
302 EXPECT_EQ(1u, LastComponent.size());
303 EXPECT_TRUE(path::is_separator(LastComponent[0], Path.second));
307 TEST(Support, HomeDirectory) {
308 std::string expected;
309 #ifdef _WIN32
310 if (wchar_t const *path = ::_wgetenv(L"USERPROFILE")) {
311 auto pathLen = ::wcslen(path);
312 ArrayRef<char> ref{reinterpret_cast<char const *>(path),
313 pathLen * sizeof(wchar_t)};
314 convertUTF16ToUTF8String(ref, expected);
316 #else
317 if (char const *path = ::getenv("HOME"))
318 expected = path;
319 #endif
320 // Do not try to test it if we don't know what to expect.
321 // On Windows we use something better than env vars.
322 if (!expected.empty()) {
323 SmallString<128> HomeDir;
324 auto status = path::home_directory(HomeDir);
325 EXPECT_TRUE(status);
326 EXPECT_EQ(expected, HomeDir);
330 #ifdef LLVM_ON_UNIX
331 TEST(Support, HomeDirectoryWithNoEnv) {
332 std::string OriginalStorage;
333 char const *OriginalEnv = ::getenv("HOME");
334 if (OriginalEnv) {
335 // We're going to unset it, so make a copy and save a pointer to the copy
336 // so that we can reset it at the end of the test.
337 OriginalStorage = OriginalEnv;
338 OriginalEnv = OriginalStorage.c_str();
341 // Don't run the test if we have nothing to compare against.
342 struct passwd *pw = getpwuid(getuid());
343 if (!pw || !pw->pw_dir) return;
345 ::unsetenv("HOME");
346 EXPECT_EQ(nullptr, ::getenv("HOME"));
347 std::string PwDir = pw->pw_dir;
349 SmallString<128> HomeDir;
350 auto status = path::home_directory(HomeDir);
351 EXPECT_TRUE(status);
352 EXPECT_EQ(PwDir, HomeDir);
354 // Now put the environment back to its original state (meaning that if it was
355 // unset before, we don't reset it).
356 if (OriginalEnv) ::setenv("HOME", OriginalEnv, 1);
358 #endif
360 TEST(Support, TempDirectory) {
361 SmallString<32> TempDir;
362 path::system_temp_directory(false, TempDir);
363 EXPECT_TRUE(!TempDir.empty());
364 TempDir.clear();
365 path::system_temp_directory(true, TempDir);
366 EXPECT_TRUE(!TempDir.empty());
369 #ifdef _WIN32
370 static std::string path2regex(std::string Path) {
371 size_t Pos = 0;
372 while ((Pos = Path.find('\\', Pos)) != std::string::npos) {
373 Path.replace(Pos, 1, "\\\\");
374 Pos += 2;
376 return Path;
379 /// Helper for running temp dir test in separated process. See below.
380 #define EXPECT_TEMP_DIR(prepare, expected) \
381 EXPECT_EXIT( \
383 prepare; \
384 SmallString<300> TempDir; \
385 path::system_temp_directory(true, TempDir); \
386 raw_os_ostream(std::cerr) << TempDir; \
387 std::exit(0); \
388 }, \
389 ::testing::ExitedWithCode(0), path2regex(expected))
391 TEST(SupportDeathTest, TempDirectoryOnWindows) {
392 // In this test we want to check how system_temp_directory responds to
393 // different values of specific env vars. To prevent corrupting env vars of
394 // the current process all checks are done in separated processes.
395 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"C:\\OtherFolder"), "C:\\OtherFolder");
396 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"C:/Unix/Path/Seperators"),
397 "C:\\Unix\\Path\\Seperators");
398 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"Local Path"), ".+\\Local Path$");
399 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"F:\\TrailingSep\\"), "F:\\TrailingSep");
400 EXPECT_TEMP_DIR(
401 _wputenv_s(L"TMP", L"C:\\2\x03C0r-\x00B5\x00B3\\\x2135\x2080"),
402 "C:\\2\xCF\x80r-\xC2\xB5\xC2\xB3\\\xE2\x84\xB5\xE2\x82\x80");
404 // Test $TMP empty, $TEMP set.
405 EXPECT_TEMP_DIR(
407 _wputenv_s(L"TMP", L"");
408 _wputenv_s(L"TEMP", L"C:\\Valid\\Path");
410 "C:\\Valid\\Path");
412 // All related env vars empty
413 EXPECT_TEMP_DIR(
415 _wputenv_s(L"TMP", L"");
416 _wputenv_s(L"TEMP", L"");
417 _wputenv_s(L"USERPROFILE", L"");
419 "C:\\Temp");
421 // Test evn var / path with 260 chars.
422 SmallString<270> Expected{"C:\\Temp\\AB\\123456789"};
423 while (Expected.size() < 260)
424 Expected.append("\\DirNameWith19Charss");
425 ASSERT_EQ(260U, Expected.size());
426 EXPECT_TEMP_DIR(_putenv_s("TMP", Expected.c_str()), Expected.c_str());
428 #endif
430 class FileSystemTest : public testing::Test {
431 protected:
432 /// Unique temporary directory in which all created filesystem entities must
433 /// be placed. It is removed at the end of each test (must be empty).
434 SmallString<128> TestDirectory;
435 SmallString<128> NonExistantFile;
437 void SetUp() override {
438 ASSERT_NO_ERROR(
439 fs::createUniqueDirectory("file-system-test", TestDirectory));
440 // We don't care about this specific file.
441 errs() << "Test Directory: " << TestDirectory << '\n';
442 errs().flush();
443 NonExistantFile = TestDirectory;
445 // Even though this value is hardcoded, is a 128-bit GUID, so we should be
446 // guaranteed that this file will never exist.
447 sys::path::append(NonExistantFile, "1B28B495C16344CB9822E588CD4C3EF0");
450 void TearDown() override { ASSERT_NO_ERROR(fs::remove(TestDirectory.str())); }
453 TEST_F(FileSystemTest, Unique) {
454 // Create a temp file.
455 int FileDescriptor;
456 SmallString<64> TempPath;
457 ASSERT_NO_ERROR(
458 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
460 // The same file should return an identical unique id.
461 fs::UniqueID F1, F2;
462 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F1));
463 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F2));
464 ASSERT_EQ(F1, F2);
466 // Different files should return different unique ids.
467 int FileDescriptor2;
468 SmallString<64> TempPath2;
469 ASSERT_NO_ERROR(
470 fs::createTemporaryFile("prefix", "temp", FileDescriptor2, TempPath2));
472 fs::UniqueID D;
473 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D));
474 ASSERT_NE(D, F1);
475 ::close(FileDescriptor2);
477 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
479 // Two paths representing the same file on disk should still provide the
480 // same unique id. We can test this by making a hard link.
481 ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2)));
482 fs::UniqueID D2;
483 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D2));
484 ASSERT_EQ(D2, F1);
486 ::close(FileDescriptor);
488 SmallString<128> Dir1;
489 ASSERT_NO_ERROR(
490 fs::createUniqueDirectory("dir1", Dir1));
491 ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F1));
492 ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F2));
493 ASSERT_EQ(F1, F2);
495 SmallString<128> Dir2;
496 ASSERT_NO_ERROR(
497 fs::createUniqueDirectory("dir2", Dir2));
498 ASSERT_NO_ERROR(fs::getUniqueID(Dir2.c_str(), F2));
499 ASSERT_NE(F1, F2);
500 ASSERT_NO_ERROR(fs::remove(Dir1));
501 ASSERT_NO_ERROR(fs::remove(Dir2));
502 ASSERT_NO_ERROR(fs::remove(TempPath2));
503 ASSERT_NO_ERROR(fs::remove(TempPath));
506 TEST_F(FileSystemTest, RealPath) {
507 ASSERT_NO_ERROR(
508 fs::create_directories(Twine(TestDirectory) + "/test1/test2/test3"));
509 ASSERT_TRUE(fs::exists(Twine(TestDirectory) + "/test1/test2/test3"));
511 SmallString<64> RealBase;
512 SmallString<64> Expected;
513 SmallString<64> Actual;
515 // TestDirectory itself might be under a symlink or have been specified with
516 // a different case than the existing temp directory. In such cases real_path
517 // on the concatenated path will differ in the TestDirectory portion from
518 // how we specified it. Make sure to compare against the real_path of the
519 // TestDirectory, and not just the value of TestDirectory.
520 ASSERT_NO_ERROR(fs::real_path(TestDirectory, RealBase));
521 path::native(Twine(RealBase) + "/test1/test2", Expected);
523 ASSERT_NO_ERROR(fs::real_path(
524 Twine(TestDirectory) + "/././test1/../test1/test2/./test3/..", Actual));
526 EXPECT_EQ(Expected, Actual);
528 SmallString<64> HomeDir;
530 // This can fail if $HOME is not set and getpwuid fails.
531 bool Result = llvm::sys::path::home_directory(HomeDir);
532 if (Result) {
533 ASSERT_NO_ERROR(fs::real_path(HomeDir, Expected));
534 ASSERT_NO_ERROR(fs::real_path("~", Actual, true));
535 EXPECT_EQ(Expected, Actual);
536 ASSERT_NO_ERROR(fs::real_path("~/", Actual, true));
537 EXPECT_EQ(Expected, Actual);
540 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/test1"));
543 TEST_F(FileSystemTest, ExpandTilde) {
544 SmallString<64> Expected;
545 SmallString<64> Actual;
546 SmallString<64> HomeDir;
548 // This can fail if $HOME is not set and getpwuid fails.
549 bool Result = llvm::sys::path::home_directory(HomeDir);
550 if (Result) {
551 fs::expand_tilde(HomeDir, Expected);
553 fs::expand_tilde("~", Actual);
554 EXPECT_EQ(Expected, Actual);
556 #ifdef _WIN32
557 Expected += "\\foo";
558 fs::expand_tilde("~\\foo", Actual);
559 #else
560 Expected += "/foo";
561 fs::expand_tilde("~/foo", Actual);
562 #endif
564 EXPECT_EQ(Expected, Actual);
568 #ifdef LLVM_ON_UNIX
569 TEST_F(FileSystemTest, RealPathNoReadPerm) {
570 SmallString<64> Expanded;
572 ASSERT_NO_ERROR(
573 fs::create_directories(Twine(TestDirectory) + "/noreadperm"));
574 ASSERT_TRUE(fs::exists(Twine(TestDirectory) + "/noreadperm"));
576 fs::setPermissions(Twine(TestDirectory) + "/noreadperm", fs::no_perms);
577 fs::setPermissions(Twine(TestDirectory) + "/noreadperm", fs::all_exe);
579 ASSERT_NO_ERROR(fs::real_path(Twine(TestDirectory) + "/noreadperm", Expanded,
580 false));
582 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/noreadperm"));
584 #endif
587 TEST_F(FileSystemTest, TempFileKeepDiscard) {
588 // We can keep then discard.
589 auto TempFileOrError = fs::TempFile::create(TestDirectory + "/test-%%%%");
590 ASSERT_TRUE((bool)TempFileOrError);
591 fs::TempFile File = std::move(*TempFileOrError);
592 ASSERT_EQ(-1, TempFileOrError->FD);
593 ASSERT_FALSE((bool)File.keep(TestDirectory + "/keep"));
594 ASSERT_FALSE((bool)File.discard());
595 ASSERT_TRUE(fs::exists(TestDirectory + "/keep"));
596 ASSERT_NO_ERROR(fs::remove(TestDirectory + "/keep"));
599 TEST_F(FileSystemTest, TempFileDiscardDiscard) {
600 // We can discard twice.
601 auto TempFileOrError = fs::TempFile::create(TestDirectory + "/test-%%%%");
602 ASSERT_TRUE((bool)TempFileOrError);
603 fs::TempFile File = std::move(*TempFileOrError);
604 ASSERT_EQ(-1, TempFileOrError->FD);
605 ASSERT_FALSE((bool)File.discard());
606 ASSERT_FALSE((bool)File.discard());
607 ASSERT_FALSE(fs::exists(TestDirectory + "/keep"));
610 TEST_F(FileSystemTest, TempFiles) {
611 // Create a temp file.
612 int FileDescriptor;
613 SmallString<64> TempPath;
614 ASSERT_NO_ERROR(
615 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
617 // Make sure it exists.
618 ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
620 // Create another temp tile.
621 int FD2;
622 SmallString<64> TempPath2;
623 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD2, TempPath2));
624 ASSERT_TRUE(TempPath2.endswith(".temp"));
625 ASSERT_NE(TempPath.str(), TempPath2.str());
627 fs::file_status A, B;
628 ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
629 ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
630 EXPECT_FALSE(fs::equivalent(A, B));
632 ::close(FD2);
634 // Remove Temp2.
635 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
636 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
637 ASSERT_EQ(fs::remove(Twine(TempPath2), false),
638 errc::no_such_file_or_directory);
640 std::error_code EC = fs::status(TempPath2.c_str(), B);
641 EXPECT_EQ(EC, errc::no_such_file_or_directory);
642 EXPECT_EQ(B.type(), fs::file_type::file_not_found);
644 // Make sure Temp2 doesn't exist.
645 ASSERT_EQ(fs::access(Twine(TempPath2), sys::fs::AccessMode::Exist),
646 errc::no_such_file_or_directory);
648 SmallString<64> TempPath3;
649 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "", TempPath3));
650 ASSERT_FALSE(TempPath3.endswith("."));
651 FileRemover Cleanup3(TempPath3);
653 // Create a hard link to Temp1.
654 ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2)));
655 bool equal;
656 ASSERT_NO_ERROR(fs::equivalent(Twine(TempPath), Twine(TempPath2), equal));
657 EXPECT_TRUE(equal);
658 ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
659 ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
660 EXPECT_TRUE(fs::equivalent(A, B));
662 // Remove Temp1.
663 ::close(FileDescriptor);
664 ASSERT_NO_ERROR(fs::remove(Twine(TempPath)));
666 // Remove the hard link.
667 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
669 // Make sure Temp1 doesn't exist.
670 ASSERT_EQ(fs::access(Twine(TempPath), sys::fs::AccessMode::Exist),
671 errc::no_such_file_or_directory);
673 #ifdef _WIN32
674 // Path name > 260 chars should get an error.
675 const char *Path270 =
676 "abcdefghijklmnopqrstuvwxyz9abcdefghijklmnopqrstuvwxyz8"
677 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
678 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
679 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
680 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
681 EXPECT_EQ(fs::createUniqueFile(Path270, FileDescriptor, TempPath),
682 errc::invalid_argument);
683 // Relative path < 247 chars, no problem.
684 const char *Path216 =
685 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
686 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
687 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
688 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
689 ASSERT_NO_ERROR(fs::createTemporaryFile(Path216, "", TempPath));
690 ASSERT_NO_ERROR(fs::remove(Twine(TempPath)));
691 #endif
694 TEST_F(FileSystemTest, TempFileCollisions) {
695 SmallString<128> TestDirectory;
696 ASSERT_NO_ERROR(
697 fs::createUniqueDirectory("CreateUniqueFileTest", TestDirectory));
698 FileRemover Cleanup(TestDirectory);
699 SmallString<128> Model = TestDirectory;
700 path::append(Model, "%.tmp");
701 SmallString<128> Path;
702 std::vector<fs::TempFile> TempFiles;
704 auto TryCreateTempFile = [&]() {
705 Expected<fs::TempFile> T = fs::TempFile::create(Model);
706 if (T) {
707 TempFiles.push_back(std::move(*T));
708 return true;
709 } else {
710 logAllUnhandledErrors(T.takeError(), errs(),
711 "Failed to create temporary file: ");
712 return false;
716 // Our single-character template allows for 16 unique names. Check that
717 // calling TryCreateTempFile repeatedly results in 16 successes.
718 // Because the test depends on random numbers, it could theoretically fail.
719 // However, the probability of this happening is tiny: with 32 calls, each
720 // of which will retry up to 128 times, to not get a given digit we would
721 // have to fail at least 15 + 17 * 128 = 2191 attempts. The probability of
722 // 2191 attempts not producing a given hexadecimal digit is
723 // (1 - 1/16) ** 2191 or 3.88e-62.
724 int Successes = 0;
725 for (int i = 0; i < 32; ++i)
726 if (TryCreateTempFile()) ++Successes;
727 EXPECT_EQ(Successes, 16);
729 for (fs::TempFile &T : TempFiles)
730 cantFail(T.discard());
733 TEST_F(FileSystemTest, CreateDir) {
734 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
735 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
736 ASSERT_EQ(fs::create_directory(Twine(TestDirectory) + "foo", false),
737 errc::file_exists);
738 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "foo"));
740 #ifdef LLVM_ON_UNIX
741 // Set a 0000 umask so that we can test our directory permissions.
742 mode_t OldUmask = ::umask(0000);
744 fs::file_status Status;
745 ASSERT_NO_ERROR(
746 fs::create_directory(Twine(TestDirectory) + "baz500", false,
747 fs::perms::owner_read | fs::perms::owner_exe));
748 ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz500", Status));
749 ASSERT_EQ(Status.permissions() & fs::perms::all_all,
750 fs::perms::owner_read | fs::perms::owner_exe);
751 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "baz777", false,
752 fs::perms::all_all));
753 ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz777", Status));
754 ASSERT_EQ(Status.permissions() & fs::perms::all_all, fs::perms::all_all);
756 // Restore umask to be safe.
757 ::umask(OldUmask);
758 #endif
760 #ifdef _WIN32
761 // Prove that create_directories() can handle a pathname > 248 characters,
762 // which is the documented limit for CreateDirectory().
763 // (248 is MAX_PATH subtracting room for an 8.3 filename.)
764 // Generate a directory path guaranteed to fall into that range.
765 size_t TmpLen = TestDirectory.size();
766 const char *OneDir = "\\123456789";
767 size_t OneDirLen = strlen(OneDir);
768 ASSERT_LT(OneDirLen, 12U);
769 size_t NLevels = ((248 - TmpLen) / OneDirLen) + 1;
770 SmallString<260> LongDir(TestDirectory);
771 for (size_t I = 0; I < NLevels; ++I)
772 LongDir.append(OneDir);
773 ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir)));
774 ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir)));
775 ASSERT_EQ(fs::create_directories(Twine(LongDir), false),
776 errc::file_exists);
777 // Tidy up, "recursively" removing the directories.
778 StringRef ThisDir(LongDir);
779 for (size_t J = 0; J < NLevels; ++J) {
780 ASSERT_NO_ERROR(fs::remove(ThisDir));
781 ThisDir = path::parent_path(ThisDir);
784 // Also verify that paths with Unix separators are handled correctly.
785 std::string LongPathWithUnixSeparators(TestDirectory.str());
786 // Add at least one subdirectory to TestDirectory, and replace slashes with
787 // backslashes
788 do {
789 LongPathWithUnixSeparators.append("/DirNameWith19Charss");
790 } while (LongPathWithUnixSeparators.size() < 260);
791 std::replace(LongPathWithUnixSeparators.begin(),
792 LongPathWithUnixSeparators.end(),
793 '\\', '/');
794 ASSERT_NO_ERROR(fs::create_directories(Twine(LongPathWithUnixSeparators)));
795 // cleanup
796 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) +
797 "/DirNameWith19Charss"));
799 // Similarly for a relative pathname. Need to set the current directory to
800 // TestDirectory so that the one we create ends up in the right place.
801 char PreviousDir[260];
802 size_t PreviousDirLen = ::GetCurrentDirectoryA(260, PreviousDir);
803 ASSERT_GT(PreviousDirLen, 0U);
804 ASSERT_LT(PreviousDirLen, 260U);
805 ASSERT_NE(::SetCurrentDirectoryA(TestDirectory.c_str()), 0);
806 LongDir.clear();
807 // Generate a relative directory name with absolute length > 248.
808 size_t LongDirLen = 249 - TestDirectory.size();
809 LongDir.assign(LongDirLen, 'a');
810 ASSERT_NO_ERROR(fs::create_directory(Twine(LongDir)));
811 // While we're here, prove that .. and . handling works in these long paths.
812 const char *DotDotDirs = "\\..\\.\\b";
813 LongDir.append(DotDotDirs);
814 ASSERT_NO_ERROR(fs::create_directory("b"));
815 ASSERT_EQ(fs::create_directory(Twine(LongDir), false), errc::file_exists);
816 // And clean up.
817 ASSERT_NO_ERROR(fs::remove("b"));
818 ASSERT_NO_ERROR(fs::remove(
819 Twine(LongDir.substr(0, LongDir.size() - strlen(DotDotDirs)))));
820 ASSERT_NE(::SetCurrentDirectoryA(PreviousDir), 0);
821 #endif
824 TEST_F(FileSystemTest, DirectoryIteration) {
825 std::error_code ec;
826 for (fs::directory_iterator i(".", ec), e; i != e; i.increment(ec))
827 ASSERT_NO_ERROR(ec);
829 // Create a known hierarchy to recurse over.
830 ASSERT_NO_ERROR(
831 fs::create_directories(Twine(TestDirectory) + "/recursive/a0/aa1"));
832 ASSERT_NO_ERROR(
833 fs::create_directories(Twine(TestDirectory) + "/recursive/a0/ab1"));
834 ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) +
835 "/recursive/dontlookhere/da1"));
836 ASSERT_NO_ERROR(
837 fs::create_directories(Twine(TestDirectory) + "/recursive/z0/za1"));
838 ASSERT_NO_ERROR(
839 fs::create_directories(Twine(TestDirectory) + "/recursive/pop/p1"));
840 typedef std::vector<std::string> v_t;
841 v_t visited;
842 for (fs::recursive_directory_iterator i(Twine(TestDirectory)
843 + "/recursive", ec), e; i != e; i.increment(ec)){
844 ASSERT_NO_ERROR(ec);
845 if (path::filename(i->path()) == "p1") {
846 i.pop();
847 // FIXME: recursive_directory_iterator should be more robust.
848 if (i == e) break;
850 if (path::filename(i->path()) == "dontlookhere")
851 i.no_push();
852 visited.push_back(path::filename(i->path()));
854 v_t::const_iterator a0 = find(visited, "a0");
855 v_t::const_iterator aa1 = find(visited, "aa1");
856 v_t::const_iterator ab1 = find(visited, "ab1");
857 v_t::const_iterator dontlookhere = find(visited, "dontlookhere");
858 v_t::const_iterator da1 = find(visited, "da1");
859 v_t::const_iterator z0 = find(visited, "z0");
860 v_t::const_iterator za1 = find(visited, "za1");
861 v_t::const_iterator pop = find(visited, "pop");
862 v_t::const_iterator p1 = find(visited, "p1");
864 // Make sure that each path was visited correctly.
865 ASSERT_NE(a0, visited.end());
866 ASSERT_NE(aa1, visited.end());
867 ASSERT_NE(ab1, visited.end());
868 ASSERT_NE(dontlookhere, visited.end());
869 ASSERT_EQ(da1, visited.end()); // Not visited.
870 ASSERT_NE(z0, visited.end());
871 ASSERT_NE(za1, visited.end());
872 ASSERT_NE(pop, visited.end());
873 ASSERT_EQ(p1, visited.end()); // Not visited.
875 // Make sure that parents were visited before children. No other ordering
876 // guarantees can be made across siblings.
877 ASSERT_LT(a0, aa1);
878 ASSERT_LT(a0, ab1);
879 ASSERT_LT(z0, za1);
881 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/aa1"));
882 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/ab1"));
883 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0"));
884 ASSERT_NO_ERROR(
885 fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere/da1"));
886 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere"));
887 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop/p1"));
888 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop"));
889 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0/za1"));
890 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0"));
891 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive"));
893 // Test recursive_directory_iterator level()
894 ASSERT_NO_ERROR(
895 fs::create_directories(Twine(TestDirectory) + "/reclevel/a/b/c"));
896 fs::recursive_directory_iterator I(Twine(TestDirectory) + "/reclevel", ec), E;
897 for (int l = 0; I != E; I.increment(ec), ++l) {
898 ASSERT_NO_ERROR(ec);
899 EXPECT_EQ(I.level(), l);
901 EXPECT_EQ(I, E);
902 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a/b/c"));
903 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a/b"));
904 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a"));
905 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel"));
908 #ifdef LLVM_ON_UNIX
909 TEST_F(FileSystemTest, BrokenSymlinkDirectoryIteration) {
910 // Create a known hierarchy to recurse over.
911 ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) + "/symlink"));
912 ASSERT_NO_ERROR(
913 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/a"));
914 ASSERT_NO_ERROR(
915 fs::create_directories(Twine(TestDirectory) + "/symlink/b/bb"));
916 ASSERT_NO_ERROR(
917 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/b/ba"));
918 ASSERT_NO_ERROR(
919 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/b/bc"));
920 ASSERT_NO_ERROR(
921 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/c"));
922 ASSERT_NO_ERROR(
923 fs::create_directories(Twine(TestDirectory) + "/symlink/d/dd/ddd"));
924 ASSERT_NO_ERROR(fs::create_link(Twine(TestDirectory) + "/symlink/d/dd",
925 Twine(TestDirectory) + "/symlink/d/da"));
926 ASSERT_NO_ERROR(
927 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/e"));
929 typedef std::vector<std::string> v_t;
930 v_t VisitedNonBrokenSymlinks;
931 v_t VisitedBrokenSymlinks;
932 std::error_code ec;
933 using testing::UnorderedElementsAre;
934 using testing::UnorderedElementsAreArray;
936 // Broken symbol links are expected to throw an error.
937 for (fs::directory_iterator i(Twine(TestDirectory) + "/symlink", ec), e;
938 i != e; i.increment(ec)) {
939 ASSERT_NO_ERROR(ec);
940 if (i->status().getError() ==
941 std::make_error_code(std::errc::no_such_file_or_directory)) {
942 VisitedBrokenSymlinks.push_back(path::filename(i->path()));
943 continue;
945 VisitedNonBrokenSymlinks.push_back(path::filename(i->path()));
947 EXPECT_THAT(VisitedNonBrokenSymlinks, UnorderedElementsAre("b", "d"));
948 VisitedNonBrokenSymlinks.clear();
950 EXPECT_THAT(VisitedBrokenSymlinks, UnorderedElementsAre("a", "c", "e"));
951 VisitedBrokenSymlinks.clear();
953 // Broken symbol links are expected to throw an error.
954 for (fs::recursive_directory_iterator i(
955 Twine(TestDirectory) + "/symlink", ec), e; i != e; i.increment(ec)) {
956 ASSERT_NO_ERROR(ec);
957 if (i->status().getError() ==
958 std::make_error_code(std::errc::no_such_file_or_directory)) {
959 VisitedBrokenSymlinks.push_back(path::filename(i->path()));
960 continue;
962 VisitedNonBrokenSymlinks.push_back(path::filename(i->path()));
964 EXPECT_THAT(VisitedNonBrokenSymlinks,
965 UnorderedElementsAre("b", "bb", "d", "da", "dd", "ddd", "ddd"));
966 VisitedNonBrokenSymlinks.clear();
968 EXPECT_THAT(VisitedBrokenSymlinks,
969 UnorderedElementsAre("a", "ba", "bc", "c", "e"));
970 VisitedBrokenSymlinks.clear();
972 for (fs::recursive_directory_iterator i(
973 Twine(TestDirectory) + "/symlink", ec, /*follow_symlinks=*/false), e;
974 i != e; i.increment(ec)) {
975 ASSERT_NO_ERROR(ec);
976 if (i->status().getError() ==
977 std::make_error_code(std::errc::no_such_file_or_directory)) {
978 VisitedBrokenSymlinks.push_back(path::filename(i->path()));
979 continue;
981 VisitedNonBrokenSymlinks.push_back(path::filename(i->path()));
983 EXPECT_THAT(VisitedNonBrokenSymlinks,
984 UnorderedElementsAreArray({"a", "b", "ba", "bb", "bc", "c", "d",
985 "da", "dd", "ddd", "e"}));
986 VisitedNonBrokenSymlinks.clear();
988 EXPECT_THAT(VisitedBrokenSymlinks, UnorderedElementsAre());
989 VisitedBrokenSymlinks.clear();
991 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/symlink"));
993 #endif
995 TEST_F(FileSystemTest, Remove) {
996 SmallString<64> BaseDir;
997 SmallString<64> Paths[4];
998 int fds[4];
999 ASSERT_NO_ERROR(fs::createUniqueDirectory("fs_remove", BaseDir));
1001 ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir) + "/foo/bar/baz"));
1002 ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir) + "/foo/bar/buzz"));
1003 ASSERT_NO_ERROR(fs::createUniqueFile(
1004 Twine(BaseDir) + "/foo/bar/baz/%%%%%%.tmp", fds[0], Paths[0]));
1005 ASSERT_NO_ERROR(fs::createUniqueFile(
1006 Twine(BaseDir) + "/foo/bar/baz/%%%%%%.tmp", fds[1], Paths[1]));
1007 ASSERT_NO_ERROR(fs::createUniqueFile(
1008 Twine(BaseDir) + "/foo/bar/buzz/%%%%%%.tmp", fds[2], Paths[2]));
1009 ASSERT_NO_ERROR(fs::createUniqueFile(
1010 Twine(BaseDir) + "/foo/bar/buzz/%%%%%%.tmp", fds[3], Paths[3]));
1012 for (int fd : fds)
1013 ::close(fd);
1015 EXPECT_TRUE(fs::exists(Twine(BaseDir) + "/foo/bar/baz"));
1016 EXPECT_TRUE(fs::exists(Twine(BaseDir) + "/foo/bar/buzz"));
1017 EXPECT_TRUE(fs::exists(Paths[0]));
1018 EXPECT_TRUE(fs::exists(Paths[1]));
1019 EXPECT_TRUE(fs::exists(Paths[2]));
1020 EXPECT_TRUE(fs::exists(Paths[3]));
1022 ASSERT_NO_ERROR(fs::remove_directories("D:/footest"));
1024 ASSERT_NO_ERROR(fs::remove_directories(BaseDir));
1025 ASSERT_FALSE(fs::exists(BaseDir));
1028 #ifdef _WIN32
1029 TEST_F(FileSystemTest, CarriageReturn) {
1030 SmallString<128> FilePathname(TestDirectory);
1031 std::error_code EC;
1032 path::append(FilePathname, "test");
1035 raw_fd_ostream File(FilePathname, EC, sys::fs::OF_Text);
1036 ASSERT_NO_ERROR(EC);
1037 File << '\n';
1040 auto Buf = MemoryBuffer::getFile(FilePathname.str());
1041 EXPECT_TRUE((bool)Buf);
1042 EXPECT_EQ(Buf.get()->getBuffer(), "\r\n");
1046 raw_fd_ostream File(FilePathname, EC, sys::fs::OF_None);
1047 ASSERT_NO_ERROR(EC);
1048 File << '\n';
1051 auto Buf = MemoryBuffer::getFile(FilePathname.str());
1052 EXPECT_TRUE((bool)Buf);
1053 EXPECT_EQ(Buf.get()->getBuffer(), "\n");
1055 ASSERT_NO_ERROR(fs::remove(Twine(FilePathname)));
1057 #endif
1059 TEST_F(FileSystemTest, Resize) {
1060 int FD;
1061 SmallString<64> TempPath;
1062 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1063 ASSERT_NO_ERROR(fs::resize_file(FD, 123));
1064 fs::file_status Status;
1065 ASSERT_NO_ERROR(fs::status(FD, Status));
1066 ASSERT_EQ(Status.getSize(), 123U);
1067 ::close(FD);
1068 ASSERT_NO_ERROR(fs::remove(TempPath));
1071 TEST_F(FileSystemTest, MD5) {
1072 int FD;
1073 SmallString<64> TempPath;
1074 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1075 StringRef Data("abcdefghijklmnopqrstuvwxyz");
1076 ASSERT_EQ(write(FD, Data.data(), Data.size()), static_cast<ssize_t>(Data.size()));
1077 lseek(FD, 0, SEEK_SET);
1078 auto Hash = fs::md5_contents(FD);
1079 ::close(FD);
1080 ASSERT_NO_ERROR(Hash.getError());
1082 EXPECT_STREQ("c3fcd3d76192e4007dfb496cca67e13b", Hash->digest().c_str());
1085 TEST_F(FileSystemTest, FileMapping) {
1086 // Create a temp file.
1087 int FileDescriptor;
1088 SmallString<64> TempPath;
1089 ASSERT_NO_ERROR(
1090 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
1091 unsigned Size = 4096;
1092 ASSERT_NO_ERROR(fs::resize_file(FileDescriptor, Size));
1094 // Map in temp file and add some content
1095 std::error_code EC;
1096 StringRef Val("hello there");
1098 fs::mapped_file_region mfr(fs::convertFDToNativeFile(FileDescriptor),
1099 fs::mapped_file_region::readwrite, Size, 0, EC);
1100 ASSERT_NO_ERROR(EC);
1101 std::copy(Val.begin(), Val.end(), mfr.data());
1102 // Explicitly add a 0.
1103 mfr.data()[Val.size()] = 0;
1104 // Unmap temp file
1106 ASSERT_EQ(close(FileDescriptor), 0);
1108 // Map it back in read-only
1110 int FD;
1111 EC = fs::openFileForRead(Twine(TempPath), FD);
1112 ASSERT_NO_ERROR(EC);
1113 fs::mapped_file_region mfr(fs::convertFDToNativeFile(FD),
1114 fs::mapped_file_region::readonly, Size, 0, EC);
1115 ASSERT_NO_ERROR(EC);
1117 // Verify content
1118 EXPECT_EQ(StringRef(mfr.const_data()), Val);
1120 // Unmap temp file
1121 fs::mapped_file_region m(fs::convertFDToNativeFile(FD),
1122 fs::mapped_file_region::readonly, Size, 0, EC);
1123 ASSERT_NO_ERROR(EC);
1124 ASSERT_EQ(close(FD), 0);
1126 ASSERT_NO_ERROR(fs::remove(TempPath));
1129 TEST(Support, NormalizePath) {
1130 using TestTuple = std::tuple<const char *, const char *, const char *>;
1131 std::vector<TestTuple> Tests;
1132 Tests.emplace_back("a", "a", "a");
1133 Tests.emplace_back("a/b", "a\\b", "a/b");
1134 Tests.emplace_back("a\\b", "a\\b", "a/b");
1135 Tests.emplace_back("a\\\\b", "a\\\\b", "a\\\\b");
1136 Tests.emplace_back("\\a", "\\a", "/a");
1137 Tests.emplace_back("a\\", "a\\", "a/");
1139 for (auto &T : Tests) {
1140 SmallString<64> Win(std::get<0>(T));
1141 SmallString<64> Posix(Win);
1142 path::native(Win, path::Style::windows);
1143 path::native(Posix, path::Style::posix);
1144 EXPECT_EQ(std::get<1>(T), Win);
1145 EXPECT_EQ(std::get<2>(T), Posix);
1148 #if defined(_WIN32)
1149 SmallString<64> PathHome;
1150 path::home_directory(PathHome);
1152 const char *Path7a = "~/aaa";
1153 SmallString<64> Path7(Path7a);
1154 path::native(Path7);
1155 EXPECT_TRUE(Path7.endswith("\\aaa"));
1156 EXPECT_TRUE(Path7.startswith(PathHome));
1157 EXPECT_EQ(Path7.size(), PathHome.size() + strlen(Path7a + 1));
1159 const char *Path8a = "~";
1160 SmallString<64> Path8(Path8a);
1161 path::native(Path8);
1162 EXPECT_EQ(Path8, PathHome);
1164 const char *Path9a = "~aaa";
1165 SmallString<64> Path9(Path9a);
1166 path::native(Path9);
1167 EXPECT_EQ(Path9, "~aaa");
1169 const char *Path10a = "aaa/~/b";
1170 SmallString<64> Path10(Path10a);
1171 path::native(Path10);
1172 EXPECT_EQ(Path10, "aaa\\~\\b");
1173 #endif
1176 TEST(Support, RemoveLeadingDotSlash) {
1177 StringRef Path1("././/foolz/wat");
1178 StringRef Path2("./////");
1180 Path1 = path::remove_leading_dotslash(Path1);
1181 EXPECT_EQ(Path1, "foolz/wat");
1182 Path2 = path::remove_leading_dotslash(Path2);
1183 EXPECT_EQ(Path2, "");
1186 static std::string remove_dots(StringRef path, bool remove_dot_dot,
1187 path::Style style) {
1188 SmallString<256> buffer(path);
1189 path::remove_dots(buffer, remove_dot_dot, style);
1190 return buffer.str();
1193 TEST(Support, RemoveDots) {
1194 EXPECT_EQ("foolz\\wat",
1195 remove_dots(".\\.\\\\foolz\\wat", false, path::Style::windows));
1196 EXPECT_EQ("", remove_dots(".\\\\\\\\\\", false, path::Style::windows));
1198 EXPECT_EQ("a\\..\\b\\c",
1199 remove_dots(".\\a\\..\\b\\c", false, path::Style::windows));
1200 EXPECT_EQ("b\\c", remove_dots(".\\a\\..\\b\\c", true, path::Style::windows));
1201 EXPECT_EQ("c", remove_dots(".\\.\\c", true, path::Style::windows));
1202 EXPECT_EQ("..\\a\\c",
1203 remove_dots("..\\a\\b\\..\\c", true, path::Style::windows));
1204 EXPECT_EQ("..\\..\\a\\c",
1205 remove_dots("..\\..\\a\\b\\..\\c", true, path::Style::windows));
1207 SmallString<64> Path1(".\\.\\c");
1208 EXPECT_TRUE(path::remove_dots(Path1, true, path::Style::windows));
1209 EXPECT_EQ("c", Path1);
1211 EXPECT_EQ("foolz/wat",
1212 remove_dots("././/foolz/wat", false, path::Style::posix));
1213 EXPECT_EQ("", remove_dots("./////", false, path::Style::posix));
1215 EXPECT_EQ("a/../b/c", remove_dots("./a/../b/c", false, path::Style::posix));
1216 EXPECT_EQ("b/c", remove_dots("./a/../b/c", true, path::Style::posix));
1217 EXPECT_EQ("c", remove_dots("././c", true, path::Style::posix));
1218 EXPECT_EQ("../a/c", remove_dots("../a/b/../c", true, path::Style::posix));
1219 EXPECT_EQ("../../a/c",
1220 remove_dots("../../a/b/../c", true, path::Style::posix));
1221 EXPECT_EQ("/a/c", remove_dots("/../../a/c", true, path::Style::posix));
1222 EXPECT_EQ("/a/c",
1223 remove_dots("/../a/b//../././/c", true, path::Style::posix));
1225 SmallString<64> Path2("././c");
1226 EXPECT_TRUE(path::remove_dots(Path2, true, path::Style::posix));
1227 EXPECT_EQ("c", Path2);
1230 TEST(Support, ReplacePathPrefix) {
1231 SmallString<64> Path1("/foo");
1232 SmallString<64> Path2("/old/foo");
1233 SmallString<64> OldPrefix("/old");
1234 SmallString<64> NewPrefix("/new");
1235 SmallString<64> NewPrefix2("/longernew");
1236 SmallString<64> EmptyPrefix("");
1238 SmallString<64> Path = Path1;
1239 path::replace_path_prefix(Path, OldPrefix, NewPrefix);
1240 EXPECT_EQ(Path, "/foo");
1241 Path = Path2;
1242 path::replace_path_prefix(Path, OldPrefix, NewPrefix);
1243 EXPECT_EQ(Path, "/new/foo");
1244 Path = Path2;
1245 path::replace_path_prefix(Path, OldPrefix, NewPrefix2);
1246 EXPECT_EQ(Path, "/longernew/foo");
1247 Path = Path1;
1248 path::replace_path_prefix(Path, EmptyPrefix, NewPrefix);
1249 EXPECT_EQ(Path, "/new/foo");
1250 Path = Path2;
1251 path::replace_path_prefix(Path, OldPrefix, EmptyPrefix);
1252 EXPECT_EQ(Path, "/foo");
1255 TEST_F(FileSystemTest, OpenFileForRead) {
1256 // Create a temp file.
1257 int FileDescriptor;
1258 SmallString<64> TempPath;
1259 ASSERT_NO_ERROR(
1260 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
1261 FileRemover Cleanup(TempPath);
1263 // Make sure it exists.
1264 ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
1266 // Open the file for read
1267 int FileDescriptor2;
1268 SmallString<64> ResultPath;
1269 ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath), FileDescriptor2,
1270 fs::OF_None, &ResultPath))
1272 // If we succeeded, check that the paths are the same (modulo case):
1273 if (!ResultPath.empty()) {
1274 // The paths returned by createTemporaryFile and getPathFromOpenFD
1275 // should reference the same file on disk.
1276 fs::UniqueID D1, D2;
1277 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), D1));
1278 ASSERT_NO_ERROR(fs::getUniqueID(Twine(ResultPath), D2));
1279 ASSERT_EQ(D1, D2);
1281 ::close(FileDescriptor);
1282 ::close(FileDescriptor2);
1284 #ifdef _WIN32
1285 // Since Windows Vista, file access time is not updated by default.
1286 // This is instead updated manually by openFileForRead.
1287 // https://blogs.technet.microsoft.com/filecab/2006/11/07/disabling-last-access-time-in-windows-vista-to-improve-ntfs-performance/
1288 // This part of the unit test is Windows specific as the updating of
1289 // access times can be disabled on Linux using /etc/fstab.
1291 // Set access time to UNIX epoch.
1292 ASSERT_NO_ERROR(sys::fs::openFileForWrite(Twine(TempPath), FileDescriptor,
1293 fs::CD_OpenExisting));
1294 TimePoint<> Epoch(std::chrono::milliseconds(0));
1295 ASSERT_NO_ERROR(fs::setLastAccessAndModificationTime(FileDescriptor, Epoch));
1296 ::close(FileDescriptor);
1298 // Open the file and ensure access time is updated, when forced.
1299 ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath), FileDescriptor,
1300 fs::OF_UpdateAtime, &ResultPath));
1302 sys::fs::file_status Status;
1303 ASSERT_NO_ERROR(sys::fs::status(FileDescriptor, Status));
1304 auto FileAccessTime = Status.getLastAccessedTime();
1306 ASSERT_NE(Epoch, FileAccessTime);
1307 ::close(FileDescriptor);
1309 // Ideally this test would include a case when ATime is not forced to update,
1310 // however the expected behaviour will differ depending on the configuration
1311 // of the Windows file system.
1312 #endif
1315 static void createFileWithData(const Twine &Path, bool ShouldExistBefore,
1316 fs::CreationDisposition Disp, StringRef Data) {
1317 int FD;
1318 ASSERT_EQ(ShouldExistBefore, fs::exists(Path));
1319 ASSERT_NO_ERROR(fs::openFileForWrite(Path, FD, Disp));
1320 FileDescriptorCloser Closer(FD);
1321 ASSERT_TRUE(fs::exists(Path));
1323 ASSERT_EQ(Data.size(), (size_t)write(FD, Data.data(), Data.size()));
1326 static void verifyFileContents(const Twine &Path, StringRef Contents) {
1327 auto Buffer = MemoryBuffer::getFile(Path);
1328 ASSERT_TRUE((bool)Buffer);
1329 StringRef Data = Buffer.get()->getBuffer();
1330 ASSERT_EQ(Data, Contents);
1333 TEST_F(FileSystemTest, CreateNew) {
1334 int FD;
1335 Optional<FileDescriptorCloser> Closer;
1337 // Succeeds if the file does not exist.
1338 ASSERT_FALSE(fs::exists(NonExistantFile));
1339 ASSERT_NO_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateNew));
1340 ASSERT_TRUE(fs::exists(NonExistantFile));
1342 FileRemover Cleanup(NonExistantFile);
1343 Closer.emplace(FD);
1345 // And creates a file of size 0.
1346 sys::fs::file_status Status;
1347 ASSERT_NO_ERROR(sys::fs::status(FD, Status));
1348 EXPECT_EQ(0ULL, Status.getSize());
1350 // Close this first, before trying to re-open the file.
1351 Closer.reset();
1353 // But fails if the file does exist.
1354 ASSERT_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateNew));
1357 TEST_F(FileSystemTest, CreateAlways) {
1358 int FD;
1359 Optional<FileDescriptorCloser> Closer;
1361 // Succeeds if the file does not exist.
1362 ASSERT_FALSE(fs::exists(NonExistantFile));
1363 ASSERT_NO_ERROR(
1364 fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateAlways));
1366 Closer.emplace(FD);
1368 ASSERT_TRUE(fs::exists(NonExistantFile));
1370 FileRemover Cleanup(NonExistantFile);
1372 // And creates a file of size 0.
1373 uint64_t FileSize;
1374 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1375 ASSERT_EQ(0ULL, FileSize);
1377 // If we write some data to it re-create it with CreateAlways, it succeeds and
1378 // truncates to 0 bytes.
1379 ASSERT_EQ(4, write(FD, "Test", 4));
1381 Closer.reset();
1383 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1384 ASSERT_EQ(4ULL, FileSize);
1386 ASSERT_NO_ERROR(
1387 fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateAlways));
1388 Closer.emplace(FD);
1389 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1390 ASSERT_EQ(0ULL, FileSize);
1393 TEST_F(FileSystemTest, OpenExisting) {
1394 int FD;
1396 // Fails if the file does not exist.
1397 ASSERT_FALSE(fs::exists(NonExistantFile));
1398 ASSERT_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_OpenExisting));
1399 ASSERT_FALSE(fs::exists(NonExistantFile));
1401 // Make a dummy file now so that we can try again when the file does exist.
1402 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1403 FileRemover Cleanup(NonExistantFile);
1404 uint64_t FileSize;
1405 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1406 ASSERT_EQ(4ULL, FileSize);
1408 // If we re-create it with different data, it overwrites rather than
1409 // appending.
1410 createFileWithData(NonExistantFile, true, fs::CD_OpenExisting, "Buzz");
1411 verifyFileContents(NonExistantFile, "Buzz");
1414 TEST_F(FileSystemTest, OpenAlways) {
1415 // Succeeds if the file does not exist.
1416 createFileWithData(NonExistantFile, false, fs::CD_OpenAlways, "Fizz");
1417 FileRemover Cleanup(NonExistantFile);
1418 uint64_t FileSize;
1419 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1420 ASSERT_EQ(4ULL, FileSize);
1422 // Now re-open it and write again, verifying the contents get over-written.
1423 createFileWithData(NonExistantFile, true, fs::CD_OpenAlways, "Bu");
1424 verifyFileContents(NonExistantFile, "Buzz");
1427 TEST_F(FileSystemTest, AppendSetsCorrectFileOffset) {
1428 fs::CreationDisposition Disps[] = {fs::CD_CreateAlways, fs::CD_OpenAlways,
1429 fs::CD_OpenExisting};
1431 // Write some data and re-open it with every possible disposition (this is a
1432 // hack that shouldn't work, but is left for compatibility. OF_Append
1433 // overrides
1434 // the specified disposition.
1435 for (fs::CreationDisposition Disp : Disps) {
1436 int FD;
1437 Optional<FileDescriptorCloser> Closer;
1439 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1441 FileRemover Cleanup(NonExistantFile);
1443 uint64_t FileSize;
1444 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1445 ASSERT_EQ(4ULL, FileSize);
1446 ASSERT_NO_ERROR(
1447 fs::openFileForWrite(NonExistantFile, FD, Disp, fs::OF_Append));
1448 Closer.emplace(FD);
1449 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1450 ASSERT_EQ(4ULL, FileSize);
1452 ASSERT_EQ(4, write(FD, "Buzz", 4));
1453 Closer.reset();
1455 verifyFileContents(NonExistantFile, "FizzBuzz");
1459 static void verifyRead(int FD, StringRef Data, bool ShouldSucceed) {
1460 std::vector<char> Buffer;
1461 Buffer.resize(Data.size());
1462 int Result = ::read(FD, Buffer.data(), Buffer.size());
1463 if (ShouldSucceed) {
1464 ASSERT_EQ((size_t)Result, Data.size());
1465 ASSERT_EQ(Data, StringRef(Buffer.data(), Buffer.size()));
1466 } else {
1467 ASSERT_EQ(-1, Result);
1468 ASSERT_EQ(EBADF, errno);
1472 static void verifyWrite(int FD, StringRef Data, bool ShouldSucceed) {
1473 int Result = ::write(FD, Data.data(), Data.size());
1474 if (ShouldSucceed)
1475 ASSERT_EQ((size_t)Result, Data.size());
1476 else {
1477 ASSERT_EQ(-1, Result);
1478 ASSERT_EQ(EBADF, errno);
1482 TEST_F(FileSystemTest, ReadOnlyFileCantWrite) {
1483 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1484 FileRemover Cleanup(NonExistantFile);
1486 int FD;
1487 ASSERT_NO_ERROR(fs::openFileForRead(NonExistantFile, FD));
1488 FileDescriptorCloser Closer(FD);
1490 verifyWrite(FD, "Buzz", false);
1491 verifyRead(FD, "Fizz", true);
1494 TEST_F(FileSystemTest, WriteOnlyFileCantRead) {
1495 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1496 FileRemover Cleanup(NonExistantFile);
1498 int FD;
1499 ASSERT_NO_ERROR(
1500 fs::openFileForWrite(NonExistantFile, FD, fs::CD_OpenExisting));
1501 FileDescriptorCloser Closer(FD);
1502 verifyRead(FD, "Fizz", false);
1503 verifyWrite(FD, "Buzz", true);
1506 TEST_F(FileSystemTest, ReadWriteFileCanReadOrWrite) {
1507 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1508 FileRemover Cleanup(NonExistantFile);
1510 int FD;
1511 ASSERT_NO_ERROR(fs::openFileForReadWrite(NonExistantFile, FD,
1512 fs::CD_OpenExisting, fs::OF_None));
1513 FileDescriptorCloser Closer(FD);
1514 verifyRead(FD, "Fizz", true);
1515 verifyWrite(FD, "Buzz", true);
1518 TEST_F(FileSystemTest, readNativeFile) {
1519 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "01234");
1520 FileRemover Cleanup(NonExistantFile);
1521 const auto &Read = [&](size_t ToRead) -> Expected<std::string> {
1522 std::string Buf(ToRead, '?');
1523 Expected<fs::file_t> FD = fs::openNativeFileForRead(NonExistantFile);
1524 if (!FD)
1525 return FD.takeError();
1526 auto Close = make_scope_exit([&] { fs::closeFile(*FD); });
1527 if (Expected<size_t> BytesRead = fs::readNativeFile(
1528 *FD, makeMutableArrayRef(&*Buf.begin(), Buf.size())))
1529 return Buf.substr(0, *BytesRead);
1530 else
1531 return BytesRead.takeError();
1533 EXPECT_THAT_EXPECTED(Read(5), HasValue("01234"));
1534 EXPECT_THAT_EXPECTED(Read(3), HasValue("012"));
1535 EXPECT_THAT_EXPECTED(Read(6), HasValue("01234"));
1538 TEST_F(FileSystemTest, readNativeFileSlice) {
1539 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "01234");
1540 FileRemover Cleanup(NonExistantFile);
1541 Expected<fs::file_t> FD = fs::openNativeFileForRead(NonExistantFile);
1542 ASSERT_THAT_EXPECTED(FD, Succeeded());
1543 auto Close = make_scope_exit([&] { fs::closeFile(*FD); });
1544 const auto &Read = [&](size_t Offset,
1545 size_t ToRead) -> Expected<std::string> {
1546 std::string Buf(ToRead, '?');
1547 if (Expected<size_t> BytesRead = fs::readNativeFileSlice(
1548 *FD, makeMutableArrayRef(&*Buf.begin(), Buf.size()), Offset))
1549 return Buf.substr(0, *BytesRead);
1550 else
1551 return BytesRead.takeError();
1553 EXPECT_THAT_EXPECTED(Read(0, 5), HasValue("01234"));
1554 EXPECT_THAT_EXPECTED(Read(0, 3), HasValue("012"));
1555 EXPECT_THAT_EXPECTED(Read(2, 3), HasValue("234"));
1556 EXPECT_THAT_EXPECTED(Read(0, 6), HasValue("01234"));
1557 EXPECT_THAT_EXPECTED(Read(2, 6), HasValue("234"));
1558 EXPECT_THAT_EXPECTED(Read(5, 5), HasValue(""));
1561 TEST_F(FileSystemTest, is_local) {
1562 bool TestDirectoryIsLocal;
1563 ASSERT_NO_ERROR(fs::is_local(TestDirectory, TestDirectoryIsLocal));
1564 EXPECT_EQ(TestDirectoryIsLocal, fs::is_local(TestDirectory));
1566 int FD;
1567 SmallString<128> TempPath;
1568 ASSERT_NO_ERROR(
1569 fs::createUniqueFile(Twine(TestDirectory) + "/temp", FD, TempPath));
1570 FileRemover Cleanup(TempPath);
1572 // Make sure it exists.
1573 ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
1575 bool TempFileIsLocal;
1576 ASSERT_NO_ERROR(fs::is_local(FD, TempFileIsLocal));
1577 EXPECT_EQ(TempFileIsLocal, fs::is_local(FD));
1578 ::close(FD);
1580 // Expect that the file and its parent directory are equally local or equally
1581 // remote.
1582 EXPECT_EQ(TestDirectoryIsLocal, TempFileIsLocal);
1585 TEST_F(FileSystemTest, getUmask) {
1586 #ifdef _WIN32
1587 EXPECT_EQ(fs::getUmask(), 0U) << "Should always be 0 on Windows.";
1588 #else
1589 unsigned OldMask = ::umask(0022);
1590 unsigned CurrentMask = fs::getUmask();
1591 EXPECT_EQ(CurrentMask, 0022U)
1592 << "getUmask() didn't return previously set umask()";
1593 EXPECT_EQ(::umask(OldMask), 0022U) << "getUmask() may have changed umask()";
1594 #endif
1597 TEST_F(FileSystemTest, RespectUmask) {
1598 #ifndef _WIN32
1599 unsigned OldMask = ::umask(0022);
1601 int FD;
1602 SmallString<128> TempPath;
1603 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1605 fs::perms AllRWE = static_cast<fs::perms>(0777);
1607 ASSERT_NO_ERROR(fs::setPermissions(TempPath, AllRWE));
1609 ErrorOr<fs::perms> Perms = fs::getPermissions(TempPath);
1610 ASSERT_TRUE(!!Perms);
1611 EXPECT_EQ(Perms.get(), AllRWE) << "Should have ignored umask by default";
1613 ASSERT_NO_ERROR(fs::setPermissions(TempPath, AllRWE));
1615 Perms = fs::getPermissions(TempPath);
1616 ASSERT_TRUE(!!Perms);
1617 EXPECT_EQ(Perms.get(), AllRWE) << "Should have ignored umask";
1619 ASSERT_NO_ERROR(
1620 fs::setPermissions(FD, static_cast<fs::perms>(AllRWE & ~fs::getUmask())));
1621 Perms = fs::getPermissions(TempPath);
1622 ASSERT_TRUE(!!Perms);
1623 EXPECT_EQ(Perms.get(), static_cast<fs::perms>(0755))
1624 << "Did not respect umask";
1626 (void)::umask(0057);
1628 ASSERT_NO_ERROR(
1629 fs::setPermissions(FD, static_cast<fs::perms>(AllRWE & ~fs::getUmask())));
1630 Perms = fs::getPermissions(TempPath);
1631 ASSERT_TRUE(!!Perms);
1632 EXPECT_EQ(Perms.get(), static_cast<fs::perms>(0720))
1633 << "Did not respect umask";
1635 (void)::umask(OldMask);
1636 (void)::close(FD);
1637 #endif
1640 TEST_F(FileSystemTest, set_current_path) {
1641 SmallString<128> path;
1643 ASSERT_NO_ERROR(fs::current_path(path));
1644 ASSERT_NE(TestDirectory, path);
1646 struct RestorePath {
1647 SmallString<128> path;
1648 RestorePath(const SmallString<128> &path) : path(path) {}
1649 ~RestorePath() { fs::set_current_path(path); }
1650 } restore_path(path);
1652 ASSERT_NO_ERROR(fs::set_current_path(TestDirectory));
1654 ASSERT_NO_ERROR(fs::current_path(path));
1656 fs::UniqueID D1, D2;
1657 ASSERT_NO_ERROR(fs::getUniqueID(TestDirectory, D1));
1658 ASSERT_NO_ERROR(fs::getUniqueID(path, D2));
1659 ASSERT_EQ(D1, D2) << "D1: " << TestDirectory << "\nD2: " << path;
1662 TEST_F(FileSystemTest, permissions) {
1663 int FD;
1664 SmallString<64> TempPath;
1665 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1666 FileRemover Cleanup(TempPath);
1668 // Make sure it exists.
1669 ASSERT_TRUE(fs::exists(Twine(TempPath)));
1671 auto CheckPermissions = [&](fs::perms Expected) {
1672 ErrorOr<fs::perms> Actual = fs::getPermissions(TempPath);
1673 return Actual && *Actual == Expected;
1676 std::error_code NoError;
1677 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_all), NoError);
1678 EXPECT_TRUE(CheckPermissions(fs::all_all));
1680 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read | fs::all_exe), NoError);
1681 EXPECT_TRUE(CheckPermissions(fs::all_read | fs::all_exe));
1683 #if defined(_WIN32)
1684 fs::perms ReadOnly = fs::all_read | fs::all_exe;
1685 EXPECT_EQ(fs::setPermissions(TempPath, fs::no_perms), NoError);
1686 EXPECT_TRUE(CheckPermissions(ReadOnly));
1688 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_read), NoError);
1689 EXPECT_TRUE(CheckPermissions(ReadOnly));
1691 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_write), NoError);
1692 EXPECT_TRUE(CheckPermissions(fs::all_all));
1694 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_exe), NoError);
1695 EXPECT_TRUE(CheckPermissions(ReadOnly));
1697 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_all), NoError);
1698 EXPECT_TRUE(CheckPermissions(fs::all_all));
1700 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_read), NoError);
1701 EXPECT_TRUE(CheckPermissions(ReadOnly));
1703 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_write), NoError);
1704 EXPECT_TRUE(CheckPermissions(fs::all_all));
1706 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_exe), NoError);
1707 EXPECT_TRUE(CheckPermissions(ReadOnly));
1709 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_all), NoError);
1710 EXPECT_TRUE(CheckPermissions(fs::all_all));
1712 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_read), NoError);
1713 EXPECT_TRUE(CheckPermissions(ReadOnly));
1715 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_write), NoError);
1716 EXPECT_TRUE(CheckPermissions(fs::all_all));
1718 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_exe), NoError);
1719 EXPECT_TRUE(CheckPermissions(ReadOnly));
1721 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_all), NoError);
1722 EXPECT_TRUE(CheckPermissions(fs::all_all));
1724 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read), NoError);
1725 EXPECT_TRUE(CheckPermissions(ReadOnly));
1727 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_write), NoError);
1728 EXPECT_TRUE(CheckPermissions(fs::all_all));
1730 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_exe), NoError);
1731 EXPECT_TRUE(CheckPermissions(ReadOnly));
1733 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe), NoError);
1734 EXPECT_TRUE(CheckPermissions(ReadOnly));
1736 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_gid_on_exe), NoError);
1737 EXPECT_TRUE(CheckPermissions(ReadOnly));
1739 EXPECT_EQ(fs::setPermissions(TempPath, fs::sticky_bit), NoError);
1740 EXPECT_TRUE(CheckPermissions(ReadOnly));
1742 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe |
1743 fs::set_gid_on_exe |
1744 fs::sticky_bit),
1745 NoError);
1746 EXPECT_TRUE(CheckPermissions(ReadOnly));
1748 EXPECT_EQ(fs::setPermissions(TempPath, ReadOnly | fs::set_uid_on_exe |
1749 fs::set_gid_on_exe |
1750 fs::sticky_bit),
1751 NoError);
1752 EXPECT_TRUE(CheckPermissions(ReadOnly));
1754 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms), NoError);
1755 EXPECT_TRUE(CheckPermissions(fs::all_all));
1756 #else
1757 EXPECT_EQ(fs::setPermissions(TempPath, fs::no_perms), NoError);
1758 EXPECT_TRUE(CheckPermissions(fs::no_perms));
1760 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_read), NoError);
1761 EXPECT_TRUE(CheckPermissions(fs::owner_read));
1763 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_write), NoError);
1764 EXPECT_TRUE(CheckPermissions(fs::owner_write));
1766 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_exe), NoError);
1767 EXPECT_TRUE(CheckPermissions(fs::owner_exe));
1769 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_all), NoError);
1770 EXPECT_TRUE(CheckPermissions(fs::owner_all));
1772 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_read), NoError);
1773 EXPECT_TRUE(CheckPermissions(fs::group_read));
1775 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_write), NoError);
1776 EXPECT_TRUE(CheckPermissions(fs::group_write));
1778 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_exe), NoError);
1779 EXPECT_TRUE(CheckPermissions(fs::group_exe));
1781 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_all), NoError);
1782 EXPECT_TRUE(CheckPermissions(fs::group_all));
1784 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_read), NoError);
1785 EXPECT_TRUE(CheckPermissions(fs::others_read));
1787 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_write), NoError);
1788 EXPECT_TRUE(CheckPermissions(fs::others_write));
1790 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_exe), NoError);
1791 EXPECT_TRUE(CheckPermissions(fs::others_exe));
1793 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_all), NoError);
1794 EXPECT_TRUE(CheckPermissions(fs::others_all));
1796 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read), NoError);
1797 EXPECT_TRUE(CheckPermissions(fs::all_read));
1799 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_write), NoError);
1800 EXPECT_TRUE(CheckPermissions(fs::all_write));
1802 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_exe), NoError);
1803 EXPECT_TRUE(CheckPermissions(fs::all_exe));
1805 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe), NoError);
1806 EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe));
1808 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_gid_on_exe), NoError);
1809 EXPECT_TRUE(CheckPermissions(fs::set_gid_on_exe));
1811 // Modern BSDs require root to set the sticky bit on files.
1812 // AIX and Solaris without root will mask off (i.e., lose) the sticky bit
1813 // on files.
1814 #if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
1815 !defined(_AIX) && !(defined(__sun__) && defined(__svr4__))
1816 EXPECT_EQ(fs::setPermissions(TempPath, fs::sticky_bit), NoError);
1817 EXPECT_TRUE(CheckPermissions(fs::sticky_bit));
1819 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe |
1820 fs::set_gid_on_exe |
1821 fs::sticky_bit),
1822 NoError);
1823 EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe | fs::set_gid_on_exe |
1824 fs::sticky_bit));
1826 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read | fs::set_uid_on_exe |
1827 fs::set_gid_on_exe |
1828 fs::sticky_bit),
1829 NoError);
1830 EXPECT_TRUE(CheckPermissions(fs::all_read | fs::set_uid_on_exe |
1831 fs::set_gid_on_exe | fs::sticky_bit));
1833 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms), NoError);
1834 EXPECT_TRUE(CheckPermissions(fs::all_perms));
1835 #endif // !FreeBSD && !NetBSD && !OpenBSD && !AIX
1837 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms & ~fs::sticky_bit),
1838 NoError);
1839 EXPECT_TRUE(CheckPermissions(fs::all_perms & ~fs::sticky_bit));
1840 #endif
1843 } // anonymous namespace