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