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