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 bool Result = llvm::sys::path::home_directory(HomeDir); 520 if (Result) { 521 ASSERT_NO_ERROR(fs::real_path(HomeDir, Expected)); 522 ASSERT_NO_ERROR(fs::real_path("~", Actual, true)); 523 EXPECT_EQ(Expected, Actual); 524 ASSERT_NO_ERROR(fs::real_path("~/", Actual, true)); 525 EXPECT_EQ(Expected, Actual); 526 } 527 528 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/test1")); 529 } 530 531 #ifdef LLVM_ON_UNIX 532 TEST_F(FileSystemTest, RealPathNoReadPerm) { 533 SmallString<64> Expanded; 534 535 ASSERT_NO_ERROR( 536 fs::create_directories(Twine(TestDirectory) + "/noreadperm")); 537 ASSERT_TRUE(fs::exists(Twine(TestDirectory) + "/noreadperm")); 538 539 fs::setPermissions(Twine(TestDirectory) + "/noreadperm", fs::no_perms); 540 fs::setPermissions(Twine(TestDirectory) + "/noreadperm", fs::all_exe); 541 542 ASSERT_NO_ERROR(fs::real_path(Twine(TestDirectory) + "/noreadperm", Expanded, 543 false)); 544 545 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/noreadperm")); 546 } 547 #endif 548 549 550 TEST_F(FileSystemTest, TempFileKeepDiscard) { 551 // We can keep then discard. 552 auto TempFileOrError = fs::TempFile::create(TestDirectory + "/test-%%%%"); 553 ASSERT_TRUE((bool)TempFileOrError); 554 fs::TempFile File = std::move(*TempFileOrError); 555 ASSERT_FALSE((bool)File.keep(TestDirectory + "/keep")); 556 ASSERT_FALSE((bool)File.discard()); 557 ASSERT_TRUE(fs::exists(TestDirectory + "/keep")); 558 ASSERT_NO_ERROR(fs::remove(TestDirectory + "/keep")); 559 } 560 561 TEST_F(FileSystemTest, TempFileDiscardDiscard) { 562 // We can discard twice. 563 auto TempFileOrError = fs::TempFile::create(TestDirectory + "/test-%%%%"); 564 ASSERT_TRUE((bool)TempFileOrError); 565 fs::TempFile File = std::move(*TempFileOrError); 566 ASSERT_FALSE((bool)File.discard()); 567 ASSERT_FALSE((bool)File.discard()); 568 ASSERT_FALSE(fs::exists(TestDirectory + "/keep")); 569 } 570 571 TEST_F(FileSystemTest, TempFiles) { 572 // Create a temp file. 573 int FileDescriptor; 574 SmallString<64> TempPath; 575 ASSERT_NO_ERROR( 576 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath)); 577 578 // Make sure it exists. 579 ASSERT_TRUE(sys::fs::exists(Twine(TempPath))); 580 581 // Create another temp tile. 582 int FD2; 583 SmallString<64> TempPath2; 584 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD2, TempPath2)); 585 ASSERT_TRUE(TempPath2.endswith(".temp")); 586 ASSERT_NE(TempPath.str(), TempPath2.str()); 587 588 fs::file_status A, B; 589 ASSERT_NO_ERROR(fs::status(Twine(TempPath), A)); 590 ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B)); 591 EXPECT_FALSE(fs::equivalent(A, B)); 592 593 ::close(FD2); 594 595 // Remove Temp2. 596 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2))); 597 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2))); 598 ASSERT_EQ(fs::remove(Twine(TempPath2), false), 599 errc::no_such_file_or_directory); 600 601 std::error_code EC = fs::status(TempPath2.c_str(), B); 602 EXPECT_EQ(EC, errc::no_such_file_or_directory); 603 EXPECT_EQ(B.type(), fs::file_type::file_not_found); 604 605 // Make sure Temp2 doesn't exist. 606 ASSERT_EQ(fs::access(Twine(TempPath2), sys::fs::AccessMode::Exist), 607 errc::no_such_file_or_directory); 608 609 SmallString<64> TempPath3; 610 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "", TempPath3)); 611 ASSERT_FALSE(TempPath3.endswith(".")); 612 FileRemover Cleanup3(TempPath3); 613 614 // Create a hard link to Temp1. 615 ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2))); 616 bool equal; 617 ASSERT_NO_ERROR(fs::equivalent(Twine(TempPath), Twine(TempPath2), equal)); 618 EXPECT_TRUE(equal); 619 ASSERT_NO_ERROR(fs::status(Twine(TempPath), A)); 620 ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B)); 621 EXPECT_TRUE(fs::equivalent(A, B)); 622 623 // Remove Temp1. 624 ::close(FileDescriptor); 625 ASSERT_NO_ERROR(fs::remove(Twine(TempPath))); 626 627 // Remove the hard link. 628 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2))); 629 630 // Make sure Temp1 doesn't exist. 631 ASSERT_EQ(fs::access(Twine(TempPath), sys::fs::AccessMode::Exist), 632 errc::no_such_file_or_directory); 633 634 #ifdef _WIN32 635 // Path name > 260 chars should get an error. 636 const char *Path270 = 637 "abcdefghijklmnopqrstuvwxyz9abcdefghijklmnopqrstuvwxyz8" 638 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6" 639 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4" 640 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2" 641 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0"; 642 EXPECT_EQ(fs::createUniqueFile(Path270, FileDescriptor, TempPath), 643 errc::invalid_argument); 644 // Relative path < 247 chars, no problem. 645 const char *Path216 = 646 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6" 647 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4" 648 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2" 649 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0"; 650 ASSERT_NO_ERROR(fs::createTemporaryFile(Path216, "", TempPath)); 651 ASSERT_NO_ERROR(fs::remove(Twine(TempPath))); 652 #endif 653 } 654 655 TEST_F(FileSystemTest, TempFileCollisions) { 656 SmallString<128> TestDirectory; 657 ASSERT_NO_ERROR( 658 fs::createUniqueDirectory("CreateUniqueFileTest", TestDirectory)); 659 FileRemover Cleanup(TestDirectory); 660 SmallString<128> Model = TestDirectory; 661 path::append(Model, "%.tmp"); 662 SmallString<128> Path; 663 std::vector<fs::TempFile> TempFiles; 664 665 auto TryCreateTempFile = [&]() { 666 Expected<fs::TempFile> T = fs::TempFile::create(Model); 667 if (T) { 668 TempFiles.push_back(std::move(*T)); 669 return true; 670 } else { 671 logAllUnhandledErrors(T.takeError(), errs(), 672 "Failed to create temporary file: "); 673 return false; 674 } 675 }; 676 677 // We should be able to create exactly 16 temporary files. 678 for (int i = 0; i < 16; ++i) 679 EXPECT_TRUE(TryCreateTempFile()); 680 EXPECT_FALSE(TryCreateTempFile()); 681 682 for (fs::TempFile &T : TempFiles) 683 cantFail(T.discard()); 684 } 685 686 TEST_F(FileSystemTest, CreateDir) { 687 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo")); 688 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo")); 689 ASSERT_EQ(fs::create_directory(Twine(TestDirectory) + "foo", false), 690 errc::file_exists); 691 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "foo")); 692 693 #ifdef LLVM_ON_UNIX 694 // Set a 0000 umask so that we can test our directory permissions. 695 mode_t OldUmask = ::umask(0000); 696 697 fs::file_status Status; 698 ASSERT_NO_ERROR( 699 fs::create_directory(Twine(TestDirectory) + "baz500", false, 700 fs::perms::owner_read | fs::perms::owner_exe)); 701 ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz500", Status)); 702 ASSERT_EQ(Status.permissions() & fs::perms::all_all, 703 fs::perms::owner_read | fs::perms::owner_exe); 704 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "baz777", false, 705 fs::perms::all_all)); 706 ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz777", Status)); 707 ASSERT_EQ(Status.permissions() & fs::perms::all_all, fs::perms::all_all); 708 709 // Restore umask to be safe. 710 ::umask(OldUmask); 711 #endif 712 713 #ifdef _WIN32 714 // Prove that create_directories() can handle a pathname > 248 characters, 715 // which is the documented limit for CreateDirectory(). 716 // (248 is MAX_PATH subtracting room for an 8.3 filename.) 717 // Generate a directory path guaranteed to fall into that range. 718 size_t TmpLen = TestDirectory.size(); 719 const char *OneDir = "\\123456789"; 720 size_t OneDirLen = strlen(OneDir); 721 ASSERT_LT(OneDirLen, 12U); 722 size_t NLevels = ((248 - TmpLen) / OneDirLen) + 1; 723 SmallString<260> LongDir(TestDirectory); 724 for (size_t I = 0; I < NLevels; ++I) 725 LongDir.append(OneDir); 726 ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir))); 727 ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir))); 728 ASSERT_EQ(fs::create_directories(Twine(LongDir), false), 729 errc::file_exists); 730 // Tidy up, "recursively" removing the directories. 731 StringRef ThisDir(LongDir); 732 for (size_t J = 0; J < NLevels; ++J) { 733 ASSERT_NO_ERROR(fs::remove(ThisDir)); 734 ThisDir = path::parent_path(ThisDir); 735 } 736 737 // Also verify that paths with Unix separators are handled correctly. 738 std::string LongPathWithUnixSeparators(TestDirectory.str()); 739 // Add at least one subdirectory to TestDirectory, and replace slashes with 740 // backslashes 741 do { 742 LongPathWithUnixSeparators.append("/DirNameWith19Charss"); 743 } while (LongPathWithUnixSeparators.size() < 260); 744 std::replace(LongPathWithUnixSeparators.begin(), 745 LongPathWithUnixSeparators.end(), 746 '\\', '/'); 747 ASSERT_NO_ERROR(fs::create_directories(Twine(LongPathWithUnixSeparators))); 748 // cleanup 749 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + 750 "/DirNameWith19Charss")); 751 752 // Similarly for a relative pathname. Need to set the current directory to 753 // TestDirectory so that the one we create ends up in the right place. 754 char PreviousDir[260]; 755 size_t PreviousDirLen = ::GetCurrentDirectoryA(260, PreviousDir); 756 ASSERT_GT(PreviousDirLen, 0U); 757 ASSERT_LT(PreviousDirLen, 260U); 758 ASSERT_NE(::SetCurrentDirectoryA(TestDirectory.c_str()), 0); 759 LongDir.clear(); 760 // Generate a relative directory name with absolute length > 248. 761 size_t LongDirLen = 249 - TestDirectory.size(); 762 LongDir.assign(LongDirLen, 'a'); 763 ASSERT_NO_ERROR(fs::create_directory(Twine(LongDir))); 764 // While we're here, prove that .. and . handling works in these long paths. 765 const char *DotDotDirs = "\\..\\.\\b"; 766 LongDir.append(DotDotDirs); 767 ASSERT_NO_ERROR(fs::create_directory("b")); 768 ASSERT_EQ(fs::create_directory(Twine(LongDir), false), errc::file_exists); 769 // And clean up. 770 ASSERT_NO_ERROR(fs::remove("b")); 771 ASSERT_NO_ERROR(fs::remove( 772 Twine(LongDir.substr(0, LongDir.size() - strlen(DotDotDirs))))); 773 ASSERT_NE(::SetCurrentDirectoryA(PreviousDir), 0); 774 #endif 775 } 776 777 TEST_F(FileSystemTest, DirectoryIteration) { 778 std::error_code ec; 779 for (fs::directory_iterator i(".", ec), e; i != e; i.increment(ec)) 780 ASSERT_NO_ERROR(ec); 781 782 // Create a known hierarchy to recurse over. 783 ASSERT_NO_ERROR( 784 fs::create_directories(Twine(TestDirectory) + "/recursive/a0/aa1")); 785 ASSERT_NO_ERROR( 786 fs::create_directories(Twine(TestDirectory) + "/recursive/a0/ab1")); 787 ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) + 788 "/recursive/dontlookhere/da1")); 789 ASSERT_NO_ERROR( 790 fs::create_directories(Twine(TestDirectory) + "/recursive/z0/za1")); 791 ASSERT_NO_ERROR( 792 fs::create_directories(Twine(TestDirectory) + "/recursive/pop/p1")); 793 typedef std::vector<std::string> v_t; 794 v_t visited; 795 for (fs::recursive_directory_iterator i(Twine(TestDirectory) 796 + "/recursive", ec), e; i != e; i.increment(ec)){ 797 ASSERT_NO_ERROR(ec); 798 if (path::filename(i->path()) == "p1") { 799 i.pop(); 800 // FIXME: recursive_directory_iterator should be more robust. 801 if (i == e) break; 802 } 803 if (path::filename(i->path()) == "dontlookhere") 804 i.no_push(); 805 visited.push_back(path::filename(i->path())); 806 } 807 v_t::const_iterator a0 = find(visited, "a0"); 808 v_t::const_iterator aa1 = find(visited, "aa1"); 809 v_t::const_iterator ab1 = find(visited, "ab1"); 810 v_t::const_iterator dontlookhere = find(visited, "dontlookhere"); 811 v_t::const_iterator da1 = find(visited, "da1"); 812 v_t::const_iterator z0 = find(visited, "z0"); 813 v_t::const_iterator za1 = find(visited, "za1"); 814 v_t::const_iterator pop = find(visited, "pop"); 815 v_t::const_iterator p1 = find(visited, "p1"); 816 817 // Make sure that each path was visited correctly. 818 ASSERT_NE(a0, visited.end()); 819 ASSERT_NE(aa1, visited.end()); 820 ASSERT_NE(ab1, visited.end()); 821 ASSERT_NE(dontlookhere, visited.end()); 822 ASSERT_EQ(da1, visited.end()); // Not visited. 823 ASSERT_NE(z0, visited.end()); 824 ASSERT_NE(za1, visited.end()); 825 ASSERT_NE(pop, visited.end()); 826 ASSERT_EQ(p1, visited.end()); // Not visited. 827 828 // Make sure that parents were visited before children. No other ordering 829 // guarantees can be made across siblings. 830 ASSERT_LT(a0, aa1); 831 ASSERT_LT(a0, ab1); 832 ASSERT_LT(z0, za1); 833 834 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/aa1")); 835 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/ab1")); 836 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0")); 837 ASSERT_NO_ERROR( 838 fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere/da1")); 839 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere")); 840 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop/p1")); 841 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop")); 842 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0/za1")); 843 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0")); 844 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive")); 845 846 // Test recursive_directory_iterator level() 847 ASSERT_NO_ERROR( 848 fs::create_directories(Twine(TestDirectory) + "/reclevel/a/b/c")); 849 fs::recursive_directory_iterator I(Twine(TestDirectory) + "/reclevel", ec), E; 850 for (int l = 0; I != E; I.increment(ec), ++l) { 851 ASSERT_NO_ERROR(ec); 852 EXPECT_EQ(I.level(), l); 853 } 854 EXPECT_EQ(I, E); 855 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a/b/c")); 856 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a/b")); 857 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a")); 858 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel")); 859 } 860 861 #ifdef LLVM_ON_UNIX 862 TEST_F(FileSystemTest, BrokenSymlinkDirectoryIteration) { 863 // Create a known hierarchy to recurse over. 864 ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) + "/symlink")); 865 ASSERT_NO_ERROR( 866 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/a")); 867 ASSERT_NO_ERROR( 868 fs::create_directories(Twine(TestDirectory) + "/symlink/b/bb")); 869 ASSERT_NO_ERROR( 870 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/b/ba")); 871 ASSERT_NO_ERROR( 872 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/b/bc")); 873 ASSERT_NO_ERROR( 874 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/c")); 875 ASSERT_NO_ERROR( 876 fs::create_directories(Twine(TestDirectory) + "/symlink/d/dd/ddd")); 877 ASSERT_NO_ERROR(fs::create_link(Twine(TestDirectory) + "/symlink/d/dd", 878 Twine(TestDirectory) + "/symlink/d/da")); 879 ASSERT_NO_ERROR( 880 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/e")); 881 882 typedef std::vector<std::string> v_t; 883 v_t VisitedNonBrokenSymlinks; 884 v_t VisitedBrokenSymlinks; 885 std::error_code ec; 886 using testing::UnorderedElementsAre; 887 using testing::UnorderedElementsAreArray; 888 889 // Broken symbol links are expected to throw an error. 890 for (fs::directory_iterator i(Twine(TestDirectory) + "/symlink", ec), e; 891 i != e; i.increment(ec)) { 892 ASSERT_NO_ERROR(ec); 893 if (i->status().getError() == 894 std::make_error_code(std::errc::no_such_file_or_directory)) { 895 VisitedBrokenSymlinks.push_back(path::filename(i->path())); 896 continue; 897 } 898 VisitedNonBrokenSymlinks.push_back(path::filename(i->path())); 899 } 900 EXPECT_THAT(VisitedNonBrokenSymlinks, UnorderedElementsAre("b", "d")); 901 VisitedNonBrokenSymlinks.clear(); 902 903 EXPECT_THAT(VisitedBrokenSymlinks, UnorderedElementsAre("a", "c", "e")); 904 VisitedBrokenSymlinks.clear(); 905 906 // Broken symbol links are expected to throw an error. 907 for (fs::recursive_directory_iterator i( 908 Twine(TestDirectory) + "/symlink", ec), e; i != e; i.increment(ec)) { 909 ASSERT_NO_ERROR(ec); 910 if (i->status().getError() == 911 std::make_error_code(std::errc::no_such_file_or_directory)) { 912 VisitedBrokenSymlinks.push_back(path::filename(i->path())); 913 continue; 914 } 915 VisitedNonBrokenSymlinks.push_back(path::filename(i->path())); 916 } 917 EXPECT_THAT(VisitedNonBrokenSymlinks, 918 UnorderedElementsAre("b", "bb", "d", "da", "dd", "ddd", "ddd")); 919 VisitedNonBrokenSymlinks.clear(); 920 921 EXPECT_THAT(VisitedBrokenSymlinks, 922 UnorderedElementsAre("a", "ba", "bc", "c", "e")); 923 VisitedBrokenSymlinks.clear(); 924 925 for (fs::recursive_directory_iterator i( 926 Twine(TestDirectory) + "/symlink", ec, /*follow_symlinks=*/false), e; 927 i != e; i.increment(ec)) { 928 ASSERT_NO_ERROR(ec); 929 if (i->status().getError() == 930 std::make_error_code(std::errc::no_such_file_or_directory)) { 931 VisitedBrokenSymlinks.push_back(path::filename(i->path())); 932 continue; 933 } 934 VisitedNonBrokenSymlinks.push_back(path::filename(i->path())); 935 } 936 EXPECT_THAT(VisitedNonBrokenSymlinks, 937 UnorderedElementsAreArray({"a", "b", "ba", "bb", "bc", "c", "d", 938 "da", "dd", "ddd", "e"})); 939 VisitedNonBrokenSymlinks.clear(); 940 941 EXPECT_THAT(VisitedBrokenSymlinks, UnorderedElementsAre()); 942 VisitedBrokenSymlinks.clear(); 943 944 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/symlink")); 945 } 946 #endif 947 948 TEST_F(FileSystemTest, Remove) { 949 SmallString<64> BaseDir; 950 SmallString<64> Paths[4]; 951 int fds[4]; 952 ASSERT_NO_ERROR(fs::createUniqueDirectory("fs_remove", BaseDir)); 953 954 ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir) + "/foo/bar/baz")); 955 ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir) + "/foo/bar/buzz")); 956 ASSERT_NO_ERROR(fs::createUniqueFile( 957 Twine(BaseDir) + "/foo/bar/baz/%%%%%%.tmp", fds[0], Paths[0])); 958 ASSERT_NO_ERROR(fs::createUniqueFile( 959 Twine(BaseDir) + "/foo/bar/baz/%%%%%%.tmp", fds[1], Paths[1])); 960 ASSERT_NO_ERROR(fs::createUniqueFile( 961 Twine(BaseDir) + "/foo/bar/buzz/%%%%%%.tmp", fds[2], Paths[2])); 962 ASSERT_NO_ERROR(fs::createUniqueFile( 963 Twine(BaseDir) + "/foo/bar/buzz/%%%%%%.tmp", fds[3], Paths[3])); 964 965 for (int fd : fds) 966 ::close(fd); 967 968 EXPECT_TRUE(fs::exists(Twine(BaseDir) + "/foo/bar/baz")); 969 EXPECT_TRUE(fs::exists(Twine(BaseDir) + "/foo/bar/buzz")); 970 EXPECT_TRUE(fs::exists(Paths[0])); 971 EXPECT_TRUE(fs::exists(Paths[1])); 972 EXPECT_TRUE(fs::exists(Paths[2])); 973 EXPECT_TRUE(fs::exists(Paths[3])); 974 975 ASSERT_NO_ERROR(fs::remove_directories("D:/footest")); 976 977 ASSERT_NO_ERROR(fs::remove_directories(BaseDir)); 978 ASSERT_FALSE(fs::exists(BaseDir)); 979 } 980 981 #ifdef _WIN32 982 TEST_F(FileSystemTest, CarriageReturn) { 983 SmallString<128> FilePathname(TestDirectory); 984 std::error_code EC; 985 path::append(FilePathname, "test"); 986 987 { 988 raw_fd_ostream File(FilePathname, EC, sys::fs::F_Text); 989 ASSERT_NO_ERROR(EC); 990 File << '\n'; 991 } 992 { 993 auto Buf = MemoryBuffer::getFile(FilePathname.str()); 994 EXPECT_TRUE((bool)Buf); 995 EXPECT_EQ(Buf.get()->getBuffer(), "\r\n"); 996 } 997 998 { 999 raw_fd_ostream File(FilePathname, EC, sys::fs::F_None); 1000 ASSERT_NO_ERROR(EC); 1001 File << '\n'; 1002 } 1003 { 1004 auto Buf = MemoryBuffer::getFile(FilePathname.str()); 1005 EXPECT_TRUE((bool)Buf); 1006 EXPECT_EQ(Buf.get()->getBuffer(), "\n"); 1007 } 1008 ASSERT_NO_ERROR(fs::remove(Twine(FilePathname))); 1009 } 1010 #endif 1011 1012 TEST_F(FileSystemTest, Resize) { 1013 int FD; 1014 SmallString<64> TempPath; 1015 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath)); 1016 ASSERT_NO_ERROR(fs::resize_file(FD, 123)); 1017 fs::file_status Status; 1018 ASSERT_NO_ERROR(fs::status(FD, Status)); 1019 ASSERT_EQ(Status.getSize(), 123U); 1020 ::close(FD); 1021 ASSERT_NO_ERROR(fs::remove(TempPath)); 1022 } 1023 1024 TEST_F(FileSystemTest, MD5) { 1025 int FD; 1026 SmallString<64> TempPath; 1027 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath)); 1028 StringRef Data("abcdefghijklmnopqrstuvwxyz"); 1029 ASSERT_EQ(write(FD, Data.data(), Data.size()), static_cast<ssize_t>(Data.size())); 1030 lseek(FD, 0, SEEK_SET); 1031 auto Hash = fs::md5_contents(FD); 1032 ::close(FD); 1033 ASSERT_NO_ERROR(Hash.getError()); 1034 1035 EXPECT_STREQ("c3fcd3d76192e4007dfb496cca67e13b", Hash->digest().c_str()); 1036 } 1037 1038 TEST_F(FileSystemTest, FileMapping) { 1039 // Create a temp file. 1040 int FileDescriptor; 1041 SmallString<64> TempPath; 1042 ASSERT_NO_ERROR( 1043 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath)); 1044 unsigned Size = 4096; 1045 ASSERT_NO_ERROR(fs::resize_file(FileDescriptor, Size)); 1046 1047 // Map in temp file and add some content 1048 std::error_code EC; 1049 StringRef Val("hello there"); 1050 { 1051 fs::mapped_file_region mfr(FileDescriptor, 1052 fs::mapped_file_region::readwrite, Size, 0, EC); 1053 ASSERT_NO_ERROR(EC); 1054 std::copy(Val.begin(), Val.end(), mfr.data()); 1055 // Explicitly add a 0. 1056 mfr.data()[Val.size()] = 0; 1057 // Unmap temp file 1058 } 1059 ASSERT_EQ(close(FileDescriptor), 0); 1060 1061 // Map it back in read-only 1062 { 1063 int FD; 1064 EC = fs::openFileForRead(Twine(TempPath), FD); 1065 ASSERT_NO_ERROR(EC); 1066 fs::mapped_file_region mfr(FD, fs::mapped_file_region::readonly, Size, 0, EC); 1067 ASSERT_NO_ERROR(EC); 1068 1069 // Verify content 1070 EXPECT_EQ(StringRef(mfr.const_data()), Val); 1071 1072 // Unmap temp file 1073 fs::mapped_file_region m(FD, fs::mapped_file_region::readonly, Size, 0, EC); 1074 ASSERT_NO_ERROR(EC); 1075 ASSERT_EQ(close(FD), 0); 1076 } 1077 ASSERT_NO_ERROR(fs::remove(TempPath)); 1078 } 1079 1080 TEST(Support, NormalizePath) { 1081 using TestTuple = std::tuple<const char *, const char *, const char *>; 1082 std::vector<TestTuple> Tests; 1083 Tests.emplace_back("a", "a", "a"); 1084 Tests.emplace_back("a/b", "a\\b", "a/b"); 1085 Tests.emplace_back("a\\b", "a\\b", "a/b"); 1086 Tests.emplace_back("a\\\\b", "a\\\\b", "a\\\\b"); 1087 Tests.emplace_back("\\a", "\\a", "/a"); 1088 Tests.emplace_back("a\\", "a\\", "a/"); 1089 1090 for (auto &T : Tests) { 1091 SmallString<64> Win(std::get<0>(T)); 1092 SmallString<64> Posix(Win); 1093 path::native(Win, path::Style::windows); 1094 path::native(Posix, path::Style::posix); 1095 EXPECT_EQ(std::get<1>(T), Win); 1096 EXPECT_EQ(std::get<2>(T), Posix); 1097 } 1098 1099 #if defined(_WIN32) 1100 SmallString<64> PathHome; 1101 path::home_directory(PathHome); 1102 1103 const char *Path7a = "~/aaa"; 1104 SmallString<64> Path7(Path7a); 1105 path::native(Path7); 1106 EXPECT_TRUE(Path7.endswith("\\aaa")); 1107 EXPECT_TRUE(Path7.startswith(PathHome)); 1108 EXPECT_EQ(Path7.size(), PathHome.size() + strlen(Path7a + 1)); 1109 1110 const char *Path8a = "~"; 1111 SmallString<64> Path8(Path8a); 1112 path::native(Path8); 1113 EXPECT_EQ(Path8, PathHome); 1114 1115 const char *Path9a = "~aaa"; 1116 SmallString<64> Path9(Path9a); 1117 path::native(Path9); 1118 EXPECT_EQ(Path9, "~aaa"); 1119 1120 const char *Path10a = "aaa/~/b"; 1121 SmallString<64> Path10(Path10a); 1122 path::native(Path10); 1123 EXPECT_EQ(Path10, "aaa\\~\\b"); 1124 #endif 1125 } 1126 1127 TEST(Support, RemoveLeadingDotSlash) { 1128 StringRef Path1("././/foolz/wat"); 1129 StringRef Path2("./////"); 1130 1131 Path1 = path::remove_leading_dotslash(Path1); 1132 EXPECT_EQ(Path1, "foolz/wat"); 1133 Path2 = path::remove_leading_dotslash(Path2); 1134 EXPECT_EQ(Path2, ""); 1135 } 1136 1137 static std::string remove_dots(StringRef path, bool remove_dot_dot, 1138 path::Style style) { 1139 SmallString<256> buffer(path); 1140 path::remove_dots(buffer, remove_dot_dot, style); 1141 return buffer.str(); 1142 } 1143 1144 TEST(Support, RemoveDots) { 1145 EXPECT_EQ("foolz\\wat", 1146 remove_dots(".\\.\\\\foolz\\wat", false, path::Style::windows)); 1147 EXPECT_EQ("", remove_dots(".\\\\\\\\\\", false, path::Style::windows)); 1148 1149 EXPECT_EQ("a\\..\\b\\c", 1150 remove_dots(".\\a\\..\\b\\c", false, path::Style::windows)); 1151 EXPECT_EQ("b\\c", remove_dots(".\\a\\..\\b\\c", true, path::Style::windows)); 1152 EXPECT_EQ("c", remove_dots(".\\.\\c", true, path::Style::windows)); 1153 EXPECT_EQ("..\\a\\c", 1154 remove_dots("..\\a\\b\\..\\c", true, path::Style::windows)); 1155 EXPECT_EQ("..\\..\\a\\c", 1156 remove_dots("..\\..\\a\\b\\..\\c", true, path::Style::windows)); 1157 1158 SmallString<64> Path1(".\\.\\c"); 1159 EXPECT_TRUE(path::remove_dots(Path1, true, path::Style::windows)); 1160 EXPECT_EQ("c", Path1); 1161 1162 EXPECT_EQ("foolz/wat", 1163 remove_dots("././/foolz/wat", false, path::Style::posix)); 1164 EXPECT_EQ("", remove_dots("./////", false, path::Style::posix)); 1165 1166 EXPECT_EQ("a/../b/c", remove_dots("./a/../b/c", false, path::Style::posix)); 1167 EXPECT_EQ("b/c", remove_dots("./a/../b/c", true, path::Style::posix)); 1168 EXPECT_EQ("c", remove_dots("././c", true, path::Style::posix)); 1169 EXPECT_EQ("../a/c", remove_dots("../a/b/../c", true, path::Style::posix)); 1170 EXPECT_EQ("../../a/c", 1171 remove_dots("../../a/b/../c", true, path::Style::posix)); 1172 EXPECT_EQ("/a/c", remove_dots("/../../a/c", true, path::Style::posix)); 1173 EXPECT_EQ("/a/c", 1174 remove_dots("/../a/b//../././/c", true, path::Style::posix)); 1175 1176 SmallString<64> Path2("././c"); 1177 EXPECT_TRUE(path::remove_dots(Path2, true, path::Style::posix)); 1178 EXPECT_EQ("c", Path2); 1179 } 1180 1181 TEST(Support, ReplacePathPrefix) { 1182 SmallString<64> Path1("/foo"); 1183 SmallString<64> Path2("/old/foo"); 1184 SmallString<64> OldPrefix("/old"); 1185 SmallString<64> NewPrefix("/new"); 1186 SmallString<64> NewPrefix2("/longernew"); 1187 SmallString<64> EmptyPrefix(""); 1188 1189 SmallString<64> Path = Path1; 1190 path::replace_path_prefix(Path, OldPrefix, NewPrefix); 1191 EXPECT_EQ(Path, "/foo"); 1192 Path = Path2; 1193 path::replace_path_prefix(Path, OldPrefix, NewPrefix); 1194 EXPECT_EQ(Path, "/new/foo"); 1195 Path = Path2; 1196 path::replace_path_prefix(Path, OldPrefix, NewPrefix2); 1197 EXPECT_EQ(Path, "/longernew/foo"); 1198 Path = Path1; 1199 path::replace_path_prefix(Path, EmptyPrefix, NewPrefix); 1200 EXPECT_EQ(Path, "/new/foo"); 1201 Path = Path2; 1202 path::replace_path_prefix(Path, OldPrefix, EmptyPrefix); 1203 EXPECT_EQ(Path, "/foo"); 1204 } 1205 1206 TEST_F(FileSystemTest, OpenFileForRead) { 1207 // Create a temp file. 1208 int FileDescriptor; 1209 SmallString<64> TempPath; 1210 ASSERT_NO_ERROR( 1211 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath)); 1212 FileRemover Cleanup(TempPath); 1213 1214 // Make sure it exists. 1215 ASSERT_TRUE(sys::fs::exists(Twine(TempPath))); 1216 1217 // Open the file for read 1218 int FileDescriptor2; 1219 SmallString<64> ResultPath; 1220 ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath), FileDescriptor2, 1221 fs::OF_None, &ResultPath)) 1222 1223 // If we succeeded, check that the paths are the same (modulo case): 1224 if (!ResultPath.empty()) { 1225 // The paths returned by createTemporaryFile and getPathFromOpenFD 1226 // should reference the same file on disk. 1227 fs::UniqueID D1, D2; 1228 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), D1)); 1229 ASSERT_NO_ERROR(fs::getUniqueID(Twine(ResultPath), D2)); 1230 ASSERT_EQ(D1, D2); 1231 } 1232 ::close(FileDescriptor); 1233 ::close(FileDescriptor2); 1234 1235 #ifdef _WIN32 1236 // Since Windows Vista, file access time is not updated by default. 1237 // This is instead updated manually by openFileForRead. 1238 // https://blogs.technet.microsoft.com/filecab/2006/11/07/disabling-last-access-time-in-windows-vista-to-improve-ntfs-performance/ 1239 // This part of the unit test is Windows specific as the updating of 1240 // access times can be disabled on Linux using /etc/fstab. 1241 1242 // Set access time to UNIX epoch. 1243 ASSERT_NO_ERROR(sys::fs::openFileForWrite(Twine(TempPath), FileDescriptor, 1244 fs::CD_OpenExisting)); 1245 TimePoint<> Epoch(std::chrono::milliseconds(0)); 1246 ASSERT_NO_ERROR(fs::setLastAccessAndModificationTime(FileDescriptor, Epoch)); 1247 ::close(FileDescriptor); 1248 1249 // Open the file and ensure access time is updated, when forced. 1250 ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath), FileDescriptor, 1251 fs::OF_UpdateAtime, &ResultPath)); 1252 1253 sys::fs::file_status Status; 1254 ASSERT_NO_ERROR(sys::fs::status(FileDescriptor, Status)); 1255 auto FileAccessTime = Status.getLastAccessedTime(); 1256 1257 ASSERT_NE(Epoch, FileAccessTime); 1258 ::close(FileDescriptor); 1259 1260 // Ideally this test would include a case when ATime is not forced to update, 1261 // however the expected behaviour will differ depending on the configuration 1262 // of the Windows file system. 1263 #endif 1264 } 1265 1266 static void createFileWithData(const Twine &Path, bool ShouldExistBefore, 1267 fs::CreationDisposition Disp, StringRef Data) { 1268 int FD; 1269 ASSERT_EQ(ShouldExistBefore, fs::exists(Path)); 1270 ASSERT_NO_ERROR(fs::openFileForWrite(Path, FD, Disp)); 1271 FileDescriptorCloser Closer(FD); 1272 ASSERT_TRUE(fs::exists(Path)); 1273 1274 ASSERT_EQ(Data.size(), (size_t)write(FD, Data.data(), Data.size())); 1275 } 1276 1277 static void verifyFileContents(const Twine &Path, StringRef Contents) { 1278 auto Buffer = MemoryBuffer::getFile(Path); 1279 ASSERT_TRUE((bool)Buffer); 1280 StringRef Data = Buffer.get()->getBuffer(); 1281 ASSERT_EQ(Data, Contents); 1282 } 1283 1284 TEST_F(FileSystemTest, CreateNew) { 1285 int FD; 1286 Optional<FileDescriptorCloser> Closer; 1287 1288 // Succeeds if the file does not exist. 1289 ASSERT_FALSE(fs::exists(NonExistantFile)); 1290 ASSERT_NO_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateNew)); 1291 ASSERT_TRUE(fs::exists(NonExistantFile)); 1292 1293 FileRemover Cleanup(NonExistantFile); 1294 Closer.emplace(FD); 1295 1296 // And creates a file of size 0. 1297 sys::fs::file_status Status; 1298 ASSERT_NO_ERROR(sys::fs::status(FD, Status)); 1299 EXPECT_EQ(0ULL, Status.getSize()); 1300 1301 // Close this first, before trying to re-open the file. 1302 Closer.reset(); 1303 1304 // But fails if the file does exist. 1305 ASSERT_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateNew)); 1306 } 1307 1308 TEST_F(FileSystemTest, CreateAlways) { 1309 int FD; 1310 Optional<FileDescriptorCloser> Closer; 1311 1312 // Succeeds if the file does not exist. 1313 ASSERT_FALSE(fs::exists(NonExistantFile)); 1314 ASSERT_NO_ERROR( 1315 fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateAlways)); 1316 1317 Closer.emplace(FD); 1318 1319 ASSERT_TRUE(fs::exists(NonExistantFile)); 1320 1321 FileRemover Cleanup(NonExistantFile); 1322 1323 // And creates a file of size 0. 1324 uint64_t FileSize; 1325 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize)); 1326 ASSERT_EQ(0ULL, FileSize); 1327 1328 // If we write some data to it re-create it with CreateAlways, it succeeds and 1329 // truncates to 0 bytes. 1330 ASSERT_EQ(4, write(FD, "Test", 4)); 1331 1332 Closer.reset(); 1333 1334 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize)); 1335 ASSERT_EQ(4ULL, FileSize); 1336 1337 ASSERT_NO_ERROR( 1338 fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateAlways)); 1339 Closer.emplace(FD); 1340 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize)); 1341 ASSERT_EQ(0ULL, FileSize); 1342 } 1343 1344 TEST_F(FileSystemTest, OpenExisting) { 1345 int FD; 1346 1347 // Fails if the file does not exist. 1348 ASSERT_FALSE(fs::exists(NonExistantFile)); 1349 ASSERT_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_OpenExisting)); 1350 ASSERT_FALSE(fs::exists(NonExistantFile)); 1351 1352 // Make a dummy file now so that we can try again when the file does exist. 1353 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz"); 1354 FileRemover Cleanup(NonExistantFile); 1355 uint64_t FileSize; 1356 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize)); 1357 ASSERT_EQ(4ULL, FileSize); 1358 1359 // If we re-create it with different data, it overwrites rather than 1360 // appending. 1361 createFileWithData(NonExistantFile, true, fs::CD_OpenExisting, "Buzz"); 1362 verifyFileContents(NonExistantFile, "Buzz"); 1363 } 1364 1365 TEST_F(FileSystemTest, OpenAlways) { 1366 // Succeeds if the file does not exist. 1367 createFileWithData(NonExistantFile, false, fs::CD_OpenAlways, "Fizz"); 1368 FileRemover Cleanup(NonExistantFile); 1369 uint64_t FileSize; 1370 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize)); 1371 ASSERT_EQ(4ULL, FileSize); 1372 1373 // Now re-open it and write again, verifying the contents get over-written. 1374 createFileWithData(NonExistantFile, true, fs::CD_OpenAlways, "Bu"); 1375 verifyFileContents(NonExistantFile, "Buzz"); 1376 } 1377 1378 TEST_F(FileSystemTest, AppendSetsCorrectFileOffset) { 1379 fs::CreationDisposition Disps[] = {fs::CD_CreateAlways, fs::CD_OpenAlways, 1380 fs::CD_OpenExisting}; 1381 1382 // Write some data and re-open it with every possible disposition (this is a 1383 // hack that shouldn't work, but is left for compatibility. F_Append 1384 // overrides 1385 // the specified disposition. 1386 for (fs::CreationDisposition Disp : Disps) { 1387 int FD; 1388 Optional<FileDescriptorCloser> Closer; 1389 1390 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz"); 1391 1392 FileRemover Cleanup(NonExistantFile); 1393 1394 uint64_t FileSize; 1395 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize)); 1396 ASSERT_EQ(4ULL, FileSize); 1397 ASSERT_NO_ERROR( 1398 fs::openFileForWrite(NonExistantFile, FD, Disp, fs::OF_Append)); 1399 Closer.emplace(FD); 1400 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize)); 1401 ASSERT_EQ(4ULL, FileSize); 1402 1403 ASSERT_EQ(4, write(FD, "Buzz", 4)); 1404 Closer.reset(); 1405 1406 verifyFileContents(NonExistantFile, "FizzBuzz"); 1407 } 1408 } 1409 1410 static void verifyRead(int FD, StringRef Data, bool ShouldSucceed) { 1411 std::vector<char> Buffer; 1412 Buffer.resize(Data.size()); 1413 int Result = ::read(FD, Buffer.data(), Buffer.size()); 1414 if (ShouldSucceed) { 1415 ASSERT_EQ((size_t)Result, Data.size()); 1416 ASSERT_EQ(Data, StringRef(Buffer.data(), Buffer.size())); 1417 } else { 1418 ASSERT_EQ(-1, Result); 1419 ASSERT_EQ(EBADF, errno); 1420 } 1421 } 1422 1423 static void verifyWrite(int FD, StringRef Data, bool ShouldSucceed) { 1424 int Result = ::write(FD, Data.data(), Data.size()); 1425 if (ShouldSucceed) 1426 ASSERT_EQ((size_t)Result, Data.size()); 1427 else { 1428 ASSERT_EQ(-1, Result); 1429 ASSERT_EQ(EBADF, errno); 1430 } 1431 } 1432 1433 TEST_F(FileSystemTest, ReadOnlyFileCantWrite) { 1434 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz"); 1435 FileRemover Cleanup(NonExistantFile); 1436 1437 int FD; 1438 ASSERT_NO_ERROR(fs::openFileForRead(NonExistantFile, FD)); 1439 FileDescriptorCloser Closer(FD); 1440 1441 verifyWrite(FD, "Buzz", false); 1442 verifyRead(FD, "Fizz", true); 1443 } 1444 1445 TEST_F(FileSystemTest, WriteOnlyFileCantRead) { 1446 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz"); 1447 FileRemover Cleanup(NonExistantFile); 1448 1449 int FD; 1450 ASSERT_NO_ERROR( 1451 fs::openFileForWrite(NonExistantFile, FD, fs::CD_OpenExisting)); 1452 FileDescriptorCloser Closer(FD); 1453 verifyRead(FD, "Fizz", false); 1454 verifyWrite(FD, "Buzz", true); 1455 } 1456 1457 TEST_F(FileSystemTest, ReadWriteFileCanReadOrWrite) { 1458 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz"); 1459 FileRemover Cleanup(NonExistantFile); 1460 1461 int FD; 1462 ASSERT_NO_ERROR(fs::openFileForReadWrite(NonExistantFile, FD, 1463 fs::CD_OpenExisting, fs::OF_None)); 1464 FileDescriptorCloser Closer(FD); 1465 verifyRead(FD, "Fizz", true); 1466 verifyWrite(FD, "Buzz", true); 1467 } 1468 1469 TEST_F(FileSystemTest, set_current_path) { 1470 SmallString<128> path; 1471 1472 ASSERT_NO_ERROR(fs::current_path(path)); 1473 ASSERT_NE(TestDirectory, path); 1474 1475 struct RestorePath { 1476 SmallString<128> path; 1477 RestorePath(const SmallString<128> &path) : path(path) {} 1478 ~RestorePath() { fs::set_current_path(path); } 1479 } restore_path(path); 1480 1481 ASSERT_NO_ERROR(fs::set_current_path(TestDirectory)); 1482 1483 ASSERT_NO_ERROR(fs::current_path(path)); 1484 1485 fs::UniqueID D1, D2; 1486 ASSERT_NO_ERROR(fs::getUniqueID(TestDirectory, D1)); 1487 ASSERT_NO_ERROR(fs::getUniqueID(path, D2)); 1488 ASSERT_EQ(D1, D2) << "D1: " << TestDirectory << "\nD2: " << path; 1489 } 1490 1491 TEST_F(FileSystemTest, permissions) { 1492 int FD; 1493 SmallString<64> TempPath; 1494 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath)); 1495 FileRemover Cleanup(TempPath); 1496 1497 // Make sure it exists. 1498 ASSERT_TRUE(fs::exists(Twine(TempPath))); 1499 1500 auto CheckPermissions = [&](fs::perms Expected) { 1501 ErrorOr<fs::perms> Actual = fs::getPermissions(TempPath); 1502 return Actual && *Actual == Expected; 1503 }; 1504 1505 std::error_code NoError; 1506 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_all), NoError); 1507 EXPECT_TRUE(CheckPermissions(fs::all_all)); 1508 1509 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read | fs::all_exe), NoError); 1510 EXPECT_TRUE(CheckPermissions(fs::all_read | fs::all_exe)); 1511 1512 #if defined(_WIN32) 1513 fs::perms ReadOnly = fs::all_read | fs::all_exe; 1514 EXPECT_EQ(fs::setPermissions(TempPath, fs::no_perms), NoError); 1515 EXPECT_TRUE(CheckPermissions(ReadOnly)); 1516 1517 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_read), NoError); 1518 EXPECT_TRUE(CheckPermissions(ReadOnly)); 1519 1520 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_write), NoError); 1521 EXPECT_TRUE(CheckPermissions(fs::all_all)); 1522 1523 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_exe), NoError); 1524 EXPECT_TRUE(CheckPermissions(ReadOnly)); 1525 1526 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_all), NoError); 1527 EXPECT_TRUE(CheckPermissions(fs::all_all)); 1528 1529 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_read), NoError); 1530 EXPECT_TRUE(CheckPermissions(ReadOnly)); 1531 1532 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_write), NoError); 1533 EXPECT_TRUE(CheckPermissions(fs::all_all)); 1534 1535 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_exe), NoError); 1536 EXPECT_TRUE(CheckPermissions(ReadOnly)); 1537 1538 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_all), NoError); 1539 EXPECT_TRUE(CheckPermissions(fs::all_all)); 1540 1541 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_read), NoError); 1542 EXPECT_TRUE(CheckPermissions(ReadOnly)); 1543 1544 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_write), NoError); 1545 EXPECT_TRUE(CheckPermissions(fs::all_all)); 1546 1547 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_exe), NoError); 1548 EXPECT_TRUE(CheckPermissions(ReadOnly)); 1549 1550 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_all), NoError); 1551 EXPECT_TRUE(CheckPermissions(fs::all_all)); 1552 1553 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read), NoError); 1554 EXPECT_TRUE(CheckPermissions(ReadOnly)); 1555 1556 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_write), NoError); 1557 EXPECT_TRUE(CheckPermissions(fs::all_all)); 1558 1559 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_exe), NoError); 1560 EXPECT_TRUE(CheckPermissions(ReadOnly)); 1561 1562 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe), NoError); 1563 EXPECT_TRUE(CheckPermissions(ReadOnly)); 1564 1565 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_gid_on_exe), NoError); 1566 EXPECT_TRUE(CheckPermissions(ReadOnly)); 1567 1568 EXPECT_EQ(fs::setPermissions(TempPath, fs::sticky_bit), NoError); 1569 EXPECT_TRUE(CheckPermissions(ReadOnly)); 1570 1571 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe | 1572 fs::set_gid_on_exe | 1573 fs::sticky_bit), 1574 NoError); 1575 EXPECT_TRUE(CheckPermissions(ReadOnly)); 1576 1577 EXPECT_EQ(fs::setPermissions(TempPath, ReadOnly | fs::set_uid_on_exe | 1578 fs::set_gid_on_exe | 1579 fs::sticky_bit), 1580 NoError); 1581 EXPECT_TRUE(CheckPermissions(ReadOnly)); 1582 1583 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms), NoError); 1584 EXPECT_TRUE(CheckPermissions(fs::all_all)); 1585 #else 1586 EXPECT_EQ(fs::setPermissions(TempPath, fs::no_perms), NoError); 1587 EXPECT_TRUE(CheckPermissions(fs::no_perms)); 1588 1589 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_read), NoError); 1590 EXPECT_TRUE(CheckPermissions(fs::owner_read)); 1591 1592 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_write), NoError); 1593 EXPECT_TRUE(CheckPermissions(fs::owner_write)); 1594 1595 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_exe), NoError); 1596 EXPECT_TRUE(CheckPermissions(fs::owner_exe)); 1597 1598 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_all), NoError); 1599 EXPECT_TRUE(CheckPermissions(fs::owner_all)); 1600 1601 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_read), NoError); 1602 EXPECT_TRUE(CheckPermissions(fs::group_read)); 1603 1604 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_write), NoError); 1605 EXPECT_TRUE(CheckPermissions(fs::group_write)); 1606 1607 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_exe), NoError); 1608 EXPECT_TRUE(CheckPermissions(fs::group_exe)); 1609 1610 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_all), NoError); 1611 EXPECT_TRUE(CheckPermissions(fs::group_all)); 1612 1613 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_read), NoError); 1614 EXPECT_TRUE(CheckPermissions(fs::others_read)); 1615 1616 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_write), NoError); 1617 EXPECT_TRUE(CheckPermissions(fs::others_write)); 1618 1619 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_exe), NoError); 1620 EXPECT_TRUE(CheckPermissions(fs::others_exe)); 1621 1622 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_all), NoError); 1623 EXPECT_TRUE(CheckPermissions(fs::others_all)); 1624 1625 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read), NoError); 1626 EXPECT_TRUE(CheckPermissions(fs::all_read)); 1627 1628 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_write), NoError); 1629 EXPECT_TRUE(CheckPermissions(fs::all_write)); 1630 1631 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_exe), NoError); 1632 EXPECT_TRUE(CheckPermissions(fs::all_exe)); 1633 1634 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe), NoError); 1635 EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe)); 1636 1637 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_gid_on_exe), NoError); 1638 EXPECT_TRUE(CheckPermissions(fs::set_gid_on_exe)); 1639 1640 // Modern BSDs require root to set the sticky bit on files. 1641 #if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) 1642 EXPECT_EQ(fs::setPermissions(TempPath, fs::sticky_bit), NoError); 1643 EXPECT_TRUE(CheckPermissions(fs::sticky_bit)); 1644 1645 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe | 1646 fs::set_gid_on_exe | 1647 fs::sticky_bit), 1648 NoError); 1649 EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe | fs::set_gid_on_exe | 1650 fs::sticky_bit)); 1651 1652 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read | fs::set_uid_on_exe | 1653 fs::set_gid_on_exe | 1654 fs::sticky_bit), 1655 NoError); 1656 EXPECT_TRUE(CheckPermissions(fs::all_read | fs::set_uid_on_exe | 1657 fs::set_gid_on_exe | fs::sticky_bit)); 1658 1659 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms), NoError); 1660 EXPECT_TRUE(CheckPermissions(fs::all_perms)); 1661 #endif // !FreeBSD && !NetBSD && !OpenBSD 1662 1663 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms & ~fs::sticky_bit), 1664 NoError); 1665 EXPECT_TRUE(CheckPermissions(fs::all_perms & ~fs::sticky_bit)); 1666 #endif 1667 } 1668 1669 } // anonymous namespace 1670