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