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