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