1 //===- llvm/unittest/Support/Path.cpp - Path tests ------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Support/Path.h"
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ADT/SmallVector.h"
12 #include "llvm/ADT/Triple.h"
13 #include "llvm/BinaryFormat/Magic.h"
14 #include "llvm/Config/llvm-config.h"
15 #include "llvm/Support/ConvertUTF.h"
16 #include "llvm/Support/Errc.h"
17 #include "llvm/Support/ErrorHandling.h"
18 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/FileUtilities.h"
20 #include "llvm/Support/Host.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Testing/Support/Error.h"
24 #include "gmock/gmock.h"
25 #include "gtest/gtest.h"
28 #include "llvm/ADT/ArrayRef.h"
29 #include "llvm/Support/Chrono.h"
40 using namespace llvm::sys
;
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()); \
53 #define ASSERT_ERROR(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()); \
63 struct FileDescriptorCloser
{
64 explicit FileDescriptorCloser(int FD
) : FD(FD
) {}
65 ~FileDescriptorCloser() { ::close(FD
); }
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(' '));
75 EXPECT_TRUE(path::is_separator('\\', path::Style::windows
));
76 EXPECT_FALSE(path::is_separator('\\', path::Style::posix
));
79 EXPECT_TRUE(path::is_separator('\\'));
81 EXPECT_FALSE(path::is_separator('\\'));
86 SmallVector
<StringRef
, 40> paths
;
89 paths
.push_back("..");
90 paths
.push_back("foo");
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");
129 for (SmallVector
<StringRef
, 40>::const_iterator i
= paths
.begin(),
134 SmallVector
<StringRef
, 5> ComponentStack
;
135 for (sys::path::const_iterator ci
= sys::path::begin(*i
),
136 ce
= sys::path::end(*i
);
139 EXPECT_FALSE(ci
->empty());
140 ComponentStack
.push_back(*ci
);
143 SmallVector
<StringRef
, 5> ReverseComponentStack
;
144 for (sys::path::reverse_iterator ci
= sys::path::rbegin(*i
),
145 ce
= sys::path::rend(*i
);
148 EXPECT_FALSE(ci
->empty());
149 ReverseComponentStack
.push_back(*ci
);
151 std::reverse(ReverseComponentStack
.begin(), ReverseComponentStack
.end());
152 EXPECT_THAT(ComponentStack
, testing::ContainerEq(ReverseComponentStack
));
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
);
173 SmallString
<128> temp_store
;
175 ASSERT_NO_ERROR(fs::make_absolute(temp_store
));
177 path::remove_filename(temp_store
);
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());
186 path::native(*i
, temp_store
);
190 SmallString
<32> Relative("foo.cpp");
191 sys::fs::make_absolute("/root", Relative
);
192 Relative
[5] = '/'; // Fix up windows paths.
193 ASSERT_EQ("/root/foo.cpp", Relative
);
197 SmallString
<32> Relative("foo.cpp");
198 sys::fs::make_absolute("//root", Relative
);
199 Relative
[6] = '/'; // Fix up windows paths.
200 ASSERT_EQ("//root/foo.cpp", Relative
);
204 TEST(Support
, FilenameParent
) {
205 EXPECT_EQ("/", path::filename("/"));
206 EXPECT_EQ("", path::parent_path("/"));
208 EXPECT_EQ("\\", path::filename("c:\\", path::Style::windows
));
209 EXPECT_EQ("c:", path::parent_path("c:\\", path::Style::windows
));
211 EXPECT_EQ("/", path::filename("///"));
212 EXPECT_EQ("", path::parent_path("///"));
214 EXPECT_EQ("\\", path::filename("c:\\\\", path::Style::windows
));
215 EXPECT_EQ("c:", path::parent_path("c:\\\\", path::Style::windows
));
217 EXPECT_EQ("bar", path::filename("/foo/bar"));
218 EXPECT_EQ("/foo", path::parent_path("/foo/bar"));
220 EXPECT_EQ("foo", path::filename("/foo"));
221 EXPECT_EQ("/", path::parent_path("/foo"));
223 EXPECT_EQ("foo", path::filename("foo"));
224 EXPECT_EQ("", path::parent_path("foo"));
226 EXPECT_EQ(".", path::filename("foo/"));
227 EXPECT_EQ("foo", path::parent_path("foo/"));
229 EXPECT_EQ("//net", path::filename("//net"));
230 EXPECT_EQ("", path::parent_path("//net"));
232 EXPECT_EQ("/", path::filename("//net/"));
233 EXPECT_EQ("//net", path::parent_path("//net/"));
235 EXPECT_EQ("foo", path::filename("//net/foo"));
236 EXPECT_EQ("//net/", path::parent_path("//net/foo"));
238 // These checks are just to make sure we do something reasonable with the
239 // paths below. They are not meant to prescribe the one true interpretation of
240 // these paths. Other decompositions (e.g. "//" -> "" + "//") are also
242 EXPECT_EQ("/", path::filename("//"));
243 EXPECT_EQ("", path::parent_path("//"));
245 EXPECT_EQ("\\", path::filename("\\\\", path::Style::windows
));
246 EXPECT_EQ("", path::parent_path("\\\\", path::Style::windows
));
248 EXPECT_EQ("\\", path::filename("\\\\\\", path::Style::windows
));
249 EXPECT_EQ("", path::parent_path("\\\\\\", path::Style::windows
));
252 static std::vector
<StringRef
>
253 GetComponents(StringRef Path
, path::Style S
= path::Style::native
) {
254 return {path::begin(Path
, S
), path::end(Path
)};
257 TEST(Support
, PathIterator
) {
258 EXPECT_THAT(GetComponents("/foo"), testing::ElementsAre("/", "foo"));
259 EXPECT_THAT(GetComponents("/"), testing::ElementsAre("/"));
260 EXPECT_THAT(GetComponents("//"), testing::ElementsAre("/"));
261 EXPECT_THAT(GetComponents("///"), testing::ElementsAre("/"));
262 EXPECT_THAT(GetComponents("c/d/e/foo.txt"),
263 testing::ElementsAre("c", "d", "e", "foo.txt"));
264 EXPECT_THAT(GetComponents(".c/.d/../."),
265 testing::ElementsAre(".c", ".d", "..", "."));
266 EXPECT_THAT(GetComponents("/c/d/e/foo.txt"),
267 testing::ElementsAre("/", "c", "d", "e", "foo.txt"));
268 EXPECT_THAT(GetComponents("/.c/.d/../."),
269 testing::ElementsAre("/", ".c", ".d", "..", "."));
270 EXPECT_THAT(GetComponents("c:\\c\\e\\foo.txt", path::Style::windows
),
271 testing::ElementsAre("c:", "\\", "c", "e", "foo.txt"));
272 EXPECT_THAT(GetComponents("//net/"), testing::ElementsAre("//net", "/"));
273 EXPECT_THAT(GetComponents("//net/c/foo.txt"),
274 testing::ElementsAre("//net", "/", "c", "foo.txt"));
277 TEST(Support
, AbsolutePathIteratorEnd
) {
278 // Trailing slashes are converted to '.' unless they are part of the root path.
279 SmallVector
<std::pair
<StringRef
, path::Style
>, 4> Paths
;
280 Paths
.emplace_back("/foo/", path::Style::native
);
281 Paths
.emplace_back("/foo//", path::Style::native
);
282 Paths
.emplace_back("//net/foo/", path::Style::native
);
283 Paths
.emplace_back("c:\\foo\\", path::Style::windows
);
285 for (auto &Path
: Paths
) {
286 SCOPED_TRACE(Path
.first
);
287 StringRef LastComponent
= *path::rbegin(Path
.first
, Path
.second
);
288 EXPECT_EQ(".", LastComponent
);
291 SmallVector
<std::pair
<StringRef
, path::Style
>, 3> RootPaths
;
292 RootPaths
.emplace_back("/", path::Style::native
);
293 RootPaths
.emplace_back("//net/", path::Style::native
);
294 RootPaths
.emplace_back("c:\\", path::Style::windows
);
295 RootPaths
.emplace_back("//net//", path::Style::native
);
296 RootPaths
.emplace_back("c:\\\\", path::Style::windows
);
298 for (auto &Path
: RootPaths
) {
299 SCOPED_TRACE(Path
.first
);
300 StringRef LastComponent
= *path::rbegin(Path
.first
, Path
.second
);
301 EXPECT_EQ(1u, LastComponent
.size());
302 EXPECT_TRUE(path::is_separator(LastComponent
[0], Path
.second
));
306 TEST(Support
, HomeDirectory
) {
307 std::string expected
;
309 if (wchar_t const *path
= ::_wgetenv(L
"USERPROFILE")) {
310 auto pathLen
= ::wcslen(path
);
311 ArrayRef
<char> ref
{reinterpret_cast<char const *>(path
),
312 pathLen
* sizeof(wchar_t)};
313 convertUTF16ToUTF8String(ref
, expected
);
316 if (char const *path
= ::getenv("HOME"))
319 // Do not try to test it if we don't know what to expect.
320 // On Windows we use something better than env vars.
321 if (!expected
.empty()) {
322 SmallString
<128> HomeDir
;
323 auto status
= path::home_directory(HomeDir
);
325 EXPECT_EQ(expected
, HomeDir
);
330 TEST(Support
, HomeDirectoryWithNoEnv
) {
331 std::string OriginalStorage
;
332 char const *OriginalEnv
= ::getenv("HOME");
334 // We're going to unset it, so make a copy and save a pointer to the copy
335 // so that we can reset it at the end of the test.
336 OriginalStorage
= OriginalEnv
;
337 OriginalEnv
= OriginalStorage
.c_str();
340 // Don't run the test if we have nothing to compare against.
341 struct passwd
*pw
= getpwuid(getuid());
342 if (!pw
|| !pw
->pw_dir
) return;
345 EXPECT_EQ(nullptr, ::getenv("HOME"));
346 std::string PwDir
= pw
->pw_dir
;
348 SmallString
<128> HomeDir
;
349 auto status
= path::home_directory(HomeDir
);
351 EXPECT_EQ(PwDir
, HomeDir
);
353 // Now put the environment back to its original state (meaning that if it was
354 // unset before, we don't reset it).
355 if (OriginalEnv
) ::setenv("HOME", OriginalEnv
, 1);
359 TEST(Support
, TempDirectory
) {
360 SmallString
<32> TempDir
;
361 path::system_temp_directory(false, TempDir
);
362 EXPECT_TRUE(!TempDir
.empty());
364 path::system_temp_directory(true, TempDir
);
365 EXPECT_TRUE(!TempDir
.empty());
369 static std::string
path2regex(std::string Path
) {
371 while ((Pos
= Path
.find('\\', Pos
)) != std::string::npos
) {
372 Path
.replace(Pos
, 1, "\\\\");
378 /// Helper for running temp dir test in separated process. See below.
379 #define EXPECT_TEMP_DIR(prepare, expected) \
383 SmallString<300> TempDir; \
384 path::system_temp_directory(true, TempDir); \
385 raw_os_ostream(std::cerr) << TempDir; \
388 ::testing::ExitedWithCode(0), path2regex(expected))
390 TEST(SupportDeathTest
, TempDirectoryOnWindows
) {
391 // In this test we want to check how system_temp_directory responds to
392 // different values of specific env vars. To prevent corrupting env vars of
393 // the current process all checks are done in separated processes.
394 EXPECT_TEMP_DIR(_wputenv_s(L
"TMP", L
"C:\\OtherFolder"), "C:\\OtherFolder");
395 EXPECT_TEMP_DIR(_wputenv_s(L
"TMP", L
"C:/Unix/Path/Seperators"),
396 "C:\\Unix\\Path\\Seperators");
397 EXPECT_TEMP_DIR(_wputenv_s(L
"TMP", L
"Local Path"), ".+\\Local Path$");
398 EXPECT_TEMP_DIR(_wputenv_s(L
"TMP", L
"F:\\TrailingSep\\"), "F:\\TrailingSep");
400 _wputenv_s(L
"TMP", L
"C:\\2\x03C0r-\x00B5\x00B3\\\x2135\x2080"),
401 "C:\\2\xCF\x80r-\xC2\xB5\xC2\xB3\\\xE2\x84\xB5\xE2\x82\x80");
403 // Test $TMP empty, $TEMP set.
406 _wputenv_s(L
"TMP", L
"");
407 _wputenv_s(L
"TEMP", L
"C:\\Valid\\Path");
411 // All related env vars empty
414 _wputenv_s(L
"TMP", L
"");
415 _wputenv_s(L
"TEMP", L
"");
416 _wputenv_s(L
"USERPROFILE", L
"");
420 // Test evn var / path with 260 chars.
421 SmallString
<270> Expected
{"C:\\Temp\\AB\\123456789"};
422 while (Expected
.size() < 260)
423 Expected
.append("\\DirNameWith19Charss");
424 ASSERT_EQ(260U, Expected
.size());
425 EXPECT_TEMP_DIR(_putenv_s("TMP", Expected
.c_str()), Expected
.c_str());
429 class FileSystemTest
: public testing::Test
{
431 /// Unique temporary directory in which all created filesystem entities must
432 /// be placed. It is removed at the end of each test (must be empty).
433 SmallString
<128> TestDirectory
;
434 SmallString
<128> NonExistantFile
;
436 void SetUp() override
{
438 fs::createUniqueDirectory("file-system-test", TestDirectory
));
439 // We don't care about this specific file.
440 errs() << "Test Directory: " << TestDirectory
<< '\n';
442 NonExistantFile
= TestDirectory
;
444 // Even though this value is hardcoded, is a 128-bit GUID, so we should be
445 // guaranteed that this file will never exist.
446 sys::path::append(NonExistantFile
, "1B28B495C16344CB9822E588CD4C3EF0");
449 void TearDown() override
{ ASSERT_NO_ERROR(fs::remove(TestDirectory
.str())); }
452 TEST_F(FileSystemTest
, Unique
) {
453 // Create a temp file.
455 SmallString
<64> TempPath
;
457 fs::createTemporaryFile("prefix", "temp", FileDescriptor
, TempPath
));
459 // The same file should return an identical unique id.
461 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath
), F1
));
462 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath
), F2
));
465 // Different files should return different unique ids.
467 SmallString
<64> TempPath2
;
469 fs::createTemporaryFile("prefix", "temp", FileDescriptor2
, TempPath2
));
472 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2
), D
));
474 ::close(FileDescriptor2
);
476 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2
)));
478 // Two paths representing the same file on disk should still provide the
479 // same unique id. We can test this by making a hard link.
480 ASSERT_NO_ERROR(fs::create_link(Twine(TempPath
), Twine(TempPath2
)));
482 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2
), D2
));
485 ::close(FileDescriptor
);
487 SmallString
<128> Dir1
;
489 fs::createUniqueDirectory("dir1", Dir1
));
490 ASSERT_NO_ERROR(fs::getUniqueID(Dir1
.c_str(), F1
));
491 ASSERT_NO_ERROR(fs::getUniqueID(Dir1
.c_str(), F2
));
494 SmallString
<128> Dir2
;
496 fs::createUniqueDirectory("dir2", Dir2
));
497 ASSERT_NO_ERROR(fs::getUniqueID(Dir2
.c_str(), F2
));
499 ASSERT_NO_ERROR(fs::remove(Dir1
));
500 ASSERT_NO_ERROR(fs::remove(Dir2
));
501 ASSERT_NO_ERROR(fs::remove(TempPath2
));
502 ASSERT_NO_ERROR(fs::remove(TempPath
));
505 TEST_F(FileSystemTest
, RealPath
) {
507 fs::create_directories(Twine(TestDirectory
) + "/test1/test2/test3"));
508 ASSERT_TRUE(fs::exists(Twine(TestDirectory
) + "/test1/test2/test3"));
510 SmallString
<64> RealBase
;
511 SmallString
<64> Expected
;
512 SmallString
<64> Actual
;
514 // TestDirectory itself might be under a symlink or have been specified with
515 // a different case than the existing temp directory. In such cases real_path
516 // on the concatenated path will differ in the TestDirectory portion from
517 // how we specified it. Make sure to compare against the real_path of the
518 // TestDirectory, and not just the value of TestDirectory.
519 ASSERT_NO_ERROR(fs::real_path(TestDirectory
, RealBase
));
520 path::native(Twine(RealBase
) + "/test1/test2", Expected
);
522 ASSERT_NO_ERROR(fs::real_path(
523 Twine(TestDirectory
) + "/././test1/../test1/test2/./test3/..", Actual
));
525 EXPECT_EQ(Expected
, Actual
);
527 SmallString
<64> HomeDir
;
529 // This can fail if $HOME is not set and getpwuid fails.
530 bool Result
= llvm::sys::path::home_directory(HomeDir
);
532 ASSERT_NO_ERROR(fs::real_path(HomeDir
, Expected
));
533 ASSERT_NO_ERROR(fs::real_path("~", Actual
, true));
534 EXPECT_EQ(Expected
, Actual
);
535 ASSERT_NO_ERROR(fs::real_path("~/", Actual
, true));
536 EXPECT_EQ(Expected
, Actual
);
539 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory
) + "/test1"));
542 TEST_F(FileSystemTest
, ExpandTilde
) {
543 SmallString
<64> Expected
;
544 SmallString
<64> Actual
;
545 SmallString
<64> HomeDir
;
547 // This can fail if $HOME is not set and getpwuid fails.
548 bool Result
= llvm::sys::path::home_directory(HomeDir
);
550 fs::expand_tilde(HomeDir
, Expected
);
552 fs::expand_tilde("~", Actual
);
553 EXPECT_EQ(Expected
, Actual
);
557 fs::expand_tilde("~\\foo", Actual
);
560 fs::expand_tilde("~/foo", Actual
);
563 EXPECT_EQ(Expected
, Actual
);
568 TEST_F(FileSystemTest
, RealPathNoReadPerm
) {
569 SmallString
<64> Expanded
;
572 fs::create_directories(Twine(TestDirectory
) + "/noreadperm"));
573 ASSERT_TRUE(fs::exists(Twine(TestDirectory
) + "/noreadperm"));
575 fs::setPermissions(Twine(TestDirectory
) + "/noreadperm", fs::no_perms
);
576 fs::setPermissions(Twine(TestDirectory
) + "/noreadperm", fs::all_exe
);
578 ASSERT_NO_ERROR(fs::real_path(Twine(TestDirectory
) + "/noreadperm", Expanded
,
581 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory
) + "/noreadperm"));
586 TEST_F(FileSystemTest
, TempFileKeepDiscard
) {
587 // We can keep then discard.
588 auto TempFileOrError
= fs::TempFile::create(TestDirectory
+ "/test-%%%%");
589 ASSERT_TRUE((bool)TempFileOrError
);
590 fs::TempFile File
= std::move(*TempFileOrError
);
591 ASSERT_EQ(-1, TempFileOrError
->FD
);
592 ASSERT_FALSE((bool)File
.keep(TestDirectory
+ "/keep"));
593 ASSERT_FALSE((bool)File
.discard());
594 ASSERT_TRUE(fs::exists(TestDirectory
+ "/keep"));
595 ASSERT_NO_ERROR(fs::remove(TestDirectory
+ "/keep"));
598 TEST_F(FileSystemTest
, TempFileDiscardDiscard
) {
599 // We can discard twice.
600 auto TempFileOrError
= fs::TempFile::create(TestDirectory
+ "/test-%%%%");
601 ASSERT_TRUE((bool)TempFileOrError
);
602 fs::TempFile File
= std::move(*TempFileOrError
);
603 ASSERT_EQ(-1, TempFileOrError
->FD
);
604 ASSERT_FALSE((bool)File
.discard());
605 ASSERT_FALSE((bool)File
.discard());
606 ASSERT_FALSE(fs::exists(TestDirectory
+ "/keep"));
609 TEST_F(FileSystemTest
, TempFiles
) {
610 // Create a temp file.
612 SmallString
<64> TempPath
;
614 fs::createTemporaryFile("prefix", "temp", FileDescriptor
, TempPath
));
616 // Make sure it exists.
617 ASSERT_TRUE(sys::fs::exists(Twine(TempPath
)));
619 // Create another temp tile.
621 SmallString
<64> TempPath2
;
622 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD2
, TempPath2
));
623 ASSERT_TRUE(TempPath2
.endswith(".temp"));
624 ASSERT_NE(TempPath
.str(), TempPath2
.str());
626 fs::file_status A
, B
;
627 ASSERT_NO_ERROR(fs::status(Twine(TempPath
), A
));
628 ASSERT_NO_ERROR(fs::status(Twine(TempPath2
), B
));
629 EXPECT_FALSE(fs::equivalent(A
, B
));
634 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2
)));
635 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2
)));
636 ASSERT_EQ(fs::remove(Twine(TempPath2
), false),
637 errc::no_such_file_or_directory
);
639 std::error_code EC
= fs::status(TempPath2
.c_str(), B
);
640 EXPECT_EQ(EC
, errc::no_such_file_or_directory
);
641 EXPECT_EQ(B
.type(), fs::file_type::file_not_found
);
643 // Make sure Temp2 doesn't exist.
644 ASSERT_EQ(fs::access(Twine(TempPath2
), sys::fs::AccessMode::Exist
),
645 errc::no_such_file_or_directory
);
647 SmallString
<64> TempPath3
;
648 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "", TempPath3
));
649 ASSERT_FALSE(TempPath3
.endswith("."));
650 FileRemover
Cleanup3(TempPath3
);
652 // Create a hard link to Temp1.
653 ASSERT_NO_ERROR(fs::create_link(Twine(TempPath
), Twine(TempPath2
)));
655 ASSERT_NO_ERROR(fs::equivalent(Twine(TempPath
), Twine(TempPath2
), equal
));
657 ASSERT_NO_ERROR(fs::status(Twine(TempPath
), A
));
658 ASSERT_NO_ERROR(fs::status(Twine(TempPath2
), B
));
659 EXPECT_TRUE(fs::equivalent(A
, B
));
662 ::close(FileDescriptor
);
663 ASSERT_NO_ERROR(fs::remove(Twine(TempPath
)));
665 // Remove the hard link.
666 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2
)));
668 // Make sure Temp1 doesn't exist.
669 ASSERT_EQ(fs::access(Twine(TempPath
), sys::fs::AccessMode::Exist
),
670 errc::no_such_file_or_directory
);
673 // Path name > 260 chars should get an error.
674 const char *Path270
=
675 "abcdefghijklmnopqrstuvwxyz9abcdefghijklmnopqrstuvwxyz8"
676 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
677 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
678 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
679 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
680 EXPECT_EQ(fs::createUniqueFile(Path270
, FileDescriptor
, TempPath
),
681 errc::invalid_argument
);
682 // Relative path < 247 chars, no problem.
683 const char *Path216
=
684 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
685 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
686 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
687 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
688 ASSERT_NO_ERROR(fs::createTemporaryFile(Path216
, "", TempPath
));
689 ASSERT_NO_ERROR(fs::remove(Twine(TempPath
)));
693 TEST_F(FileSystemTest
, TempFileCollisions
) {
694 SmallString
<128> TestDirectory
;
696 fs::createUniqueDirectory("CreateUniqueFileTest", TestDirectory
));
697 FileRemover
Cleanup(TestDirectory
);
698 SmallString
<128> Model
= TestDirectory
;
699 path::append(Model
, "%.tmp");
700 SmallString
<128> Path
;
701 std::vector
<fs::TempFile
> TempFiles
;
703 auto TryCreateTempFile
= [&]() {
704 Expected
<fs::TempFile
> T
= fs::TempFile::create(Model
);
706 TempFiles
.push_back(std::move(*T
));
709 logAllUnhandledErrors(T
.takeError(), errs(),
710 "Failed to create temporary file: ");
715 // Our single-character template allows for 16 unique names. Check that
716 // calling TryCreateTempFile repeatedly results in 16 successes.
717 // Because the test depends on random numbers, it could theoretically fail.
718 // However, the probability of this happening is tiny: with 32 calls, each
719 // of which will retry up to 128 times, to not get a given digit we would
720 // have to fail at least 15 + 17 * 128 = 2191 attempts. The probability of
721 // 2191 attempts not producing a given hexadecimal digit is
722 // (1 - 1/16) ** 2191 or 3.88e-62.
724 for (int i
= 0; i
< 32; ++i
)
725 if (TryCreateTempFile()) ++Successes
;
726 EXPECT_EQ(Successes
, 16);
728 for (fs::TempFile
&T
: TempFiles
)
729 cantFail(T
.discard());
732 TEST_F(FileSystemTest
, CreateDir
) {
733 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory
) + "foo"));
734 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory
) + "foo"));
735 ASSERT_EQ(fs::create_directory(Twine(TestDirectory
) + "foo", false),
737 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "foo"));
740 // Set a 0000 umask so that we can test our directory permissions.
741 mode_t OldUmask
= ::umask(0000);
743 fs::file_status Status
;
745 fs::create_directory(Twine(TestDirectory
) + "baz500", false,
746 fs::perms::owner_read
| fs::perms::owner_exe
));
747 ASSERT_NO_ERROR(fs::status(Twine(TestDirectory
) + "baz500", Status
));
748 ASSERT_EQ(Status
.permissions() & fs::perms::all_all
,
749 fs::perms::owner_read
| fs::perms::owner_exe
);
750 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory
) + "baz777", false,
751 fs::perms::all_all
));
752 ASSERT_NO_ERROR(fs::status(Twine(TestDirectory
) + "baz777", Status
));
753 ASSERT_EQ(Status
.permissions() & fs::perms::all_all
, fs::perms::all_all
);
755 // Restore umask to be safe.
760 // Prove that create_directories() can handle a pathname > 248 characters,
761 // which is the documented limit for CreateDirectory().
762 // (248 is MAX_PATH subtracting room for an 8.3 filename.)
763 // Generate a directory path guaranteed to fall into that range.
764 size_t TmpLen
= TestDirectory
.size();
765 const char *OneDir
= "\\123456789";
766 size_t OneDirLen
= strlen(OneDir
);
767 ASSERT_LT(OneDirLen
, 12U);
768 size_t NLevels
= ((248 - TmpLen
) / OneDirLen
) + 1;
769 SmallString
<260> LongDir(TestDirectory
);
770 for (size_t I
= 0; I
< NLevels
; ++I
)
771 LongDir
.append(OneDir
);
772 ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir
)));
773 ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir
)));
774 ASSERT_EQ(fs::create_directories(Twine(LongDir
), false),
776 // Tidy up, "recursively" removing the directories.
777 StringRef
ThisDir(LongDir
);
778 for (size_t J
= 0; J
< NLevels
; ++J
) {
779 ASSERT_NO_ERROR(fs::remove(ThisDir
));
780 ThisDir
= path::parent_path(ThisDir
);
783 // Also verify that paths with Unix separators are handled correctly.
784 std::string
LongPathWithUnixSeparators(TestDirectory
.str());
785 // Add at least one subdirectory to TestDirectory, and replace slashes with
788 LongPathWithUnixSeparators
.append("/DirNameWith19Charss");
789 } while (LongPathWithUnixSeparators
.size() < 260);
790 std::replace(LongPathWithUnixSeparators
.begin(),
791 LongPathWithUnixSeparators
.end(),
793 ASSERT_NO_ERROR(fs::create_directories(Twine(LongPathWithUnixSeparators
)));
795 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory
) +
796 "/DirNameWith19Charss"));
798 // Similarly for a relative pathname. Need to set the current directory to
799 // TestDirectory so that the one we create ends up in the right place.
800 char PreviousDir
[260];
801 size_t PreviousDirLen
= ::GetCurrentDirectoryA(260, PreviousDir
);
802 ASSERT_GT(PreviousDirLen
, 0U);
803 ASSERT_LT(PreviousDirLen
, 260U);
804 ASSERT_NE(::SetCurrentDirectoryA(TestDirectory
.c_str()), 0);
806 // Generate a relative directory name with absolute length > 248.
807 size_t LongDirLen
= 249 - TestDirectory
.size();
808 LongDir
.assign(LongDirLen
, 'a');
809 ASSERT_NO_ERROR(fs::create_directory(Twine(LongDir
)));
810 // While we're here, prove that .. and . handling works in these long paths.
811 const char *DotDotDirs
= "\\..\\.\\b";
812 LongDir
.append(DotDotDirs
);
813 ASSERT_NO_ERROR(fs::create_directory("b"));
814 ASSERT_EQ(fs::create_directory(Twine(LongDir
), false), errc::file_exists
);
816 ASSERT_NO_ERROR(fs::remove("b"));
817 ASSERT_NO_ERROR(fs::remove(
818 Twine(LongDir
.substr(0, LongDir
.size() - strlen(DotDotDirs
)))));
819 ASSERT_NE(::SetCurrentDirectoryA(PreviousDir
), 0);
823 TEST_F(FileSystemTest
, DirectoryIteration
) {
825 for (fs::directory_iterator
i(".", ec
), e
; i
!= e
; i
.increment(ec
))
828 // Create a known hierarchy to recurse over.
830 fs::create_directories(Twine(TestDirectory
) + "/recursive/a0/aa1"));
832 fs::create_directories(Twine(TestDirectory
) + "/recursive/a0/ab1"));
833 ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory
) +
834 "/recursive/dontlookhere/da1"));
836 fs::create_directories(Twine(TestDirectory
) + "/recursive/z0/za1"));
838 fs::create_directories(Twine(TestDirectory
) + "/recursive/pop/p1"));
839 typedef std::vector
<std::string
> v_t
;
841 for (fs::recursive_directory_iterator
i(Twine(TestDirectory
)
842 + "/recursive", ec
), e
; i
!= e
; i
.increment(ec
)){
844 if (path::filename(i
->path()) == "p1") {
846 // FIXME: recursive_directory_iterator should be more robust.
849 if (path::filename(i
->path()) == "dontlookhere")
851 visited
.push_back(path::filename(i
->path()));
853 v_t::const_iterator a0
= find(visited
, "a0");
854 v_t::const_iterator aa1
= find(visited
, "aa1");
855 v_t::const_iterator ab1
= find(visited
, "ab1");
856 v_t::const_iterator dontlookhere
= find(visited
, "dontlookhere");
857 v_t::const_iterator da1
= find(visited
, "da1");
858 v_t::const_iterator z0
= find(visited
, "z0");
859 v_t::const_iterator za1
= find(visited
, "za1");
860 v_t::const_iterator pop
= find(visited
, "pop");
861 v_t::const_iterator p1
= find(visited
, "p1");
863 // Make sure that each path was visited correctly.
864 ASSERT_NE(a0
, visited
.end());
865 ASSERT_NE(aa1
, visited
.end());
866 ASSERT_NE(ab1
, visited
.end());
867 ASSERT_NE(dontlookhere
, visited
.end());
868 ASSERT_EQ(da1
, visited
.end()); // Not visited.
869 ASSERT_NE(z0
, visited
.end());
870 ASSERT_NE(za1
, visited
.end());
871 ASSERT_NE(pop
, visited
.end());
872 ASSERT_EQ(p1
, visited
.end()); // Not visited.
874 // Make sure that parents were visited before children. No other ordering
875 // guarantees can be made across siblings.
880 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/a0/aa1"));
881 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/a0/ab1"));
882 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/a0"));
884 fs::remove(Twine(TestDirectory
) + "/recursive/dontlookhere/da1"));
885 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/dontlookhere"));
886 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/pop/p1"));
887 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/pop"));
888 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/z0/za1"));
889 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/z0"));
890 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive"));
892 // Test recursive_directory_iterator level()
894 fs::create_directories(Twine(TestDirectory
) + "/reclevel/a/b/c"));
895 fs::recursive_directory_iterator
I(Twine(TestDirectory
) + "/reclevel", ec
), E
;
896 for (int l
= 0; I
!= E
; I
.increment(ec
), ++l
) {
898 EXPECT_EQ(I
.level(), l
);
901 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/reclevel/a/b/c"));
902 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/reclevel/a/b"));
903 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/reclevel/a"));
904 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/reclevel"));
908 TEST_F(FileSystemTest
, BrokenSymlinkDirectoryIteration
) {
909 // Create a known hierarchy to recurse over.
910 ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory
) + "/symlink"));
912 fs::create_link("no_such_file", Twine(TestDirectory
) + "/symlink/a"));
914 fs::create_directories(Twine(TestDirectory
) + "/symlink/b/bb"));
916 fs::create_link("no_such_file", Twine(TestDirectory
) + "/symlink/b/ba"));
918 fs::create_link("no_such_file", Twine(TestDirectory
) + "/symlink/b/bc"));
920 fs::create_link("no_such_file", Twine(TestDirectory
) + "/symlink/c"));
922 fs::create_directories(Twine(TestDirectory
) + "/symlink/d/dd/ddd"));
923 ASSERT_NO_ERROR(fs::create_link(Twine(TestDirectory
) + "/symlink/d/dd",
924 Twine(TestDirectory
) + "/symlink/d/da"));
926 fs::create_link("no_such_file", Twine(TestDirectory
) + "/symlink/e"));
928 typedef std::vector
<std::string
> v_t
;
929 v_t VisitedNonBrokenSymlinks
;
930 v_t VisitedBrokenSymlinks
;
932 using testing::UnorderedElementsAre
;
933 using testing::UnorderedElementsAreArray
;
935 // Broken symbol links are expected to throw an error.
936 for (fs::directory_iterator
i(Twine(TestDirectory
) + "/symlink", ec
), e
;
937 i
!= e
; i
.increment(ec
)) {
939 if (i
->status().getError() ==
940 std::make_error_code(std::errc::no_such_file_or_directory
)) {
941 VisitedBrokenSymlinks
.push_back(path::filename(i
->path()));
944 VisitedNonBrokenSymlinks
.push_back(path::filename(i
->path()));
946 EXPECT_THAT(VisitedNonBrokenSymlinks
, UnorderedElementsAre("b", "d"));
947 VisitedNonBrokenSymlinks
.clear();
949 EXPECT_THAT(VisitedBrokenSymlinks
, UnorderedElementsAre("a", "c", "e"));
950 VisitedBrokenSymlinks
.clear();
952 // Broken symbol links are expected to throw an error.
953 for (fs::recursive_directory_iterator
i(
954 Twine(TestDirectory
) + "/symlink", ec
), e
; i
!= e
; i
.increment(ec
)) {
956 if (i
->status().getError() ==
957 std::make_error_code(std::errc::no_such_file_or_directory
)) {
958 VisitedBrokenSymlinks
.push_back(path::filename(i
->path()));
961 VisitedNonBrokenSymlinks
.push_back(path::filename(i
->path()));
963 EXPECT_THAT(VisitedNonBrokenSymlinks
,
964 UnorderedElementsAre("b", "bb", "d", "da", "dd", "ddd", "ddd"));
965 VisitedNonBrokenSymlinks
.clear();
967 EXPECT_THAT(VisitedBrokenSymlinks
,
968 UnorderedElementsAre("a", "ba", "bc", "c", "e"));
969 VisitedBrokenSymlinks
.clear();
971 for (fs::recursive_directory_iterator
i(
972 Twine(TestDirectory
) + "/symlink", ec
, /*follow_symlinks=*/false), e
;
973 i
!= e
; i
.increment(ec
)) {
975 if (i
->status().getError() ==
976 std::make_error_code(std::errc::no_such_file_or_directory
)) {
977 VisitedBrokenSymlinks
.push_back(path::filename(i
->path()));
980 VisitedNonBrokenSymlinks
.push_back(path::filename(i
->path()));
982 EXPECT_THAT(VisitedNonBrokenSymlinks
,
983 UnorderedElementsAreArray({"a", "b", "ba", "bb", "bc", "c", "d",
984 "da", "dd", "ddd", "e"}));
985 VisitedNonBrokenSymlinks
.clear();
987 EXPECT_THAT(VisitedBrokenSymlinks
, UnorderedElementsAre());
988 VisitedBrokenSymlinks
.clear();
990 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory
) + "/symlink"));
994 TEST_F(FileSystemTest
, Remove
) {
995 SmallString
<64> BaseDir
;
996 SmallString
<64> Paths
[4];
998 ASSERT_NO_ERROR(fs::createUniqueDirectory("fs_remove", BaseDir
));
1000 ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir
) + "/foo/bar/baz"));
1001 ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir
) + "/foo/bar/buzz"));
1002 ASSERT_NO_ERROR(fs::createUniqueFile(
1003 Twine(BaseDir
) + "/foo/bar/baz/%%%%%%.tmp", fds
[0], Paths
[0]));
1004 ASSERT_NO_ERROR(fs::createUniqueFile(
1005 Twine(BaseDir
) + "/foo/bar/baz/%%%%%%.tmp", fds
[1], Paths
[1]));
1006 ASSERT_NO_ERROR(fs::createUniqueFile(
1007 Twine(BaseDir
) + "/foo/bar/buzz/%%%%%%.tmp", fds
[2], Paths
[2]));
1008 ASSERT_NO_ERROR(fs::createUniqueFile(
1009 Twine(BaseDir
) + "/foo/bar/buzz/%%%%%%.tmp", fds
[3], Paths
[3]));
1014 EXPECT_TRUE(fs::exists(Twine(BaseDir
) + "/foo/bar/baz"));
1015 EXPECT_TRUE(fs::exists(Twine(BaseDir
) + "/foo/bar/buzz"));
1016 EXPECT_TRUE(fs::exists(Paths
[0]));
1017 EXPECT_TRUE(fs::exists(Paths
[1]));
1018 EXPECT_TRUE(fs::exists(Paths
[2]));
1019 EXPECT_TRUE(fs::exists(Paths
[3]));
1021 ASSERT_NO_ERROR(fs::remove_directories("D:/footest"));
1023 ASSERT_NO_ERROR(fs::remove_directories(BaseDir
));
1024 ASSERT_FALSE(fs::exists(BaseDir
));
1028 TEST_F(FileSystemTest
, CarriageReturn
) {
1029 SmallString
<128> FilePathname(TestDirectory
);
1031 path::append(FilePathname
, "test");
1034 raw_fd_ostream
File(FilePathname
, EC
, sys::fs::OF_Text
);
1035 ASSERT_NO_ERROR(EC
);
1039 auto Buf
= MemoryBuffer::getFile(FilePathname
.str());
1040 EXPECT_TRUE((bool)Buf
);
1041 EXPECT_EQ(Buf
.get()->getBuffer(), "\r\n");
1045 raw_fd_ostream
File(FilePathname
, EC
, sys::fs::OF_None
);
1046 ASSERT_NO_ERROR(EC
);
1050 auto Buf
= MemoryBuffer::getFile(FilePathname
.str());
1051 EXPECT_TRUE((bool)Buf
);
1052 EXPECT_EQ(Buf
.get()->getBuffer(), "\n");
1054 ASSERT_NO_ERROR(fs::remove(Twine(FilePathname
)));
1058 TEST_F(FileSystemTest
, Resize
) {
1060 SmallString
<64> TempPath
;
1061 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD
, TempPath
));
1062 ASSERT_NO_ERROR(fs::resize_file(FD
, 123));
1063 fs::file_status Status
;
1064 ASSERT_NO_ERROR(fs::status(FD
, Status
));
1065 ASSERT_EQ(Status
.getSize(), 123U);
1067 ASSERT_NO_ERROR(fs::remove(TempPath
));
1070 TEST_F(FileSystemTest
, MD5
) {
1072 SmallString
<64> TempPath
;
1073 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD
, TempPath
));
1074 StringRef
Data("abcdefghijklmnopqrstuvwxyz");
1075 ASSERT_EQ(write(FD
, Data
.data(), Data
.size()), static_cast<ssize_t
>(Data
.size()));
1076 lseek(FD
, 0, SEEK_SET
);
1077 auto Hash
= fs::md5_contents(FD
);
1079 ASSERT_NO_ERROR(Hash
.getError());
1081 EXPECT_STREQ("c3fcd3d76192e4007dfb496cca67e13b", Hash
->digest().c_str());
1084 TEST_F(FileSystemTest
, FileMapping
) {
1085 // Create a temp file.
1087 SmallString
<64> TempPath
;
1089 fs::createTemporaryFile("prefix", "temp", FileDescriptor
, TempPath
));
1090 unsigned Size
= 4096;
1091 ASSERT_NO_ERROR(fs::resize_file(FileDescriptor
, Size
));
1093 // Map in temp file and add some content
1095 StringRef
Val("hello there");
1097 fs::mapped_file_region
mfr(fs::convertFDToNativeFile(FileDescriptor
),
1098 fs::mapped_file_region::readwrite
, Size
, 0, EC
);
1099 ASSERT_NO_ERROR(EC
);
1100 std::copy(Val
.begin(), Val
.end(), mfr
.data());
1101 // Explicitly add a 0.
1102 mfr
.data()[Val
.size()] = 0;
1105 ASSERT_EQ(close(FileDescriptor
), 0);
1107 // Map it back in read-only
1110 EC
= fs::openFileForRead(Twine(TempPath
), FD
);
1111 ASSERT_NO_ERROR(EC
);
1112 fs::mapped_file_region
mfr(fs::convertFDToNativeFile(FD
),
1113 fs::mapped_file_region::readonly
, Size
, 0, EC
);
1114 ASSERT_NO_ERROR(EC
);
1117 EXPECT_EQ(StringRef(mfr
.const_data()), Val
);
1120 fs::mapped_file_region
m(fs::convertFDToNativeFile(FD
),
1121 fs::mapped_file_region::readonly
, Size
, 0, EC
);
1122 ASSERT_NO_ERROR(EC
);
1123 ASSERT_EQ(close(FD
), 0);
1125 ASSERT_NO_ERROR(fs::remove(TempPath
));
1128 TEST(Support
, NormalizePath
) {
1129 using TestTuple
= std::tuple
<const char *, const char *, const char *>;
1130 std::vector
<TestTuple
> Tests
;
1131 Tests
.emplace_back("a", "a", "a");
1132 Tests
.emplace_back("a/b", "a\\b", "a/b");
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", "\\a", "/a");
1136 Tests
.emplace_back("a\\", "a\\", "a/");
1138 for (auto &T
: Tests
) {
1139 SmallString
<64> Win(std::get
<0>(T
));
1140 SmallString
<64> Posix(Win
);
1141 path::native(Win
, path::Style::windows
);
1142 path::native(Posix
, path::Style::posix
);
1143 EXPECT_EQ(std::get
<1>(T
), Win
);
1144 EXPECT_EQ(std::get
<2>(T
), Posix
);
1148 SmallString
<64> PathHome
;
1149 path::home_directory(PathHome
);
1151 const char *Path7a
= "~/aaa";
1152 SmallString
<64> Path7(Path7a
);
1153 path::native(Path7
);
1154 EXPECT_TRUE(Path7
.endswith("\\aaa"));
1155 EXPECT_TRUE(Path7
.startswith(PathHome
));
1156 EXPECT_EQ(Path7
.size(), PathHome
.size() + strlen(Path7a
+ 1));
1158 const char *Path8a
= "~";
1159 SmallString
<64> Path8(Path8a
);
1160 path::native(Path8
);
1161 EXPECT_EQ(Path8
, PathHome
);
1163 const char *Path9a
= "~aaa";
1164 SmallString
<64> Path9(Path9a
);
1165 path::native(Path9
);
1166 EXPECT_EQ(Path9
, "~aaa");
1168 const char *Path10a
= "aaa/~/b";
1169 SmallString
<64> Path10(Path10a
);
1170 path::native(Path10
);
1171 EXPECT_EQ(Path10
, "aaa\\~\\b");
1175 TEST(Support
, RemoveLeadingDotSlash
) {
1176 StringRef
Path1("././/foolz/wat");
1177 StringRef
Path2("./////");
1179 Path1
= path::remove_leading_dotslash(Path1
);
1180 EXPECT_EQ(Path1
, "foolz/wat");
1181 Path2
= path::remove_leading_dotslash(Path2
);
1182 EXPECT_EQ(Path2
, "");
1185 static std::string
remove_dots(StringRef path
, bool remove_dot_dot
,
1186 path::Style style
) {
1187 SmallString
<256> buffer(path
);
1188 path::remove_dots(buffer
, remove_dot_dot
, style
);
1189 return buffer
.str();
1192 TEST(Support
, RemoveDots
) {
1193 EXPECT_EQ("foolz\\wat",
1194 remove_dots(".\\.\\\\foolz\\wat", false, path::Style::windows
));
1195 EXPECT_EQ("", remove_dots(".\\\\\\\\\\", false, path::Style::windows
));
1197 EXPECT_EQ("a\\..\\b\\c",
1198 remove_dots(".\\a\\..\\b\\c", false, path::Style::windows
));
1199 EXPECT_EQ("b\\c", remove_dots(".\\a\\..\\b\\c", true, path::Style::windows
));
1200 EXPECT_EQ("c", remove_dots(".\\.\\c", true, path::Style::windows
));
1201 EXPECT_EQ("..\\a\\c",
1202 remove_dots("..\\a\\b\\..\\c", true, path::Style::windows
));
1203 EXPECT_EQ("..\\..\\a\\c",
1204 remove_dots("..\\..\\a\\b\\..\\c", true, path::Style::windows
));
1206 SmallString
<64> Path1(".\\.\\c");
1207 EXPECT_TRUE(path::remove_dots(Path1
, true, path::Style::windows
));
1208 EXPECT_EQ("c", Path1
);
1210 EXPECT_EQ("foolz/wat",
1211 remove_dots("././/foolz/wat", false, path::Style::posix
));
1212 EXPECT_EQ("", remove_dots("./////", false, path::Style::posix
));
1214 EXPECT_EQ("a/../b/c", remove_dots("./a/../b/c", false, path::Style::posix
));
1215 EXPECT_EQ("b/c", remove_dots("./a/../b/c", true, path::Style::posix
));
1216 EXPECT_EQ("c", remove_dots("././c", true, path::Style::posix
));
1217 EXPECT_EQ("../a/c", remove_dots("../a/b/../c", true, path::Style::posix
));
1218 EXPECT_EQ("../../a/c",
1219 remove_dots("../../a/b/../c", true, path::Style::posix
));
1220 EXPECT_EQ("/a/c", remove_dots("/../../a/c", true, path::Style::posix
));
1222 remove_dots("/../a/b//../././/c", true, path::Style::posix
));
1224 SmallString
<64> Path2("././c");
1225 EXPECT_TRUE(path::remove_dots(Path2
, true, path::Style::posix
));
1226 EXPECT_EQ("c", Path2
);
1229 TEST(Support
, ReplacePathPrefix
) {
1230 SmallString
<64> Path1("/foo");
1231 SmallString
<64> Path2("/old/foo");
1232 SmallString
<64> OldPrefix("/old");
1233 SmallString
<64> NewPrefix("/new");
1234 SmallString
<64> NewPrefix2("/longernew");
1235 SmallString
<64> EmptyPrefix("");
1237 SmallString
<64> Path
= Path1
;
1238 path::replace_path_prefix(Path
, OldPrefix
, NewPrefix
);
1239 EXPECT_EQ(Path
, "/foo");
1241 path::replace_path_prefix(Path
, OldPrefix
, NewPrefix
);
1242 EXPECT_EQ(Path
, "/new/foo");
1244 path::replace_path_prefix(Path
, OldPrefix
, NewPrefix2
);
1245 EXPECT_EQ(Path
, "/longernew/foo");
1247 path::replace_path_prefix(Path
, EmptyPrefix
, NewPrefix
);
1248 EXPECT_EQ(Path
, "/new/foo");
1250 path::replace_path_prefix(Path
, OldPrefix
, EmptyPrefix
);
1251 EXPECT_EQ(Path
, "/foo");
1254 TEST_F(FileSystemTest
, OpenFileForRead
) {
1255 // Create a temp file.
1257 SmallString
<64> TempPath
;
1259 fs::createTemporaryFile("prefix", "temp", FileDescriptor
, TempPath
));
1260 FileRemover
Cleanup(TempPath
);
1262 // Make sure it exists.
1263 ASSERT_TRUE(sys::fs::exists(Twine(TempPath
)));
1265 // Open the file for read
1266 int FileDescriptor2
;
1267 SmallString
<64> ResultPath
;
1268 ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath
), FileDescriptor2
,
1269 fs::OF_None
, &ResultPath
))
1271 // If we succeeded, check that the paths are the same (modulo case):
1272 if (!ResultPath
.empty()) {
1273 // The paths returned by createTemporaryFile and getPathFromOpenFD
1274 // should reference the same file on disk.
1275 fs::UniqueID D1
, D2
;
1276 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath
), D1
));
1277 ASSERT_NO_ERROR(fs::getUniqueID(Twine(ResultPath
), D2
));
1280 ::close(FileDescriptor
);
1281 ::close(FileDescriptor2
);
1284 // Since Windows Vista, file access time is not updated by default.
1285 // This is instead updated manually by openFileForRead.
1286 // https://blogs.technet.microsoft.com/filecab/2006/11/07/disabling-last-access-time-in-windows-vista-to-improve-ntfs-performance/
1287 // This part of the unit test is Windows specific as the updating of
1288 // access times can be disabled on Linux using /etc/fstab.
1290 // Set access time to UNIX epoch.
1291 ASSERT_NO_ERROR(sys::fs::openFileForWrite(Twine(TempPath
), FileDescriptor
,
1292 fs::CD_OpenExisting
));
1293 TimePoint
<> Epoch(std::chrono::milliseconds(0));
1294 ASSERT_NO_ERROR(fs::setLastAccessAndModificationTime(FileDescriptor
, Epoch
));
1295 ::close(FileDescriptor
);
1297 // Open the file and ensure access time is updated, when forced.
1298 ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath
), FileDescriptor
,
1299 fs::OF_UpdateAtime
, &ResultPath
));
1301 sys::fs::file_status Status
;
1302 ASSERT_NO_ERROR(sys::fs::status(FileDescriptor
, Status
));
1303 auto FileAccessTime
= Status
.getLastAccessedTime();
1305 ASSERT_NE(Epoch
, FileAccessTime
);
1306 ::close(FileDescriptor
);
1308 // Ideally this test would include a case when ATime is not forced to update,
1309 // however the expected behaviour will differ depending on the configuration
1310 // of the Windows file system.
1314 static void createFileWithData(const Twine
&Path
, bool ShouldExistBefore
,
1315 fs::CreationDisposition Disp
, StringRef Data
) {
1317 ASSERT_EQ(ShouldExistBefore
, fs::exists(Path
));
1318 ASSERT_NO_ERROR(fs::openFileForWrite(Path
, FD
, Disp
));
1319 FileDescriptorCloser
Closer(FD
);
1320 ASSERT_TRUE(fs::exists(Path
));
1322 ASSERT_EQ(Data
.size(), (size_t)write(FD
, Data
.data(), Data
.size()));
1325 static void verifyFileContents(const Twine
&Path
, StringRef Contents
) {
1326 auto Buffer
= MemoryBuffer::getFile(Path
);
1327 ASSERT_TRUE((bool)Buffer
);
1328 StringRef Data
= Buffer
.get()->getBuffer();
1329 ASSERT_EQ(Data
, Contents
);
1332 TEST_F(FileSystemTest
, CreateNew
) {
1334 Optional
<FileDescriptorCloser
> Closer
;
1336 // Succeeds if the file does not exist.
1337 ASSERT_FALSE(fs::exists(NonExistantFile
));
1338 ASSERT_NO_ERROR(fs::openFileForWrite(NonExistantFile
, FD
, fs::CD_CreateNew
));
1339 ASSERT_TRUE(fs::exists(NonExistantFile
));
1341 FileRemover
Cleanup(NonExistantFile
);
1344 // And creates a file of size 0.
1345 sys::fs::file_status Status
;
1346 ASSERT_NO_ERROR(sys::fs::status(FD
, Status
));
1347 EXPECT_EQ(0ULL, Status
.getSize());
1349 // Close this first, before trying to re-open the file.
1352 // But fails if the file does exist.
1353 ASSERT_ERROR(fs::openFileForWrite(NonExistantFile
, FD
, fs::CD_CreateNew
));
1356 TEST_F(FileSystemTest
, CreateAlways
) {
1358 Optional
<FileDescriptorCloser
> Closer
;
1360 // Succeeds if the file does not exist.
1361 ASSERT_FALSE(fs::exists(NonExistantFile
));
1363 fs::openFileForWrite(NonExistantFile
, FD
, fs::CD_CreateAlways
));
1367 ASSERT_TRUE(fs::exists(NonExistantFile
));
1369 FileRemover
Cleanup(NonExistantFile
);
1371 // And creates a file of size 0.
1373 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1374 ASSERT_EQ(0ULL, FileSize
);
1376 // If we write some data to it re-create it with CreateAlways, it succeeds and
1377 // truncates to 0 bytes.
1378 ASSERT_EQ(4, write(FD
, "Test", 4));
1382 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1383 ASSERT_EQ(4ULL, FileSize
);
1386 fs::openFileForWrite(NonExistantFile
, FD
, fs::CD_CreateAlways
));
1388 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1389 ASSERT_EQ(0ULL, FileSize
);
1392 TEST_F(FileSystemTest
, OpenExisting
) {
1395 // Fails if the file does not exist.
1396 ASSERT_FALSE(fs::exists(NonExistantFile
));
1397 ASSERT_ERROR(fs::openFileForWrite(NonExistantFile
, FD
, fs::CD_OpenExisting
));
1398 ASSERT_FALSE(fs::exists(NonExistantFile
));
1400 // Make a dummy file now so that we can try again when the file does exist.
1401 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "Fizz");
1402 FileRemover
Cleanup(NonExistantFile
);
1404 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1405 ASSERT_EQ(4ULL, FileSize
);
1407 // If we re-create it with different data, it overwrites rather than
1409 createFileWithData(NonExistantFile
, true, fs::CD_OpenExisting
, "Buzz");
1410 verifyFileContents(NonExistantFile
, "Buzz");
1413 TEST_F(FileSystemTest
, OpenAlways
) {
1414 // Succeeds if the file does not exist.
1415 createFileWithData(NonExistantFile
, false, fs::CD_OpenAlways
, "Fizz");
1416 FileRemover
Cleanup(NonExistantFile
);
1418 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1419 ASSERT_EQ(4ULL, FileSize
);
1421 // Now re-open it and write again, verifying the contents get over-written.
1422 createFileWithData(NonExistantFile
, true, fs::CD_OpenAlways
, "Bu");
1423 verifyFileContents(NonExistantFile
, "Buzz");
1426 TEST_F(FileSystemTest
, AppendSetsCorrectFileOffset
) {
1427 fs::CreationDisposition Disps
[] = {fs::CD_CreateAlways
, fs::CD_OpenAlways
,
1428 fs::CD_OpenExisting
};
1430 // Write some data and re-open it with every possible disposition (this is a
1431 // hack that shouldn't work, but is left for compatibility. OF_Append
1433 // the specified disposition.
1434 for (fs::CreationDisposition Disp
: Disps
) {
1436 Optional
<FileDescriptorCloser
> Closer
;
1438 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "Fizz");
1440 FileRemover
Cleanup(NonExistantFile
);
1443 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1444 ASSERT_EQ(4ULL, FileSize
);
1446 fs::openFileForWrite(NonExistantFile
, FD
, Disp
, fs::OF_Append
));
1448 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1449 ASSERT_EQ(4ULL, FileSize
);
1451 ASSERT_EQ(4, write(FD
, "Buzz", 4));
1454 verifyFileContents(NonExistantFile
, "FizzBuzz");
1458 static void verifyRead(int FD
, StringRef Data
, bool ShouldSucceed
) {
1459 std::vector
<char> Buffer
;
1460 Buffer
.resize(Data
.size());
1461 int Result
= ::read(FD
, Buffer
.data(), Buffer
.size());
1462 if (ShouldSucceed
) {
1463 ASSERT_EQ((size_t)Result
, Data
.size());
1464 ASSERT_EQ(Data
, StringRef(Buffer
.data(), Buffer
.size()));
1466 ASSERT_EQ(-1, Result
);
1467 ASSERT_EQ(EBADF
, errno
);
1471 static void verifyWrite(int FD
, StringRef Data
, bool ShouldSucceed
) {
1472 int Result
= ::write(FD
, Data
.data(), Data
.size());
1474 ASSERT_EQ((size_t)Result
, Data
.size());
1476 ASSERT_EQ(-1, Result
);
1477 ASSERT_EQ(EBADF
, errno
);
1481 TEST_F(FileSystemTest
, ReadOnlyFileCantWrite
) {
1482 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "Fizz");
1483 FileRemover
Cleanup(NonExistantFile
);
1486 ASSERT_NO_ERROR(fs::openFileForRead(NonExistantFile
, FD
));
1487 FileDescriptorCloser
Closer(FD
);
1489 verifyWrite(FD
, "Buzz", false);
1490 verifyRead(FD
, "Fizz", true);
1493 TEST_F(FileSystemTest
, WriteOnlyFileCantRead
) {
1494 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "Fizz");
1495 FileRemover
Cleanup(NonExistantFile
);
1499 fs::openFileForWrite(NonExistantFile
, FD
, fs::CD_OpenExisting
));
1500 FileDescriptorCloser
Closer(FD
);
1501 verifyRead(FD
, "Fizz", false);
1502 verifyWrite(FD
, "Buzz", true);
1505 TEST_F(FileSystemTest
, ReadWriteFileCanReadOrWrite
) {
1506 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "Fizz");
1507 FileRemover
Cleanup(NonExistantFile
);
1510 ASSERT_NO_ERROR(fs::openFileForReadWrite(NonExistantFile
, FD
,
1511 fs::CD_OpenExisting
, fs::OF_None
));
1512 FileDescriptorCloser
Closer(FD
);
1513 verifyRead(FD
, "Fizz", true);
1514 verifyWrite(FD
, "Buzz", true);
1517 TEST_F(FileSystemTest
, readNativeFileSlice
) {
1518 char Data
[10] = {'0', '1', '2', '3', '4', 0, 0, 0, 0, 0};
1519 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
,
1520 StringRef(Data
, 5));
1521 FileRemover
Cleanup(NonExistantFile
);
1522 Expected
<fs::file_t
> FD
= fs::openNativeFileForRead(NonExistantFile
);
1523 ASSERT_THAT_EXPECTED(FD
, Succeeded());
1525 const auto &Read
= [&](size_t Offset
,
1526 size_t ToRead
) -> Expected
<ArrayRef
<char>> {
1527 std::memset(Buf
, 0x47, sizeof(Buf
));
1528 if (std::error_code EC
= fs::readNativeFileSlice(
1529 *FD
, makeMutableArrayRef(Buf
, ToRead
), Offset
))
1530 return errorCodeToError(EC
);
1531 return makeArrayRef(Buf
, ToRead
);
1533 EXPECT_THAT_EXPECTED(Read(0, 5), HasValue(makeArrayRef(Data
+ 0, 5)));
1534 EXPECT_THAT_EXPECTED(Read(0, 3), HasValue(makeArrayRef(Data
+ 0, 3)));
1535 EXPECT_THAT_EXPECTED(Read(2, 3), HasValue(makeArrayRef(Data
+ 2, 3)));
1536 EXPECT_THAT_EXPECTED(Read(0, 6), HasValue(makeArrayRef(Data
+ 0, 6)));
1537 EXPECT_THAT_EXPECTED(Read(2, 6), HasValue(makeArrayRef(Data
+ 2, 6)));
1538 EXPECT_THAT_EXPECTED(Read(5, 5), HasValue(makeArrayRef(Data
+ 5, 5)));
1541 TEST_F(FileSystemTest
, is_local
) {
1542 bool TestDirectoryIsLocal
;
1543 ASSERT_NO_ERROR(fs::is_local(TestDirectory
, TestDirectoryIsLocal
));
1544 EXPECT_EQ(TestDirectoryIsLocal
, fs::is_local(TestDirectory
));
1547 SmallString
<128> TempPath
;
1549 fs::createUniqueFile(Twine(TestDirectory
) + "/temp", FD
, TempPath
));
1550 FileRemover
Cleanup(TempPath
);
1552 // Make sure it exists.
1553 ASSERT_TRUE(sys::fs::exists(Twine(TempPath
)));
1555 bool TempFileIsLocal
;
1556 ASSERT_NO_ERROR(fs::is_local(FD
, TempFileIsLocal
));
1557 EXPECT_EQ(TempFileIsLocal
, fs::is_local(FD
));
1560 // Expect that the file and its parent directory are equally local or equally
1562 EXPECT_EQ(TestDirectoryIsLocal
, TempFileIsLocal
);
1565 TEST_F(FileSystemTest
, getUmask
) {
1567 EXPECT_EQ(fs::getUmask(), 0U) << "Should always be 0 on Windows.";
1569 unsigned OldMask
= ::umask(0022);
1570 unsigned CurrentMask
= fs::getUmask();
1571 EXPECT_EQ(CurrentMask
, 0022U)
1572 << "getUmask() didn't return previously set umask()";
1573 EXPECT_EQ(::umask(OldMask
), 0022U) << "getUmask() may have changed umask()";
1577 TEST_F(FileSystemTest
, RespectUmask
) {
1579 unsigned OldMask
= ::umask(0022);
1582 SmallString
<128> TempPath
;
1583 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD
, TempPath
));
1585 fs::perms AllRWE
= static_cast<fs::perms
>(0777);
1587 ASSERT_NO_ERROR(fs::setPermissions(TempPath
, AllRWE
));
1589 ErrorOr
<fs::perms
> Perms
= fs::getPermissions(TempPath
);
1590 ASSERT_TRUE(!!Perms
);
1591 EXPECT_EQ(Perms
.get(), AllRWE
) << "Should have ignored umask by default";
1593 ASSERT_NO_ERROR(fs::setPermissions(TempPath
, AllRWE
));
1595 Perms
= fs::getPermissions(TempPath
);
1596 ASSERT_TRUE(!!Perms
);
1597 EXPECT_EQ(Perms
.get(), AllRWE
) << "Should have ignored umask";
1600 fs::setPermissions(FD
, static_cast<fs::perms
>(AllRWE
& ~fs::getUmask())));
1601 Perms
= fs::getPermissions(TempPath
);
1602 ASSERT_TRUE(!!Perms
);
1603 EXPECT_EQ(Perms
.get(), static_cast<fs::perms
>(0755))
1604 << "Did not respect umask";
1606 (void)::umask(0057);
1609 fs::setPermissions(FD
, static_cast<fs::perms
>(AllRWE
& ~fs::getUmask())));
1610 Perms
= fs::getPermissions(TempPath
);
1611 ASSERT_TRUE(!!Perms
);
1612 EXPECT_EQ(Perms
.get(), static_cast<fs::perms
>(0720))
1613 << "Did not respect umask";
1615 (void)::umask(OldMask
);
1620 TEST_F(FileSystemTest
, set_current_path
) {
1621 SmallString
<128> path
;
1623 ASSERT_NO_ERROR(fs::current_path(path
));
1624 ASSERT_NE(TestDirectory
, path
);
1626 struct RestorePath
{
1627 SmallString
<128> path
;
1628 RestorePath(const SmallString
<128> &path
) : path(path
) {}
1629 ~RestorePath() { fs::set_current_path(path
); }
1630 } restore_path(path
);
1632 ASSERT_NO_ERROR(fs::set_current_path(TestDirectory
));
1634 ASSERT_NO_ERROR(fs::current_path(path
));
1636 fs::UniqueID D1
, D2
;
1637 ASSERT_NO_ERROR(fs::getUniqueID(TestDirectory
, D1
));
1638 ASSERT_NO_ERROR(fs::getUniqueID(path
, D2
));
1639 ASSERT_EQ(D1
, D2
) << "D1: " << TestDirectory
<< "\nD2: " << path
;
1642 TEST_F(FileSystemTest
, permissions
) {
1644 SmallString
<64> TempPath
;
1645 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD
, TempPath
));
1646 FileRemover
Cleanup(TempPath
);
1648 // Make sure it exists.
1649 ASSERT_TRUE(fs::exists(Twine(TempPath
)));
1651 auto CheckPermissions
= [&](fs::perms Expected
) {
1652 ErrorOr
<fs::perms
> Actual
= fs::getPermissions(TempPath
);
1653 return Actual
&& *Actual
== Expected
;
1656 std::error_code NoError
;
1657 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_all
), NoError
);
1658 EXPECT_TRUE(CheckPermissions(fs::all_all
));
1660 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_read
| fs::all_exe
), NoError
);
1661 EXPECT_TRUE(CheckPermissions(fs::all_read
| fs::all_exe
));
1664 fs::perms ReadOnly
= fs::all_read
| fs::all_exe
;
1665 EXPECT_EQ(fs::setPermissions(TempPath
, fs::no_perms
), NoError
);
1666 EXPECT_TRUE(CheckPermissions(ReadOnly
));
1668 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_read
), NoError
);
1669 EXPECT_TRUE(CheckPermissions(ReadOnly
));
1671 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_write
), NoError
);
1672 EXPECT_TRUE(CheckPermissions(fs::all_all
));
1674 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_exe
), NoError
);
1675 EXPECT_TRUE(CheckPermissions(ReadOnly
));
1677 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_all
), NoError
);
1678 EXPECT_TRUE(CheckPermissions(fs::all_all
));
1680 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_read
), NoError
);
1681 EXPECT_TRUE(CheckPermissions(ReadOnly
));
1683 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_write
), NoError
);
1684 EXPECT_TRUE(CheckPermissions(fs::all_all
));
1686 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_exe
), NoError
);
1687 EXPECT_TRUE(CheckPermissions(ReadOnly
));
1689 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_all
), NoError
);
1690 EXPECT_TRUE(CheckPermissions(fs::all_all
));
1692 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_read
), NoError
);
1693 EXPECT_TRUE(CheckPermissions(ReadOnly
));
1695 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_write
), NoError
);
1696 EXPECT_TRUE(CheckPermissions(fs::all_all
));
1698 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_exe
), NoError
);
1699 EXPECT_TRUE(CheckPermissions(ReadOnly
));
1701 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_all
), NoError
);
1702 EXPECT_TRUE(CheckPermissions(fs::all_all
));
1704 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_read
), NoError
);
1705 EXPECT_TRUE(CheckPermissions(ReadOnly
));
1707 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_write
), NoError
);
1708 EXPECT_TRUE(CheckPermissions(fs::all_all
));
1710 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_exe
), NoError
);
1711 EXPECT_TRUE(CheckPermissions(ReadOnly
));
1713 EXPECT_EQ(fs::setPermissions(TempPath
, fs::set_uid_on_exe
), NoError
);
1714 EXPECT_TRUE(CheckPermissions(ReadOnly
));
1716 EXPECT_EQ(fs::setPermissions(TempPath
, fs::set_gid_on_exe
), NoError
);
1717 EXPECT_TRUE(CheckPermissions(ReadOnly
));
1719 EXPECT_EQ(fs::setPermissions(TempPath
, fs::sticky_bit
), NoError
);
1720 EXPECT_TRUE(CheckPermissions(ReadOnly
));
1722 EXPECT_EQ(fs::setPermissions(TempPath
, fs::set_uid_on_exe
|
1723 fs::set_gid_on_exe
|
1726 EXPECT_TRUE(CheckPermissions(ReadOnly
));
1728 EXPECT_EQ(fs::setPermissions(TempPath
, ReadOnly
| fs::set_uid_on_exe
|
1729 fs::set_gid_on_exe
|
1732 EXPECT_TRUE(CheckPermissions(ReadOnly
));
1734 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_perms
), NoError
);
1735 EXPECT_TRUE(CheckPermissions(fs::all_all
));
1737 EXPECT_EQ(fs::setPermissions(TempPath
, fs::no_perms
), NoError
);
1738 EXPECT_TRUE(CheckPermissions(fs::no_perms
));
1740 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_read
), NoError
);
1741 EXPECT_TRUE(CheckPermissions(fs::owner_read
));
1743 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_write
), NoError
);
1744 EXPECT_TRUE(CheckPermissions(fs::owner_write
));
1746 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_exe
), NoError
);
1747 EXPECT_TRUE(CheckPermissions(fs::owner_exe
));
1749 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_all
), NoError
);
1750 EXPECT_TRUE(CheckPermissions(fs::owner_all
));
1752 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_read
), NoError
);
1753 EXPECT_TRUE(CheckPermissions(fs::group_read
));
1755 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_write
), NoError
);
1756 EXPECT_TRUE(CheckPermissions(fs::group_write
));
1758 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_exe
), NoError
);
1759 EXPECT_TRUE(CheckPermissions(fs::group_exe
));
1761 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_all
), NoError
);
1762 EXPECT_TRUE(CheckPermissions(fs::group_all
));
1764 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_read
), NoError
);
1765 EXPECT_TRUE(CheckPermissions(fs::others_read
));
1767 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_write
), NoError
);
1768 EXPECT_TRUE(CheckPermissions(fs::others_write
));
1770 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_exe
), NoError
);
1771 EXPECT_TRUE(CheckPermissions(fs::others_exe
));
1773 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_all
), NoError
);
1774 EXPECT_TRUE(CheckPermissions(fs::others_all
));
1776 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_read
), NoError
);
1777 EXPECT_TRUE(CheckPermissions(fs::all_read
));
1779 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_write
), NoError
);
1780 EXPECT_TRUE(CheckPermissions(fs::all_write
));
1782 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_exe
), NoError
);
1783 EXPECT_TRUE(CheckPermissions(fs::all_exe
));
1785 EXPECT_EQ(fs::setPermissions(TempPath
, fs::set_uid_on_exe
), NoError
);
1786 EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe
));
1788 EXPECT_EQ(fs::setPermissions(TempPath
, fs::set_gid_on_exe
), NoError
);
1789 EXPECT_TRUE(CheckPermissions(fs::set_gid_on_exe
));
1791 // Modern BSDs require root to set the sticky bit on files.
1792 // AIX and Solaris without root will mask off (i.e., lose) the sticky bit
1794 #if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
1795 !defined(_AIX) && !(defined(__sun__) && defined(__svr4__))
1796 EXPECT_EQ(fs::setPermissions(TempPath
, fs::sticky_bit
), NoError
);
1797 EXPECT_TRUE(CheckPermissions(fs::sticky_bit
));
1799 EXPECT_EQ(fs::setPermissions(TempPath
, fs::set_uid_on_exe
|
1800 fs::set_gid_on_exe
|
1803 EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe
| fs::set_gid_on_exe
|
1806 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_read
| fs::set_uid_on_exe
|
1807 fs::set_gid_on_exe
|
1810 EXPECT_TRUE(CheckPermissions(fs::all_read
| fs::set_uid_on_exe
|
1811 fs::set_gid_on_exe
| fs::sticky_bit
));
1813 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_perms
), NoError
);
1814 EXPECT_TRUE(CheckPermissions(fs::all_perms
));
1815 #endif // !FreeBSD && !NetBSD && !OpenBSD && !AIX
1817 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_perms
& ~fs::sticky_bit
),
1819 EXPECT_TRUE(CheckPermissions(fs::all_perms
& ~fs::sticky_bit
));
1823 } // anonymous namespace