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