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_Text); 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, MD5) { 1293 int FD; 1294 SmallString<64> TempPath; 1295 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath)); 1296 StringRef Data("abcdefghijklmnopqrstuvwxyz"); 1297 ASSERT_EQ(write(FD, Data.data(), Data.size()), static_cast<ssize_t>(Data.size())); 1298 lseek(FD, 0, SEEK_SET); 1299 auto Hash = fs::md5_contents(FD); 1300 ::close(FD); 1301 ASSERT_NO_ERROR(Hash.getError()); 1302 1303 EXPECT_STREQ("c3fcd3d76192e4007dfb496cca67e13b", Hash->digest().c_str()); 1304 } 1305 1306 TEST_F(FileSystemTest, FileMapping) { 1307 // Create a temp file. 1308 int FileDescriptor; 1309 SmallString<64> TempPath; 1310 ASSERT_NO_ERROR( 1311 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath)); 1312 unsigned Size = 4096; 1313 ASSERT_NO_ERROR(fs::resize_file(FileDescriptor, Size)); 1314 1315 // Map in temp file and add some content 1316 std::error_code EC; 1317 StringRef Val("hello there"); 1318 { 1319 fs::mapped_file_region mfr(fs::convertFDToNativeFile(FileDescriptor), 1320 fs::mapped_file_region::readwrite, Size, 0, EC); 1321 ASSERT_NO_ERROR(EC); 1322 std::copy(Val.begin(), Val.end(), mfr.data()); 1323 // Explicitly add a 0. 1324 mfr.data()[Val.size()] = 0; 1325 // Unmap temp file 1326 } 1327 ASSERT_EQ(close(FileDescriptor), 0); 1328 1329 // Map it back in read-only 1330 { 1331 int FD; 1332 EC = fs::openFileForRead(Twine(TempPath), FD); 1333 ASSERT_NO_ERROR(EC); 1334 fs::mapped_file_region mfr(fs::convertFDToNativeFile(FD), 1335 fs::mapped_file_region::readonly, Size, 0, EC); 1336 ASSERT_NO_ERROR(EC); 1337 1338 // Verify content 1339 EXPECT_EQ(StringRef(mfr.const_data()), Val); 1340 1341 // Unmap temp file 1342 fs::mapped_file_region m(fs::convertFDToNativeFile(FD), 1343 fs::mapped_file_region::readonly, Size, 0, EC); 1344 ASSERT_NO_ERROR(EC); 1345 ASSERT_EQ(close(FD), 0); 1346 } 1347 ASSERT_NO_ERROR(fs::remove(TempPath)); 1348 } 1349 1350 TEST(Support, NormalizePath) { 1351 // Input, Expected Win, Expected Posix 1352 using TestTuple = std::tuple<const char *, const char *, const char *>; 1353 std::vector<TestTuple> Tests; 1354 Tests.emplace_back("a", "a", "a"); 1355 Tests.emplace_back("a/b", "a\\b", "a/b"); 1356 Tests.emplace_back("a\\b", "a\\b", "a/b"); 1357 Tests.emplace_back("a\\\\b", "a\\\\b", "a//b"); 1358 Tests.emplace_back("\\a", "\\a", "/a"); 1359 Tests.emplace_back("a\\", "a\\", "a/"); 1360 Tests.emplace_back("a\\t", "a\\t", "a/t"); 1361 1362 for (auto &T : Tests) { 1363 SmallString<64> Win(std::get<0>(T)); 1364 SmallString<64> Posix(Win); 1365 path::native(Win, path::Style::windows); 1366 path::native(Posix, path::Style::posix); 1367 EXPECT_EQ(std::get<1>(T), Win); 1368 EXPECT_EQ(std::get<2>(T), Posix); 1369 } 1370 1371 #if defined(_WIN32) 1372 SmallString<64> PathHome; 1373 path::home_directory(PathHome); 1374 1375 const char *Path7a = "~/aaa"; 1376 SmallString<64> Path7(Path7a); 1377 path::native(Path7); 1378 EXPECT_TRUE(Path7.endswith("\\aaa")); 1379 EXPECT_TRUE(Path7.startswith(PathHome)); 1380 EXPECT_EQ(Path7.size(), PathHome.size() + strlen(Path7a + 1)); 1381 1382 const char *Path8a = "~"; 1383 SmallString<64> Path8(Path8a); 1384 path::native(Path8); 1385 EXPECT_EQ(Path8, PathHome); 1386 1387 const char *Path9a = "~aaa"; 1388 SmallString<64> Path9(Path9a); 1389 path::native(Path9); 1390 EXPECT_EQ(Path9, "~aaa"); 1391 1392 const char *Path10a = "aaa/~/b"; 1393 SmallString<64> Path10(Path10a); 1394 path::native(Path10); 1395 EXPECT_EQ(Path10, "aaa\\~\\b"); 1396 #endif 1397 } 1398 1399 TEST(Support, RemoveLeadingDotSlash) { 1400 StringRef Path1("././/foolz/wat"); 1401 StringRef Path2("./////"); 1402 1403 Path1 = path::remove_leading_dotslash(Path1); 1404 EXPECT_EQ(Path1, "foolz/wat"); 1405 Path2 = path::remove_leading_dotslash(Path2); 1406 EXPECT_EQ(Path2, ""); 1407 } 1408 1409 static std::string remove_dots(StringRef path, bool remove_dot_dot, 1410 path::Style style) { 1411 SmallString<256> buffer(path); 1412 path::remove_dots(buffer, remove_dot_dot, style); 1413 return std::string(buffer.str()); 1414 } 1415 1416 TEST(Support, RemoveDots) { 1417 EXPECT_EQ("foolz\\wat", 1418 remove_dots(".\\.\\\\foolz\\wat", false, path::Style::windows)); 1419 EXPECT_EQ("", remove_dots(".\\\\\\\\\\", false, path::Style::windows)); 1420 1421 EXPECT_EQ("a\\..\\b\\c", 1422 remove_dots(".\\a\\..\\b\\c", false, path::Style::windows)); 1423 EXPECT_EQ("b\\c", remove_dots(".\\a\\..\\b\\c", true, path::Style::windows)); 1424 EXPECT_EQ("c", remove_dots(".\\.\\c", true, path::Style::windows)); 1425 EXPECT_EQ("..\\a\\c", 1426 remove_dots("..\\a\\b\\..\\c", true, path::Style::windows)); 1427 EXPECT_EQ("..\\..\\a\\c", 1428 remove_dots("..\\..\\a\\b\\..\\c", true, path::Style::windows)); 1429 EXPECT_EQ("C:\\a\\c", remove_dots("C:\\foo\\bar//..\\..\\a\\c", true, 1430 path::Style::windows)); 1431 1432 // FIXME: These leading forward slashes are emergent behavior. VFS depends on 1433 // this behavior now. 1434 EXPECT_EQ("C:/bar", 1435 remove_dots("C:/foo/../bar", true, path::Style::windows)); 1436 EXPECT_EQ("C:/foo\\bar", 1437 remove_dots("C:/foo/bar", true, path::Style::windows)); 1438 EXPECT_EQ("C:/foo\\bar", 1439 remove_dots("C:/foo\\bar", true, path::Style::windows)); 1440 EXPECT_EQ("/", remove_dots("/", true, path::Style::windows)); 1441 EXPECT_EQ("C:/", remove_dots("C:/", true, path::Style::windows)); 1442 1443 // Some clients of remove_dots expect it to remove trailing slashes. Again, 1444 // this is emergent behavior that VFS relies on, and not inherently part of 1445 // the specification. 1446 EXPECT_EQ("C:\\foo\\bar", 1447 remove_dots("C:\\foo\\bar\\", true, path::Style::windows)); 1448 EXPECT_EQ("/foo/bar", 1449 remove_dots("/foo/bar/", true, path::Style::posix)); 1450 1451 // A double separator is rewritten. 1452 EXPECT_EQ("C:/foo\\bar", remove_dots("C:/foo//bar", true, path::Style::windows)); 1453 1454 SmallString<64> Path1(".\\.\\c"); 1455 EXPECT_TRUE(path::remove_dots(Path1, true, path::Style::windows)); 1456 EXPECT_EQ("c", Path1); 1457 1458 EXPECT_EQ("foolz/wat", 1459 remove_dots("././/foolz/wat", false, path::Style::posix)); 1460 EXPECT_EQ("", remove_dots("./////", false, path::Style::posix)); 1461 1462 EXPECT_EQ("a/../b/c", remove_dots("./a/../b/c", false, path::Style::posix)); 1463 EXPECT_EQ("b/c", remove_dots("./a/../b/c", true, path::Style::posix)); 1464 EXPECT_EQ("c", remove_dots("././c", true, path::Style::posix)); 1465 EXPECT_EQ("../a/c", remove_dots("../a/b/../c", true, path::Style::posix)); 1466 EXPECT_EQ("../../a/c", 1467 remove_dots("../../a/b/../c", true, path::Style::posix)); 1468 EXPECT_EQ("/a/c", remove_dots("/../../a/c", true, path::Style::posix)); 1469 EXPECT_EQ("/a/c", 1470 remove_dots("/../a/b//../././/c", true, path::Style::posix)); 1471 EXPECT_EQ("/", remove_dots("/", true, path::Style::posix)); 1472 1473 // FIXME: Leaving behind this double leading slash seems like a bug. 1474 EXPECT_EQ("//foo/bar", 1475 remove_dots("//foo/bar/", true, path::Style::posix)); 1476 1477 SmallString<64> Path2("././c"); 1478 EXPECT_TRUE(path::remove_dots(Path2, true, path::Style::posix)); 1479 EXPECT_EQ("c", Path2); 1480 } 1481 1482 TEST(Support, ReplacePathPrefix) { 1483 SmallString<64> Path1("/foo"); 1484 SmallString<64> Path2("/old/foo"); 1485 SmallString<64> Path3("/oldnew/foo"); 1486 SmallString<64> Path4("C:\\old/foo\\bar"); 1487 SmallString<64> OldPrefix("/old"); 1488 SmallString<64> OldPrefixSep("/old/"); 1489 SmallString<64> OldPrefixWin("c:/oLD/F"); 1490 SmallString<64> NewPrefix("/new"); 1491 SmallString<64> NewPrefix2("/longernew"); 1492 SmallString<64> EmptyPrefix(""); 1493 bool Found; 1494 1495 SmallString<64> Path = Path1; 1496 Found = path::replace_path_prefix(Path, OldPrefix, NewPrefix); 1497 EXPECT_FALSE(Found); 1498 EXPECT_EQ(Path, "/foo"); 1499 Path = Path2; 1500 Found = path::replace_path_prefix(Path, OldPrefix, NewPrefix); 1501 EXPECT_TRUE(Found); 1502 EXPECT_EQ(Path, "/new/foo"); 1503 Path = Path2; 1504 Found = path::replace_path_prefix(Path, OldPrefix, NewPrefix2); 1505 EXPECT_TRUE(Found); 1506 EXPECT_EQ(Path, "/longernew/foo"); 1507 Path = Path1; 1508 Found = path::replace_path_prefix(Path, EmptyPrefix, NewPrefix); 1509 EXPECT_TRUE(Found); 1510 EXPECT_EQ(Path, "/new/foo"); 1511 Path = Path2; 1512 Found = path::replace_path_prefix(Path, OldPrefix, EmptyPrefix); 1513 EXPECT_TRUE(Found); 1514 EXPECT_EQ(Path, "/foo"); 1515 Path = Path2; 1516 Found = path::replace_path_prefix(Path, OldPrefixSep, EmptyPrefix); 1517 EXPECT_TRUE(Found); 1518 EXPECT_EQ(Path, "foo"); 1519 Path = Path3; 1520 Found = path::replace_path_prefix(Path, OldPrefix, NewPrefix); 1521 EXPECT_TRUE(Found); 1522 EXPECT_EQ(Path, "/newnew/foo"); 1523 Path = Path3; 1524 Found = path::replace_path_prefix(Path, OldPrefix, NewPrefix2); 1525 EXPECT_TRUE(Found); 1526 EXPECT_EQ(Path, "/longernewnew/foo"); 1527 Path = Path1; 1528 Found = path::replace_path_prefix(Path, EmptyPrefix, NewPrefix); 1529 EXPECT_TRUE(Found); 1530 EXPECT_EQ(Path, "/new/foo"); 1531 Path = OldPrefix; 1532 Found = path::replace_path_prefix(Path, OldPrefix, NewPrefix); 1533 EXPECT_TRUE(Found); 1534 EXPECT_EQ(Path, "/new"); 1535 Path = OldPrefixSep; 1536 Found = path::replace_path_prefix(Path, OldPrefix, NewPrefix); 1537 EXPECT_TRUE(Found); 1538 EXPECT_EQ(Path, "/new/"); 1539 Path = OldPrefix; 1540 Found = path::replace_path_prefix(Path, OldPrefixSep, NewPrefix); 1541 EXPECT_FALSE(Found); 1542 EXPECT_EQ(Path, "/old"); 1543 Path = Path4; 1544 Found = path::replace_path_prefix(Path, OldPrefixWin, NewPrefix, 1545 path::Style::windows); 1546 EXPECT_TRUE(Found); 1547 EXPECT_EQ(Path, "/newoo\\bar"); 1548 Path = Path4; 1549 Found = path::replace_path_prefix(Path, OldPrefixWin, NewPrefix, 1550 path::Style::posix); 1551 EXPECT_FALSE(Found); 1552 EXPECT_EQ(Path, "C:\\old/foo\\bar"); 1553 } 1554 1555 TEST_F(FileSystemTest, OpenFileForRead) { 1556 // Create a temp file. 1557 int FileDescriptor; 1558 SmallString<64> TempPath; 1559 ASSERT_NO_ERROR( 1560 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath)); 1561 FileRemover Cleanup(TempPath); 1562 1563 // Make sure it exists. 1564 ASSERT_TRUE(sys::fs::exists(Twine(TempPath))); 1565 1566 // Open the file for read 1567 int FileDescriptor2; 1568 SmallString<64> ResultPath; 1569 ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath), FileDescriptor2, 1570 fs::OF_None, &ResultPath)) 1571 1572 // If we succeeded, check that the paths are the same (modulo case): 1573 if (!ResultPath.empty()) { 1574 // The paths returned by createTemporaryFile and getPathFromOpenFD 1575 // should reference the same file on disk. 1576 fs::UniqueID D1, D2; 1577 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), D1)); 1578 ASSERT_NO_ERROR(fs::getUniqueID(Twine(ResultPath), D2)); 1579 ASSERT_EQ(D1, D2); 1580 } 1581 ::close(FileDescriptor); 1582 ::close(FileDescriptor2); 1583 1584 #ifdef _WIN32 1585 // Since Windows Vista, file access time is not updated by default. 1586 // This is instead updated manually by openFileForRead. 1587 // https://blogs.technet.microsoft.com/filecab/2006/11/07/disabling-last-access-time-in-windows-vista-to-improve-ntfs-performance/ 1588 // This part of the unit test is Windows specific as the updating of 1589 // access times can be disabled on Linux using /etc/fstab. 1590 1591 // Set access time to UNIX epoch. 1592 ASSERT_NO_ERROR(sys::fs::openFileForWrite(Twine(TempPath), FileDescriptor, 1593 fs::CD_OpenExisting)); 1594 TimePoint<> Epoch(std::chrono::milliseconds(0)); 1595 ASSERT_NO_ERROR(fs::setLastAccessAndModificationTime(FileDescriptor, Epoch)); 1596 ::close(FileDescriptor); 1597 1598 // Open the file and ensure access time is updated, when forced. 1599 ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath), FileDescriptor, 1600 fs::OF_UpdateAtime, &ResultPath)); 1601 1602 sys::fs::file_status Status; 1603 ASSERT_NO_ERROR(sys::fs::status(FileDescriptor, Status)); 1604 auto FileAccessTime = Status.getLastAccessedTime(); 1605 1606 ASSERT_NE(Epoch, FileAccessTime); 1607 ::close(FileDescriptor); 1608 1609 // Ideally this test would include a case when ATime is not forced to update, 1610 // however the expected behaviour will differ depending on the configuration 1611 // of the Windows file system. 1612 #endif 1613 } 1614 1615 static void createFileWithData(const Twine &Path, bool ShouldExistBefore, 1616 fs::CreationDisposition Disp, StringRef Data) { 1617 int FD; 1618 ASSERT_EQ(ShouldExistBefore, fs::exists(Path)); 1619 ASSERT_NO_ERROR(fs::openFileForWrite(Path, FD, Disp)); 1620 FileDescriptorCloser Closer(FD); 1621 ASSERT_TRUE(fs::exists(Path)); 1622 1623 ASSERT_EQ(Data.size(), (size_t)write(FD, Data.data(), Data.size())); 1624 } 1625 1626 static void verifyFileContents(const Twine &Path, StringRef Contents) { 1627 auto Buffer = MemoryBuffer::getFile(Path); 1628 ASSERT_TRUE((bool)Buffer); 1629 StringRef Data = Buffer.get()->getBuffer(); 1630 ASSERT_EQ(Data, Contents); 1631 } 1632 1633 TEST_F(FileSystemTest, CreateNew) { 1634 int FD; 1635 Optional<FileDescriptorCloser> Closer; 1636 1637 // Succeeds if the file does not exist. 1638 ASSERT_FALSE(fs::exists(NonExistantFile)); 1639 ASSERT_NO_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateNew)); 1640 ASSERT_TRUE(fs::exists(NonExistantFile)); 1641 1642 FileRemover Cleanup(NonExistantFile); 1643 Closer.emplace(FD); 1644 1645 // And creates a file of size 0. 1646 sys::fs::file_status Status; 1647 ASSERT_NO_ERROR(sys::fs::status(FD, Status)); 1648 EXPECT_EQ(0ULL, Status.getSize()); 1649 1650 // Close this first, before trying to re-open the file. 1651 Closer.reset(); 1652 1653 // But fails if the file does exist. 1654 ASSERT_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateNew)); 1655 } 1656 1657 TEST_F(FileSystemTest, CreateAlways) { 1658 int FD; 1659 Optional<FileDescriptorCloser> Closer; 1660 1661 // Succeeds if the file does not exist. 1662 ASSERT_FALSE(fs::exists(NonExistantFile)); 1663 ASSERT_NO_ERROR( 1664 fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateAlways)); 1665 1666 Closer.emplace(FD); 1667 1668 ASSERT_TRUE(fs::exists(NonExistantFile)); 1669 1670 FileRemover Cleanup(NonExistantFile); 1671 1672 // And creates a file of size 0. 1673 uint64_t FileSize; 1674 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize)); 1675 ASSERT_EQ(0ULL, FileSize); 1676 1677 // If we write some data to it re-create it with CreateAlways, it succeeds and 1678 // truncates to 0 bytes. 1679 ASSERT_EQ(4, write(FD, "Test", 4)); 1680 1681 Closer.reset(); 1682 1683 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize)); 1684 ASSERT_EQ(4ULL, FileSize); 1685 1686 ASSERT_NO_ERROR( 1687 fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateAlways)); 1688 Closer.emplace(FD); 1689 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize)); 1690 ASSERT_EQ(0ULL, FileSize); 1691 } 1692 1693 TEST_F(FileSystemTest, OpenExisting) { 1694 int FD; 1695 1696 // Fails if the file does not exist. 1697 ASSERT_FALSE(fs::exists(NonExistantFile)); 1698 ASSERT_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_OpenExisting)); 1699 ASSERT_FALSE(fs::exists(NonExistantFile)); 1700 1701 // Make a dummy file now so that we can try again when the file does exist. 1702 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz"); 1703 FileRemover Cleanup(NonExistantFile); 1704 uint64_t FileSize; 1705 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize)); 1706 ASSERT_EQ(4ULL, FileSize); 1707 1708 // If we re-create it with different data, it overwrites rather than 1709 // appending. 1710 createFileWithData(NonExistantFile, true, fs::CD_OpenExisting, "Buzz"); 1711 verifyFileContents(NonExistantFile, "Buzz"); 1712 } 1713 1714 TEST_F(FileSystemTest, OpenAlways) { 1715 // Succeeds if the file does not exist. 1716 createFileWithData(NonExistantFile, false, fs::CD_OpenAlways, "Fizz"); 1717 FileRemover Cleanup(NonExistantFile); 1718 uint64_t FileSize; 1719 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize)); 1720 ASSERT_EQ(4ULL, FileSize); 1721 1722 // Now re-open it and write again, verifying the contents get over-written. 1723 createFileWithData(NonExistantFile, true, fs::CD_OpenAlways, "Bu"); 1724 verifyFileContents(NonExistantFile, "Buzz"); 1725 } 1726 1727 TEST_F(FileSystemTest, AppendSetsCorrectFileOffset) { 1728 fs::CreationDisposition Disps[] = {fs::CD_CreateAlways, fs::CD_OpenAlways, 1729 fs::CD_OpenExisting}; 1730 1731 // Write some data and re-open it with every possible disposition (this is a 1732 // hack that shouldn't work, but is left for compatibility. OF_Append 1733 // overrides 1734 // the specified disposition. 1735 for (fs::CreationDisposition Disp : Disps) { 1736 int FD; 1737 Optional<FileDescriptorCloser> Closer; 1738 1739 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz"); 1740 1741 FileRemover Cleanup(NonExistantFile); 1742 1743 uint64_t FileSize; 1744 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize)); 1745 ASSERT_EQ(4ULL, FileSize); 1746 ASSERT_NO_ERROR( 1747 fs::openFileForWrite(NonExistantFile, FD, Disp, fs::OF_Append)); 1748 Closer.emplace(FD); 1749 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize)); 1750 ASSERT_EQ(4ULL, FileSize); 1751 1752 ASSERT_EQ(4, write(FD, "Buzz", 4)); 1753 Closer.reset(); 1754 1755 verifyFileContents(NonExistantFile, "FizzBuzz"); 1756 } 1757 } 1758 1759 static void verifyRead(int FD, StringRef Data, bool ShouldSucceed) { 1760 std::vector<char> Buffer; 1761 Buffer.resize(Data.size()); 1762 int Result = ::read(FD, Buffer.data(), Buffer.size()); 1763 if (ShouldSucceed) { 1764 ASSERT_EQ((size_t)Result, Data.size()); 1765 ASSERT_EQ(Data, StringRef(Buffer.data(), Buffer.size())); 1766 } else { 1767 ASSERT_EQ(-1, Result); 1768 ASSERT_EQ(EBADF, errno); 1769 } 1770 } 1771 1772 static void verifyWrite(int FD, StringRef Data, bool ShouldSucceed) { 1773 int Result = ::write(FD, Data.data(), Data.size()); 1774 if (ShouldSucceed) 1775 ASSERT_EQ((size_t)Result, Data.size()); 1776 else { 1777 ASSERT_EQ(-1, Result); 1778 ASSERT_EQ(EBADF, errno); 1779 } 1780 } 1781 1782 TEST_F(FileSystemTest, ReadOnlyFileCantWrite) { 1783 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz"); 1784 FileRemover Cleanup(NonExistantFile); 1785 1786 int FD; 1787 ASSERT_NO_ERROR(fs::openFileForRead(NonExistantFile, FD)); 1788 FileDescriptorCloser Closer(FD); 1789 1790 verifyWrite(FD, "Buzz", false); 1791 verifyRead(FD, "Fizz", true); 1792 } 1793 1794 TEST_F(FileSystemTest, WriteOnlyFileCantRead) { 1795 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz"); 1796 FileRemover Cleanup(NonExistantFile); 1797 1798 int FD; 1799 ASSERT_NO_ERROR( 1800 fs::openFileForWrite(NonExistantFile, FD, fs::CD_OpenExisting)); 1801 FileDescriptorCloser Closer(FD); 1802 verifyRead(FD, "Fizz", false); 1803 verifyWrite(FD, "Buzz", true); 1804 } 1805 1806 TEST_F(FileSystemTest, ReadWriteFileCanReadOrWrite) { 1807 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz"); 1808 FileRemover Cleanup(NonExistantFile); 1809 1810 int FD; 1811 ASSERT_NO_ERROR(fs::openFileForReadWrite(NonExistantFile, FD, 1812 fs::CD_OpenExisting, fs::OF_None)); 1813 FileDescriptorCloser Closer(FD); 1814 verifyRead(FD, "Fizz", true); 1815 verifyWrite(FD, "Buzz", true); 1816 } 1817 1818 TEST_F(FileSystemTest, readNativeFile) { 1819 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "01234"); 1820 FileRemover Cleanup(NonExistantFile); 1821 const auto &Read = [&](size_t ToRead) -> Expected<std::string> { 1822 std::string Buf(ToRead, '?'); 1823 Expected<fs::file_t> FD = fs::openNativeFileForRead(NonExistantFile); 1824 if (!FD) 1825 return FD.takeError(); 1826 auto Close = make_scope_exit([&] { fs::closeFile(*FD); }); 1827 if (Expected<size_t> BytesRead = fs::readNativeFile( 1828 *FD, makeMutableArrayRef(&*Buf.begin(), Buf.size()))) 1829 return Buf.substr(0, *BytesRead); 1830 else 1831 return BytesRead.takeError(); 1832 }; 1833 EXPECT_THAT_EXPECTED(Read(5), HasValue("01234")); 1834 EXPECT_THAT_EXPECTED(Read(3), HasValue("012")); 1835 EXPECT_THAT_EXPECTED(Read(6), HasValue("01234")); 1836 } 1837 1838 TEST_F(FileSystemTest, readNativeFileSlice) { 1839 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "01234"); 1840 FileRemover Cleanup(NonExistantFile); 1841 Expected<fs::file_t> FD = fs::openNativeFileForRead(NonExistantFile); 1842 ASSERT_THAT_EXPECTED(FD, Succeeded()); 1843 auto Close = make_scope_exit([&] { fs::closeFile(*FD); }); 1844 const auto &Read = [&](size_t Offset, 1845 size_t ToRead) -> Expected<std::string> { 1846 std::string Buf(ToRead, '?'); 1847 if (Expected<size_t> BytesRead = fs::readNativeFileSlice( 1848 *FD, makeMutableArrayRef(&*Buf.begin(), Buf.size()), Offset)) 1849 return Buf.substr(0, *BytesRead); 1850 else 1851 return BytesRead.takeError(); 1852 }; 1853 EXPECT_THAT_EXPECTED(Read(0, 5), HasValue("01234")); 1854 EXPECT_THAT_EXPECTED(Read(0, 3), HasValue("012")); 1855 EXPECT_THAT_EXPECTED(Read(2, 3), HasValue("234")); 1856 EXPECT_THAT_EXPECTED(Read(0, 6), HasValue("01234")); 1857 EXPECT_THAT_EXPECTED(Read(2, 6), HasValue("234")); 1858 EXPECT_THAT_EXPECTED(Read(5, 5), HasValue("")); 1859 } 1860 1861 TEST_F(FileSystemTest, is_local) { 1862 bool TestDirectoryIsLocal; 1863 ASSERT_NO_ERROR(fs::is_local(TestDirectory, TestDirectoryIsLocal)); 1864 EXPECT_EQ(TestDirectoryIsLocal, fs::is_local(TestDirectory)); 1865 1866 int FD; 1867 SmallString<128> TempPath; 1868 ASSERT_NO_ERROR( 1869 fs::createUniqueFile(Twine(TestDirectory) + "/temp", FD, TempPath)); 1870 FileRemover Cleanup(TempPath); 1871 1872 // Make sure it exists. 1873 ASSERT_TRUE(sys::fs::exists(Twine(TempPath))); 1874 1875 bool TempFileIsLocal; 1876 ASSERT_NO_ERROR(fs::is_local(FD, TempFileIsLocal)); 1877 EXPECT_EQ(TempFileIsLocal, fs::is_local(FD)); 1878 ::close(FD); 1879 1880 // Expect that the file and its parent directory are equally local or equally 1881 // remote. 1882 EXPECT_EQ(TestDirectoryIsLocal, TempFileIsLocal); 1883 } 1884 1885 TEST_F(FileSystemTest, getUmask) { 1886 #ifdef _WIN32 1887 EXPECT_EQ(fs::getUmask(), 0U) << "Should always be 0 on Windows."; 1888 #else 1889 unsigned OldMask = ::umask(0022); 1890 unsigned CurrentMask = fs::getUmask(); 1891 EXPECT_EQ(CurrentMask, 0022U) 1892 << "getUmask() didn't return previously set umask()"; 1893 EXPECT_EQ(::umask(OldMask), 0022U) << "getUmask() may have changed umask()"; 1894 #endif 1895 } 1896 1897 TEST_F(FileSystemTest, RespectUmask) { 1898 #ifndef _WIN32 1899 unsigned OldMask = ::umask(0022); 1900 1901 int FD; 1902 SmallString<128> TempPath; 1903 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath)); 1904 1905 fs::perms AllRWE = static_cast<fs::perms>(0777); 1906 1907 ASSERT_NO_ERROR(fs::setPermissions(TempPath, AllRWE)); 1908 1909 ErrorOr<fs::perms> Perms = fs::getPermissions(TempPath); 1910 ASSERT_TRUE(!!Perms); 1911 EXPECT_EQ(Perms.get(), AllRWE) << "Should have ignored umask by default"; 1912 1913 ASSERT_NO_ERROR(fs::setPermissions(TempPath, AllRWE)); 1914 1915 Perms = fs::getPermissions(TempPath); 1916 ASSERT_TRUE(!!Perms); 1917 EXPECT_EQ(Perms.get(), AllRWE) << "Should have ignored umask"; 1918 1919 ASSERT_NO_ERROR( 1920 fs::setPermissions(FD, static_cast<fs::perms>(AllRWE & ~fs::getUmask()))); 1921 Perms = fs::getPermissions(TempPath); 1922 ASSERT_TRUE(!!Perms); 1923 EXPECT_EQ(Perms.get(), static_cast<fs::perms>(0755)) 1924 << "Did not respect umask"; 1925 1926 (void)::umask(0057); 1927 1928 ASSERT_NO_ERROR( 1929 fs::setPermissions(FD, static_cast<fs::perms>(AllRWE & ~fs::getUmask()))); 1930 Perms = fs::getPermissions(TempPath); 1931 ASSERT_TRUE(!!Perms); 1932 EXPECT_EQ(Perms.get(), static_cast<fs::perms>(0720)) 1933 << "Did not respect umask"; 1934 1935 (void)::umask(OldMask); 1936 (void)::close(FD); 1937 #endif 1938 } 1939 1940 TEST_F(FileSystemTest, set_current_path) { 1941 SmallString<128> path; 1942 1943 ASSERT_NO_ERROR(fs::current_path(path)); 1944 ASSERT_NE(TestDirectory, path); 1945 1946 struct RestorePath { 1947 SmallString<128> path; 1948 RestorePath(const SmallString<128> &path) : path(path) {} 1949 ~RestorePath() { fs::set_current_path(path); } 1950 } restore_path(path); 1951 1952 ASSERT_NO_ERROR(fs::set_current_path(TestDirectory)); 1953 1954 ASSERT_NO_ERROR(fs::current_path(path)); 1955 1956 fs::UniqueID D1, D2; 1957 ASSERT_NO_ERROR(fs::getUniqueID(TestDirectory, D1)); 1958 ASSERT_NO_ERROR(fs::getUniqueID(path, D2)); 1959 ASSERT_EQ(D1, D2) << "D1: " << TestDirectory << "\nD2: " << path; 1960 } 1961 1962 TEST_F(FileSystemTest, permissions) { 1963 int FD; 1964 SmallString<64> TempPath; 1965 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath)); 1966 FileRemover Cleanup(TempPath); 1967 1968 // Make sure it exists. 1969 ASSERT_TRUE(fs::exists(Twine(TempPath))); 1970 1971 auto CheckPermissions = [&](fs::perms Expected) { 1972 ErrorOr<fs::perms> Actual = fs::getPermissions(TempPath); 1973 return Actual && *Actual == Expected; 1974 }; 1975 1976 std::error_code NoError; 1977 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_all), NoError); 1978 EXPECT_TRUE(CheckPermissions(fs::all_all)); 1979 1980 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read | fs::all_exe), NoError); 1981 EXPECT_TRUE(CheckPermissions(fs::all_read | fs::all_exe)); 1982 1983 #if defined(_WIN32) 1984 fs::perms ReadOnly = fs::all_read | fs::all_exe; 1985 EXPECT_EQ(fs::setPermissions(TempPath, fs::no_perms), NoError); 1986 EXPECT_TRUE(CheckPermissions(ReadOnly)); 1987 1988 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_read), NoError); 1989 EXPECT_TRUE(CheckPermissions(ReadOnly)); 1990 1991 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_write), NoError); 1992 EXPECT_TRUE(CheckPermissions(fs::all_all)); 1993 1994 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_exe), NoError); 1995 EXPECT_TRUE(CheckPermissions(ReadOnly)); 1996 1997 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_all), NoError); 1998 EXPECT_TRUE(CheckPermissions(fs::all_all)); 1999 2000 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_read), NoError); 2001 EXPECT_TRUE(CheckPermissions(ReadOnly)); 2002 2003 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_write), NoError); 2004 EXPECT_TRUE(CheckPermissions(fs::all_all)); 2005 2006 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_exe), NoError); 2007 EXPECT_TRUE(CheckPermissions(ReadOnly)); 2008 2009 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_all), NoError); 2010 EXPECT_TRUE(CheckPermissions(fs::all_all)); 2011 2012 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_read), NoError); 2013 EXPECT_TRUE(CheckPermissions(ReadOnly)); 2014 2015 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_write), NoError); 2016 EXPECT_TRUE(CheckPermissions(fs::all_all)); 2017 2018 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_exe), NoError); 2019 EXPECT_TRUE(CheckPermissions(ReadOnly)); 2020 2021 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_all), NoError); 2022 EXPECT_TRUE(CheckPermissions(fs::all_all)); 2023 2024 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read), NoError); 2025 EXPECT_TRUE(CheckPermissions(ReadOnly)); 2026 2027 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_write), NoError); 2028 EXPECT_TRUE(CheckPermissions(fs::all_all)); 2029 2030 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_exe), NoError); 2031 EXPECT_TRUE(CheckPermissions(ReadOnly)); 2032 2033 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe), NoError); 2034 EXPECT_TRUE(CheckPermissions(ReadOnly)); 2035 2036 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_gid_on_exe), NoError); 2037 EXPECT_TRUE(CheckPermissions(ReadOnly)); 2038 2039 EXPECT_EQ(fs::setPermissions(TempPath, fs::sticky_bit), NoError); 2040 EXPECT_TRUE(CheckPermissions(ReadOnly)); 2041 2042 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe | 2043 fs::set_gid_on_exe | 2044 fs::sticky_bit), 2045 NoError); 2046 EXPECT_TRUE(CheckPermissions(ReadOnly)); 2047 2048 EXPECT_EQ(fs::setPermissions(TempPath, ReadOnly | fs::set_uid_on_exe | 2049 fs::set_gid_on_exe | 2050 fs::sticky_bit), 2051 NoError); 2052 EXPECT_TRUE(CheckPermissions(ReadOnly)); 2053 2054 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms), NoError); 2055 EXPECT_TRUE(CheckPermissions(fs::all_all)); 2056 #else 2057 EXPECT_EQ(fs::setPermissions(TempPath, fs::no_perms), NoError); 2058 EXPECT_TRUE(CheckPermissions(fs::no_perms)); 2059 2060 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_read), NoError); 2061 EXPECT_TRUE(CheckPermissions(fs::owner_read)); 2062 2063 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_write), NoError); 2064 EXPECT_TRUE(CheckPermissions(fs::owner_write)); 2065 2066 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_exe), NoError); 2067 EXPECT_TRUE(CheckPermissions(fs::owner_exe)); 2068 2069 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_all), NoError); 2070 EXPECT_TRUE(CheckPermissions(fs::owner_all)); 2071 2072 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_read), NoError); 2073 EXPECT_TRUE(CheckPermissions(fs::group_read)); 2074 2075 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_write), NoError); 2076 EXPECT_TRUE(CheckPermissions(fs::group_write)); 2077 2078 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_exe), NoError); 2079 EXPECT_TRUE(CheckPermissions(fs::group_exe)); 2080 2081 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_all), NoError); 2082 EXPECT_TRUE(CheckPermissions(fs::group_all)); 2083 2084 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_read), NoError); 2085 EXPECT_TRUE(CheckPermissions(fs::others_read)); 2086 2087 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_write), NoError); 2088 EXPECT_TRUE(CheckPermissions(fs::others_write)); 2089 2090 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_exe), NoError); 2091 EXPECT_TRUE(CheckPermissions(fs::others_exe)); 2092 2093 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_all), NoError); 2094 EXPECT_TRUE(CheckPermissions(fs::others_all)); 2095 2096 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read), NoError); 2097 EXPECT_TRUE(CheckPermissions(fs::all_read)); 2098 2099 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_write), NoError); 2100 EXPECT_TRUE(CheckPermissions(fs::all_write)); 2101 2102 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_exe), NoError); 2103 EXPECT_TRUE(CheckPermissions(fs::all_exe)); 2104 2105 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe), NoError); 2106 EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe)); 2107 2108 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_gid_on_exe), NoError); 2109 EXPECT_TRUE(CheckPermissions(fs::set_gid_on_exe)); 2110 2111 // Modern BSDs require root to set the sticky bit on files. 2112 // AIX and Solaris without root will mask off (i.e., lose) the sticky bit 2113 // on files. 2114 #if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \ 2115 !defined(_AIX) && !(defined(__sun__) && defined(__svr4__)) 2116 EXPECT_EQ(fs::setPermissions(TempPath, fs::sticky_bit), NoError); 2117 EXPECT_TRUE(CheckPermissions(fs::sticky_bit)); 2118 2119 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe | 2120 fs::set_gid_on_exe | 2121 fs::sticky_bit), 2122 NoError); 2123 EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe | fs::set_gid_on_exe | 2124 fs::sticky_bit)); 2125 2126 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read | fs::set_uid_on_exe | 2127 fs::set_gid_on_exe | 2128 fs::sticky_bit), 2129 NoError); 2130 EXPECT_TRUE(CheckPermissions(fs::all_read | fs::set_uid_on_exe | 2131 fs::set_gid_on_exe | fs::sticky_bit)); 2132 2133 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms), NoError); 2134 EXPECT_TRUE(CheckPermissions(fs::all_perms)); 2135 #endif // !FreeBSD && !NetBSD && !OpenBSD && !AIX 2136 2137 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms & ~fs::sticky_bit), 2138 NoError); 2139 EXPECT_TRUE(CheckPermissions(fs::all_perms & ~fs::sticky_bit)); 2140 #endif 2141 } 2142 2143 #ifdef _WIN32 2144 TEST_F(FileSystemTest, widenPath) { 2145 const std::wstring LongPathPrefix(L"\\\\?\\"); 2146 2147 // Test that the length limit is checked against the UTF-16 length and not the 2148 // UTF-8 length. 2149 std::string Input("C:\\foldername\\"); 2150 const std::string Pi("\xcf\x80"); // UTF-8 lower case pi. 2151 // Add Pi up to the MAX_PATH limit. 2152 const size_t NumChars = MAX_PATH - Input.size() - 1; 2153 for (size_t i = 0; i < NumChars; ++i) 2154 Input += Pi; 2155 // Check that UTF-8 length already exceeds MAX_PATH. 2156 EXPECT_TRUE(Input.size() > MAX_PATH); 2157 SmallVector<wchar_t, MAX_PATH + 16> Result; 2158 ASSERT_NO_ERROR(windows::widenPath(Input, Result)); 2159 // Result should not start with the long path prefix. 2160 EXPECT_TRUE(std::wmemcmp(Result.data(), LongPathPrefix.c_str(), 2161 LongPathPrefix.size()) != 0); 2162 EXPECT_EQ(Result.size(), (size_t)MAX_PATH - 1); 2163 2164 // Add another Pi to exceed the MAX_PATH limit. 2165 Input += Pi; 2166 // Construct the expected result. 2167 SmallVector<wchar_t, MAX_PATH + 16> Expected; 2168 ASSERT_NO_ERROR(windows::UTF8ToUTF16(Input, Expected)); 2169 Expected.insert(Expected.begin(), LongPathPrefix.begin(), 2170 LongPathPrefix.end()); 2171 2172 ASSERT_NO_ERROR(windows::widenPath(Input, Result)); 2173 EXPECT_EQ(Result, Expected); 2174 2175 // Test that UNC paths are handled correctly. 2176 const std::string ShareName("\\\\sharename\\"); 2177 const std::string FileName("\\filename"); 2178 // Initialize directory name so that the input is within the MAX_PATH limit. 2179 const char DirChar = 'x'; 2180 std::string DirName(MAX_PATH - ShareName.size() - FileName.size() - 1, 2181 DirChar); 2182 2183 Input = ShareName + DirName + FileName; 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 // Extend the directory name so the input exceeds the MAX_PATH limit. 2191 DirName += DirChar; 2192 Input = ShareName + DirName + FileName; 2193 // Construct the expected result. 2194 ASSERT_NO_ERROR(windows::UTF8ToUTF16(StringRef(Input).substr(2), Expected)); 2195 const std::wstring UNCPrefix(LongPathPrefix + L"UNC\\"); 2196 Expected.insert(Expected.begin(), UNCPrefix.begin(), UNCPrefix.end()); 2197 2198 ASSERT_NO_ERROR(windows::widenPath(Input, Result)); 2199 EXPECT_EQ(Result, Expected); 2200 2201 // Check that Unix separators are handled correctly. 2202 std::replace(Input.begin(), Input.end(), '\\', '/'); 2203 ASSERT_NO_ERROR(windows::widenPath(Input, Result)); 2204 EXPECT_EQ(Result, Expected); 2205 2206 // Check the removal of "dots". 2207 Input = ShareName + DirName + "\\.\\foo\\.\\.." + FileName; 2208 ASSERT_NO_ERROR(windows::widenPath(Input, Result)); 2209 EXPECT_EQ(Result, Expected); 2210 } 2211 #endif 2212 2213 #ifdef _WIN32 2214 // Windows refuses lock request if file region is already locked by the same 2215 // process. POSIX system in this case updates the existing lock. 2216 TEST_F(FileSystemTest, FileLocker) { 2217 using namespace std::chrono; 2218 int FD; 2219 std::error_code EC; 2220 SmallString<64> TempPath; 2221 EC = fs::createTemporaryFile("test", "temp", FD, TempPath); 2222 ASSERT_NO_ERROR(EC); 2223 FileRemover Cleanup(TempPath); 2224 raw_fd_ostream Stream(TempPath, EC); 2225 2226 EC = fs::tryLockFile(FD); 2227 ASSERT_NO_ERROR(EC); 2228 EC = fs::unlockFile(FD); 2229 ASSERT_NO_ERROR(EC); 2230 2231 if (auto L = Stream.lock()) { 2232 ASSERT_ERROR(fs::tryLockFile(FD)); 2233 ASSERT_NO_ERROR(L->unlock()); 2234 ASSERT_NO_ERROR(fs::tryLockFile(FD)); 2235 ASSERT_NO_ERROR(fs::unlockFile(FD)); 2236 } else { 2237 ADD_FAILURE(); 2238 handleAllErrors(L.takeError(), [&](ErrorInfoBase &EIB) {}); 2239 } 2240 2241 ASSERT_NO_ERROR(fs::tryLockFile(FD)); 2242 ASSERT_NO_ERROR(fs::unlockFile(FD)); 2243 2244 { 2245 Expected<fs::FileLocker> L1 = Stream.lock(); 2246 ASSERT_THAT_EXPECTED(L1, Succeeded()); 2247 raw_fd_ostream Stream2(FD, false); 2248 Expected<fs::FileLocker> L2 = Stream2.tryLockFor(250ms); 2249 ASSERT_THAT_EXPECTED(L2, Failed()); 2250 ASSERT_NO_ERROR(L1->unlock()); 2251 Expected<fs::FileLocker> L3 = Stream.tryLockFor(0ms); 2252 ASSERT_THAT_EXPECTED(L3, Succeeded()); 2253 } 2254 2255 ASSERT_NO_ERROR(fs::tryLockFile(FD)); 2256 ASSERT_NO_ERROR(fs::unlockFile(FD)); 2257 } 2258 #endif 2259 2260 } // anonymous namespace 2261