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