1 //===--------------------- filesystem/ops.cpp -----------------------------===// 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 "filesystem" 10 #include "array" 11 #include "iterator" 12 #include "string_view" 13 #include "type_traits" 14 #include "vector" 15 #include "cstdlib" 16 #include "climits" 17 18 #include "filesystem_common.h" 19 20 #include "posix_compat.h" 21 22 #if defined(_LIBCPP_WIN32API) 23 # define WIN32_LEAN_AND_MEAN 24 # define NOMINMAX 25 # include <windows.h> 26 #else 27 # include <unistd.h> 28 # include <sys/stat.h> 29 # include <sys/statvfs.h> 30 #endif 31 #include <time.h> 32 #include <fcntl.h> /* values for fchmodat */ 33 34 #if __has_include(<sys/sendfile.h>) 35 # include <sys/sendfile.h> 36 # define _LIBCPP_FILESYSTEM_USE_SENDFILE 37 #elif defined(__APPLE__) || __has_include(<copyfile.h>) 38 # include <copyfile.h> 39 # define _LIBCPP_FILESYSTEM_USE_COPYFILE 40 #else 41 # include "fstream" 42 # define _LIBCPP_FILESYSTEM_USE_FSTREAM 43 #endif 44 45 #if !defined(CLOCK_REALTIME) && !defined(_LIBCPP_WIN32API) 46 # include <sys/time.h> // for gettimeofday and timeval 47 #endif 48 49 #if defined(__ELF__) && defined(_LIBCPP_LINK_RT_LIB) 50 # pragma comment(lib, "rt") 51 #endif 52 53 _LIBCPP_BEGIN_NAMESPACE_FILESYSTEM 54 55 namespace { 56 57 bool isSeparator(path::value_type C) { 58 if (C == '/') 59 return true; 60 #if defined(_LIBCPP_WIN32API) 61 if (C == '\\') 62 return true; 63 #endif 64 return false; 65 } 66 67 bool isDriveLetter(path::value_type C) { 68 return (C >= 'a' && C <= 'z') || (C >= 'A' && C <= 'Z'); 69 } 70 71 namespace parser { 72 73 using string_view_t = path::__string_view; 74 using string_view_pair = pair<string_view_t, string_view_t>; 75 using PosPtr = path::value_type const*; 76 77 struct PathParser { 78 enum ParserState : unsigned char { 79 // Zero is a special sentinel value used by default constructed iterators. 80 PS_BeforeBegin = path::iterator::_BeforeBegin, 81 PS_InRootName = path::iterator::_InRootName, 82 PS_InRootDir = path::iterator::_InRootDir, 83 PS_InFilenames = path::iterator::_InFilenames, 84 PS_InTrailingSep = path::iterator::_InTrailingSep, 85 PS_AtEnd = path::iterator::_AtEnd 86 }; 87 88 const string_view_t Path; 89 string_view_t RawEntry; 90 ParserState State; 91 92 private: 93 PathParser(string_view_t P, ParserState State) noexcept : Path(P), 94 State(State) {} 95 96 public: 97 PathParser(string_view_t P, string_view_t E, unsigned char S) 98 : Path(P), RawEntry(E), State(static_cast<ParserState>(S)) { 99 // S cannot be '0' or PS_BeforeBegin. 100 } 101 102 static PathParser CreateBegin(string_view_t P) noexcept { 103 PathParser PP(P, PS_BeforeBegin); 104 PP.increment(); 105 return PP; 106 } 107 108 static PathParser CreateEnd(string_view_t P) noexcept { 109 PathParser PP(P, PS_AtEnd); 110 return PP; 111 } 112 113 PosPtr peek() const noexcept { 114 auto TkEnd = getNextTokenStartPos(); 115 auto End = getAfterBack(); 116 return TkEnd == End ? nullptr : TkEnd; 117 } 118 119 void increment() noexcept { 120 const PosPtr End = getAfterBack(); 121 const PosPtr Start = getNextTokenStartPos(); 122 if (Start == End) 123 return makeState(PS_AtEnd); 124 125 switch (State) { 126 case PS_BeforeBegin: { 127 PosPtr TkEnd = consumeRootName(Start, End); 128 if (TkEnd) 129 return makeState(PS_InRootName, Start, TkEnd); 130 } 131 _LIBCPP_FALLTHROUGH(); 132 case PS_InRootName: { 133 PosPtr TkEnd = consumeAllSeparators(Start, End); 134 if (TkEnd) 135 return makeState(PS_InRootDir, Start, TkEnd); 136 else 137 return makeState(PS_InFilenames, Start, consumeName(Start, End)); 138 } 139 case PS_InRootDir: 140 return makeState(PS_InFilenames, Start, consumeName(Start, End)); 141 142 case PS_InFilenames: { 143 PosPtr SepEnd = consumeAllSeparators(Start, End); 144 if (SepEnd != End) { 145 PosPtr TkEnd = consumeName(SepEnd, End); 146 if (TkEnd) 147 return makeState(PS_InFilenames, SepEnd, TkEnd); 148 } 149 return makeState(PS_InTrailingSep, Start, SepEnd); 150 } 151 152 case PS_InTrailingSep: 153 return makeState(PS_AtEnd); 154 155 case PS_AtEnd: 156 _LIBCPP_UNREACHABLE(); 157 } 158 } 159 160 void decrement() noexcept { 161 const PosPtr REnd = getBeforeFront(); 162 const PosPtr RStart = getCurrentTokenStartPos() - 1; 163 if (RStart == REnd) // we're decrementing the begin 164 return makeState(PS_BeforeBegin); 165 166 switch (State) { 167 case PS_AtEnd: { 168 // Try to consume a trailing separator or root directory first. 169 if (PosPtr SepEnd = consumeAllSeparators(RStart, REnd)) { 170 if (SepEnd == REnd) 171 return makeState(PS_InRootDir, Path.data(), RStart + 1); 172 PosPtr TkStart = consumeRootName(SepEnd, REnd); 173 if (TkStart == REnd) 174 return makeState(PS_InRootDir, RStart, RStart + 1); 175 return makeState(PS_InTrailingSep, SepEnd + 1, RStart + 1); 176 } else { 177 PosPtr TkStart = consumeRootName(RStart, REnd); 178 if (TkStart == REnd) 179 return makeState(PS_InRootName, TkStart + 1, RStart + 1); 180 TkStart = consumeName(RStart, REnd); 181 return makeState(PS_InFilenames, TkStart + 1, RStart + 1); 182 } 183 } 184 case PS_InTrailingSep: 185 return makeState(PS_InFilenames, consumeName(RStart, REnd) + 1, 186 RStart + 1); 187 case PS_InFilenames: { 188 PosPtr SepEnd = consumeAllSeparators(RStart, REnd); 189 if (SepEnd == REnd) 190 return makeState(PS_InRootDir, Path.data(), RStart + 1); 191 PosPtr TkStart = consumeRootName(SepEnd ? SepEnd : RStart, REnd); 192 if (TkStart == REnd) { 193 if (SepEnd) 194 return makeState(PS_InRootDir, SepEnd + 1, RStart + 1); 195 return makeState(PS_InRootName, TkStart + 1, RStart + 1); 196 } 197 TkStart = consumeName(SepEnd, REnd); 198 return makeState(PS_InFilenames, TkStart + 1, SepEnd + 1); 199 } 200 case PS_InRootDir: 201 return makeState(PS_InRootName, Path.data(), RStart + 1); 202 case PS_InRootName: 203 case PS_BeforeBegin: 204 _LIBCPP_UNREACHABLE(); 205 } 206 } 207 208 /// \brief Return a view with the "preferred representation" of the current 209 /// element. For example trailing separators are represented as a '.' 210 string_view_t operator*() const noexcept { 211 switch (State) { 212 case PS_BeforeBegin: 213 case PS_AtEnd: 214 return PS(""); 215 case PS_InRootDir: 216 if (RawEntry[0] == '\\') 217 return PS("\\"); 218 else 219 return PS("/"); 220 case PS_InTrailingSep: 221 return PS(""); 222 case PS_InRootName: 223 case PS_InFilenames: 224 return RawEntry; 225 } 226 _LIBCPP_UNREACHABLE(); 227 } 228 229 explicit operator bool() const noexcept { 230 return State != PS_BeforeBegin && State != PS_AtEnd; 231 } 232 233 PathParser& operator++() noexcept { 234 increment(); 235 return *this; 236 } 237 238 PathParser& operator--() noexcept { 239 decrement(); 240 return *this; 241 } 242 243 bool atEnd() const noexcept { 244 return State == PS_AtEnd; 245 } 246 247 bool inRootDir() const noexcept { 248 return State == PS_InRootDir; 249 } 250 251 bool inRootName() const noexcept { 252 return State == PS_InRootName; 253 } 254 255 bool inRootPath() const noexcept { 256 return inRootName() || inRootDir(); 257 } 258 259 private: 260 void makeState(ParserState NewState, PosPtr Start, PosPtr End) noexcept { 261 State = NewState; 262 RawEntry = string_view_t(Start, End - Start); 263 } 264 void makeState(ParserState NewState) noexcept { 265 State = NewState; 266 RawEntry = {}; 267 } 268 269 PosPtr getAfterBack() const noexcept { return Path.data() + Path.size(); } 270 271 PosPtr getBeforeFront() const noexcept { return Path.data() - 1; } 272 273 /// \brief Return a pointer to the first character after the currently 274 /// lexed element. 275 PosPtr getNextTokenStartPos() const noexcept { 276 switch (State) { 277 case PS_BeforeBegin: 278 return Path.data(); 279 case PS_InRootName: 280 case PS_InRootDir: 281 case PS_InFilenames: 282 return &RawEntry.back() + 1; 283 case PS_InTrailingSep: 284 case PS_AtEnd: 285 return getAfterBack(); 286 } 287 _LIBCPP_UNREACHABLE(); 288 } 289 290 /// \brief Return a pointer to the first character in the currently lexed 291 /// element. 292 PosPtr getCurrentTokenStartPos() const noexcept { 293 switch (State) { 294 case PS_BeforeBegin: 295 case PS_InRootName: 296 return &Path.front(); 297 case PS_InRootDir: 298 case PS_InFilenames: 299 case PS_InTrailingSep: 300 return &RawEntry.front(); 301 case PS_AtEnd: 302 return &Path.back() + 1; 303 } 304 _LIBCPP_UNREACHABLE(); 305 } 306 307 // Consume all consecutive separators. 308 PosPtr consumeAllSeparators(PosPtr P, PosPtr End) const noexcept { 309 if (P == nullptr || P == End || !isSeparator(*P)) 310 return nullptr; 311 const int Inc = P < End ? 1 : -1; 312 P += Inc; 313 while (P != End && isSeparator(*P)) 314 P += Inc; 315 return P; 316 } 317 318 // Consume exactly N separators, or return nullptr. 319 PosPtr consumeNSeparators(PosPtr P, PosPtr End, int N) const noexcept { 320 PosPtr Ret = consumeAllSeparators(P, End); 321 if (Ret == nullptr) 322 return nullptr; 323 if (P < End) { 324 if (Ret == P + N) 325 return Ret; 326 } else { 327 if (Ret == P - N) 328 return Ret; 329 } 330 return nullptr; 331 } 332 333 PosPtr consumeName(PosPtr P, PosPtr End) const noexcept { 334 PosPtr Start = P; 335 if (P == nullptr || P == End || isSeparator(*P)) 336 return nullptr; 337 const int Inc = P < End ? 1 : -1; 338 P += Inc; 339 while (P != End && !isSeparator(*P)) 340 P += Inc; 341 if (P == End && Inc < 0) { 342 // Iterating backwards and consumed all the rest of the input. 343 // Check if the start of the string would have been considered 344 // a root name. 345 PosPtr RootEnd = consumeRootName(End + 1, Start); 346 if (RootEnd) 347 return RootEnd - 1; 348 } 349 return P; 350 } 351 352 PosPtr consumeDriveLetter(PosPtr P, PosPtr End) const noexcept { 353 if (P == End) 354 return nullptr; 355 if (P < End) { 356 if (P + 1 == End || !isDriveLetter(P[0]) || P[1] != ':') 357 return nullptr; 358 return P + 2; 359 } else { 360 if (P - 1 == End || !isDriveLetter(P[-1]) || P[0] != ':') 361 return nullptr; 362 return P - 2; 363 } 364 } 365 366 PosPtr consumeNetworkRoot(PosPtr P, PosPtr End) const noexcept { 367 if (P == End) 368 return nullptr; 369 if (P < End) 370 return consumeName(consumeNSeparators(P, End, 2), End); 371 else 372 return consumeNSeparators(consumeName(P, End), End, 2); 373 } 374 375 PosPtr consumeRootName(PosPtr P, PosPtr End) const noexcept { 376 #if defined(_LIBCPP_WIN32API) 377 if (PosPtr Ret = consumeDriveLetter(P, End)) 378 return Ret; 379 if (PosPtr Ret = consumeNetworkRoot(P, End)) 380 return Ret; 381 #endif 382 return nullptr; 383 } 384 }; 385 386 string_view_pair separate_filename(string_view_t const& s) { 387 if (s == PS(".") || s == PS("..") || s.empty()) 388 return string_view_pair{s, PS("")}; 389 auto pos = s.find_last_of('.'); 390 if (pos == string_view_t::npos || pos == 0) 391 return string_view_pair{s, string_view_t{}}; 392 return string_view_pair{s.substr(0, pos), s.substr(pos)}; 393 } 394 395 string_view_t createView(PosPtr S, PosPtr E) noexcept { 396 return {S, static_cast<size_t>(E - S) + 1}; 397 } 398 399 } // namespace parser 400 } // namespace 401 402 // POSIX HELPERS 403 404 #if defined(_LIBCPP_WIN32API) 405 namespace detail { 406 407 errc __win_err_to_errc(int err) { 408 constexpr struct { 409 DWORD win; 410 errc errc; 411 } win_error_mapping[] = { 412 {ERROR_ACCESS_DENIED, errc::permission_denied}, 413 {ERROR_ALREADY_EXISTS, errc::file_exists}, 414 {ERROR_BAD_NETPATH, errc::no_such_file_or_directory}, 415 {ERROR_BAD_UNIT, errc::no_such_device}, 416 {ERROR_BROKEN_PIPE, errc::broken_pipe}, 417 {ERROR_BUFFER_OVERFLOW, errc::filename_too_long}, 418 {ERROR_BUSY, errc::device_or_resource_busy}, 419 {ERROR_BUSY_DRIVE, errc::device_or_resource_busy}, 420 {ERROR_CANNOT_MAKE, errc::permission_denied}, 421 {ERROR_CANTOPEN, errc::io_error}, 422 {ERROR_CANTREAD, errc::io_error}, 423 {ERROR_CANTWRITE, errc::io_error}, 424 {ERROR_CURRENT_DIRECTORY, errc::permission_denied}, 425 {ERROR_DEV_NOT_EXIST, errc::no_such_device}, 426 {ERROR_DEVICE_IN_USE, errc::device_or_resource_busy}, 427 {ERROR_DIR_NOT_EMPTY, errc::directory_not_empty}, 428 {ERROR_DIRECTORY, errc::invalid_argument}, 429 {ERROR_DISK_FULL, errc::no_space_on_device}, 430 {ERROR_FILE_EXISTS, errc::file_exists}, 431 {ERROR_FILE_NOT_FOUND, errc::no_such_file_or_directory}, 432 {ERROR_HANDLE_DISK_FULL, errc::no_space_on_device}, 433 {ERROR_INVALID_ACCESS, errc::permission_denied}, 434 {ERROR_INVALID_DRIVE, errc::no_such_device}, 435 {ERROR_INVALID_FUNCTION, errc::function_not_supported}, 436 {ERROR_INVALID_HANDLE, errc::invalid_argument}, 437 {ERROR_INVALID_NAME, errc::no_such_file_or_directory}, 438 {ERROR_INVALID_PARAMETER, errc::invalid_argument}, 439 {ERROR_LOCK_VIOLATION, errc::no_lock_available}, 440 {ERROR_LOCKED, errc::no_lock_available}, 441 {ERROR_NEGATIVE_SEEK, errc::invalid_argument}, 442 {ERROR_NOACCESS, errc::permission_denied}, 443 {ERROR_NOT_ENOUGH_MEMORY, errc::not_enough_memory}, 444 {ERROR_NOT_READY, errc::resource_unavailable_try_again}, 445 {ERROR_NOT_SAME_DEVICE, errc::cross_device_link}, 446 {ERROR_NOT_SUPPORTED, errc::not_supported}, 447 {ERROR_OPEN_FAILED, errc::io_error}, 448 {ERROR_OPEN_FILES, errc::device_or_resource_busy}, 449 {ERROR_OPERATION_ABORTED, errc::operation_canceled}, 450 {ERROR_OUTOFMEMORY, errc::not_enough_memory}, 451 {ERROR_PATH_NOT_FOUND, errc::no_such_file_or_directory}, 452 {ERROR_READ_FAULT, errc::io_error}, 453 {ERROR_REPARSE_TAG_INVALID, errc::invalid_argument}, 454 {ERROR_RETRY, errc::resource_unavailable_try_again}, 455 {ERROR_SEEK, errc::io_error}, 456 {ERROR_SHARING_VIOLATION, errc::permission_denied}, 457 {ERROR_TOO_MANY_OPEN_FILES, errc::too_many_files_open}, 458 {ERROR_WRITE_FAULT, errc::io_error}, 459 {ERROR_WRITE_PROTECT, errc::permission_denied}, 460 }; 461 462 for (const auto &pair : win_error_mapping) 463 if (pair.win == static_cast<DWORD>(err)) 464 return pair.errc; 465 return errc::invalid_argument; 466 } 467 468 } // namespace detail 469 #endif 470 471 namespace detail { 472 namespace { 473 474 using value_type = path::value_type; 475 using string_type = path::string_type; 476 477 struct FileDescriptor { 478 const path& name; 479 int fd = -1; 480 StatT m_stat; 481 file_status m_status; 482 483 template <class... Args> 484 static FileDescriptor create(const path* p, error_code& ec, Args... args) { 485 ec.clear(); 486 int fd; 487 if ((fd = detail::open(p->c_str(), args...)) == -1) { 488 ec = capture_errno(); 489 return FileDescriptor{p}; 490 } 491 return FileDescriptor(p, fd); 492 } 493 494 template <class... Args> 495 static FileDescriptor create_with_status(const path* p, error_code& ec, 496 Args... args) { 497 FileDescriptor fd = create(p, ec, args...); 498 if (!ec) 499 fd.refresh_status(ec); 500 501 return fd; 502 } 503 504 file_status get_status() const { return m_status; } 505 StatT const& get_stat() const { return m_stat; } 506 507 bool status_known() const { return _VSTD_FS::status_known(m_status); } 508 509 file_status refresh_status(error_code& ec); 510 511 void close() noexcept { 512 if (fd != -1) 513 detail::close(fd); 514 fd = -1; 515 } 516 517 FileDescriptor(FileDescriptor&& other) 518 : name(other.name), fd(other.fd), m_stat(other.m_stat), 519 m_status(other.m_status) { 520 other.fd = -1; 521 other.m_status = file_status{}; 522 } 523 524 ~FileDescriptor() { close(); } 525 526 FileDescriptor(FileDescriptor const&) = delete; 527 FileDescriptor& operator=(FileDescriptor const&) = delete; 528 529 private: 530 explicit FileDescriptor(const path* p, int fd = -1) : name(*p), fd(fd) {} 531 }; 532 533 perms posix_get_perms(const StatT& st) noexcept { 534 return static_cast<perms>(st.st_mode) & perms::mask; 535 } 536 537 file_status create_file_status(error_code& m_ec, path const& p, 538 const StatT& path_stat, error_code* ec) { 539 if (ec) 540 *ec = m_ec; 541 if (m_ec && (m_ec.value() == ENOENT || m_ec.value() == ENOTDIR)) { 542 return file_status(file_type::not_found); 543 } else if (m_ec) { 544 ErrorHandler<void> err("posix_stat", ec, &p); 545 err.report(m_ec, "failed to determine attributes for the specified path"); 546 return file_status(file_type::none); 547 } 548 // else 549 550 file_status fs_tmp; 551 auto const mode = path_stat.st_mode; 552 if (S_ISLNK(mode)) 553 fs_tmp.type(file_type::symlink); 554 else if (S_ISREG(mode)) 555 fs_tmp.type(file_type::regular); 556 else if (S_ISDIR(mode)) 557 fs_tmp.type(file_type::directory); 558 else if (S_ISBLK(mode)) 559 fs_tmp.type(file_type::block); 560 else if (S_ISCHR(mode)) 561 fs_tmp.type(file_type::character); 562 else if (S_ISFIFO(mode)) 563 fs_tmp.type(file_type::fifo); 564 else if (S_ISSOCK(mode)) 565 fs_tmp.type(file_type::socket); 566 else 567 fs_tmp.type(file_type::unknown); 568 569 fs_tmp.permissions(detail::posix_get_perms(path_stat)); 570 return fs_tmp; 571 } 572 573 file_status posix_stat(path const& p, StatT& path_stat, error_code* ec) { 574 error_code m_ec; 575 if (detail::stat(p.c_str(), &path_stat) == -1) 576 m_ec = detail::capture_errno(); 577 return create_file_status(m_ec, p, path_stat, ec); 578 } 579 580 file_status posix_stat(path const& p, error_code* ec) { 581 StatT path_stat; 582 return posix_stat(p, path_stat, ec); 583 } 584 585 file_status posix_lstat(path const& p, StatT& path_stat, error_code* ec) { 586 error_code m_ec; 587 if (detail::lstat(p.c_str(), &path_stat) == -1) 588 m_ec = detail::capture_errno(); 589 return create_file_status(m_ec, p, path_stat, ec); 590 } 591 592 file_status posix_lstat(path const& p, error_code* ec) { 593 StatT path_stat; 594 return posix_lstat(p, path_stat, ec); 595 } 596 597 // http://pubs.opengroup.org/onlinepubs/9699919799/functions/ftruncate.html 598 bool posix_ftruncate(const FileDescriptor& fd, off_t to_size, error_code& ec) { 599 if (detail::ftruncate(fd.fd, to_size) == -1) { 600 ec = capture_errno(); 601 return true; 602 } 603 ec.clear(); 604 return false; 605 } 606 607 bool posix_fchmod(const FileDescriptor& fd, const StatT& st, error_code& ec) { 608 if (detail::fchmod(fd.fd, st.st_mode) == -1) { 609 ec = capture_errno(); 610 return true; 611 } 612 ec.clear(); 613 return false; 614 } 615 616 bool stat_equivalent(const StatT& st1, const StatT& st2) { 617 return (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino); 618 } 619 620 file_status FileDescriptor::refresh_status(error_code& ec) { 621 // FD must be open and good. 622 m_status = file_status{}; 623 m_stat = {}; 624 error_code m_ec; 625 if (detail::fstat(fd, &m_stat) == -1) 626 m_ec = capture_errno(); 627 m_status = create_file_status(m_ec, name, m_stat, &ec); 628 return m_status; 629 } 630 } // namespace 631 } // end namespace detail 632 633 using detail::capture_errno; 634 using detail::ErrorHandler; 635 using detail::StatT; 636 using detail::TimeSpec; 637 using parser::createView; 638 using parser::PathParser; 639 using parser::string_view_t; 640 641 const bool _FilesystemClock::is_steady; 642 643 _FilesystemClock::time_point _FilesystemClock::now() noexcept { 644 typedef chrono::duration<rep> __secs; 645 #if defined(_LIBCPP_WIN32API) 646 typedef chrono::duration<rep, nano> __nsecs; 647 FILETIME time; 648 GetSystemTimeAsFileTime(&time); 649 TimeSpec tp = detail::filetime_to_timespec(time); 650 return time_point(__secs(tp.tv_sec) + 651 chrono::duration_cast<duration>(__nsecs(tp.tv_nsec))); 652 #elif defined(CLOCK_REALTIME) 653 typedef chrono::duration<rep, nano> __nsecs; 654 struct timespec tp; 655 if (0 != clock_gettime(CLOCK_REALTIME, &tp)) 656 __throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed"); 657 return time_point(__secs(tp.tv_sec) + 658 chrono::duration_cast<duration>(__nsecs(tp.tv_nsec))); 659 #else 660 typedef chrono::duration<rep, micro> __microsecs; 661 timeval tv; 662 gettimeofday(&tv, 0); 663 return time_point(__secs(tv.tv_sec) + __microsecs(tv.tv_usec)); 664 #endif // CLOCK_REALTIME 665 } 666 667 filesystem_error::~filesystem_error() {} 668 669 #if defined(_LIBCPP_WIN32API) 670 #define PS_FMT "%ls" 671 #else 672 #define PS_FMT "%s" 673 #endif 674 675 void filesystem_error::__create_what(int __num_paths) { 676 const char* derived_what = system_error::what(); 677 __storage_->__what_ = [&]() -> string { 678 const path::value_type* p1 = path1().native().empty() ? PS("\"\"") : path1().c_str(); 679 const path::value_type* p2 = path2().native().empty() ? PS("\"\"") : path2().c_str(); 680 switch (__num_paths) { 681 default: 682 return detail::format_string("filesystem error: %s", derived_what); 683 case 1: 684 return detail::format_string("filesystem error: %s [" PS_FMT "]", derived_what, 685 p1); 686 case 2: 687 return detail::format_string("filesystem error: %s [" PS_FMT "] [" PS_FMT "]", 688 derived_what, p1, p2); 689 } 690 }(); 691 } 692 693 static path __do_absolute(const path& p, path* cwd, error_code* ec) { 694 if (ec) 695 ec->clear(); 696 if (p.is_absolute()) 697 return p; 698 *cwd = __current_path(ec); 699 if (ec && *ec) 700 return {}; 701 return (*cwd) / p; 702 } 703 704 path __absolute(const path& p, error_code* ec) { 705 path cwd; 706 return __do_absolute(p, &cwd, ec); 707 } 708 709 path __canonical(path const& orig_p, error_code* ec) { 710 path cwd; 711 ErrorHandler<path> err("canonical", ec, &orig_p, &cwd); 712 713 path p = __do_absolute(orig_p, &cwd, ec); 714 #if (defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112) || defined(_LIBCPP_WIN32API) 715 std::unique_ptr<path::value_type, decltype(&::free)> 716 hold(detail::realpath(p.c_str(), nullptr), &::free); 717 if (hold.get() == nullptr) 718 return err.report(capture_errno()); 719 return {hold.get()}; 720 #else 721 #if defined(__MVS__) && !defined(PATH_MAX) 722 path::value_type buff[ _XOPEN_PATH_MAX + 1 ]; 723 #else 724 path::value_type buff[PATH_MAX + 1]; 725 #endif 726 path::value_type* ret; 727 if ((ret = detail::realpath(p.c_str(), buff)) == nullptr) 728 return err.report(capture_errno()); 729 return {ret}; 730 #endif 731 } 732 733 void __copy(const path& from, const path& to, copy_options options, 734 error_code* ec) { 735 ErrorHandler<void> err("copy", ec, &from, &to); 736 737 const bool sym_status = bool( 738 options & (copy_options::create_symlinks | copy_options::skip_symlinks)); 739 740 const bool sym_status2 = bool(options & copy_options::copy_symlinks); 741 742 error_code m_ec1; 743 StatT f_st = {}; 744 const file_status f = sym_status || sym_status2 745 ? detail::posix_lstat(from, f_st, &m_ec1) 746 : detail::posix_stat(from, f_st, &m_ec1); 747 if (m_ec1) 748 return err.report(m_ec1); 749 750 StatT t_st = {}; 751 const file_status t = sym_status ? detail::posix_lstat(to, t_st, &m_ec1) 752 : detail::posix_stat(to, t_st, &m_ec1); 753 754 if (not status_known(t)) 755 return err.report(m_ec1); 756 757 if (!exists(f) || is_other(f) || is_other(t) || 758 (is_directory(f) && is_regular_file(t)) || 759 detail::stat_equivalent(f_st, t_st)) { 760 return err.report(errc::function_not_supported); 761 } 762 763 if (ec) 764 ec->clear(); 765 766 if (is_symlink(f)) { 767 if (bool(copy_options::skip_symlinks & options)) { 768 // do nothing 769 } else if (not exists(t)) { 770 __copy_symlink(from, to, ec); 771 } else { 772 return err.report(errc::file_exists); 773 } 774 return; 775 } else if (is_regular_file(f)) { 776 if (bool(copy_options::directories_only & options)) { 777 // do nothing 778 } else if (bool(copy_options::create_symlinks & options)) { 779 __create_symlink(from, to, ec); 780 } else if (bool(copy_options::create_hard_links & options)) { 781 __create_hard_link(from, to, ec); 782 } else if (is_directory(t)) { 783 __copy_file(from, to / from.filename(), options, ec); 784 } else { 785 __copy_file(from, to, options, ec); 786 } 787 return; 788 } else if (is_directory(f) && bool(copy_options::create_symlinks & options)) { 789 return err.report(errc::is_a_directory); 790 } else if (is_directory(f) && (bool(copy_options::recursive & options) || 791 copy_options::none == options)) { 792 793 if (!exists(t)) { 794 // create directory to with attributes from 'from'. 795 __create_directory(to, from, ec); 796 if (ec && *ec) { 797 return; 798 } 799 } 800 directory_iterator it = 801 ec ? directory_iterator(from, *ec) : directory_iterator(from); 802 if (ec && *ec) { 803 return; 804 } 805 error_code m_ec2; 806 for (; it != directory_iterator(); it.increment(m_ec2)) { 807 if (m_ec2) { 808 return err.report(m_ec2); 809 } 810 __copy(it->path(), to / it->path().filename(), 811 options | copy_options::__in_recursive_copy, ec); 812 if (ec && *ec) { 813 return; 814 } 815 } 816 } 817 } 818 819 namespace detail { 820 namespace { 821 822 #if defined(_LIBCPP_FILESYSTEM_USE_SENDFILE) 823 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) { 824 size_t count = read_fd.get_stat().st_size; 825 do { 826 ssize_t res; 827 if ((res = ::sendfile(write_fd.fd, read_fd.fd, nullptr, count)) == -1) { 828 ec = capture_errno(); 829 return false; 830 } 831 count -= res; 832 } while (count > 0); 833 834 ec.clear(); 835 836 return true; 837 } 838 #elif defined(_LIBCPP_FILESYSTEM_USE_COPYFILE) 839 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) { 840 struct CopyFileState { 841 copyfile_state_t state; 842 CopyFileState() { state = copyfile_state_alloc(); } 843 ~CopyFileState() { copyfile_state_free(state); } 844 845 private: 846 CopyFileState(CopyFileState const&) = delete; 847 CopyFileState& operator=(CopyFileState const&) = delete; 848 }; 849 850 CopyFileState cfs; 851 if (fcopyfile(read_fd.fd, write_fd.fd, cfs.state, COPYFILE_DATA) < 0) { 852 ec = capture_errno(); 853 return false; 854 } 855 856 ec.clear(); 857 return true; 858 } 859 #elif defined(_LIBCPP_FILESYSTEM_USE_FSTREAM) 860 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) { 861 ifstream in; 862 in.__open(read_fd.fd, ios::binary); 863 if (!in.is_open()) { 864 // This assumes that __open didn't reset the error code. 865 ec = capture_errno(); 866 return false; 867 } 868 read_fd.fd = -1; 869 ofstream out; 870 out.__open(write_fd.fd, ios::binary); 871 if (!out.is_open()) { 872 ec = capture_errno(); 873 return false; 874 } 875 write_fd.fd = -1; 876 877 if (in.good() && out.good()) { 878 using InIt = istreambuf_iterator<char>; 879 using OutIt = ostreambuf_iterator<char>; 880 InIt bin(in); 881 InIt ein; 882 OutIt bout(out); 883 copy(bin, ein, bout); 884 } 885 if (out.fail() || in.fail()) { 886 ec = make_error_code(errc::io_error); 887 return false; 888 } 889 890 ec.clear(); 891 return true; 892 } 893 #else 894 # error "Unknown implementation for copy_file_impl" 895 #endif // copy_file_impl implementation 896 897 } // end anonymous namespace 898 } // end namespace detail 899 900 bool __copy_file(const path& from, const path& to, copy_options options, 901 error_code* ec) { 902 using detail::FileDescriptor; 903 ErrorHandler<bool> err("copy_file", ec, &to, &from); 904 905 error_code m_ec; 906 FileDescriptor from_fd = FileDescriptor::create_with_status( 907 &from, m_ec, O_RDONLY | O_NONBLOCK | O_BINARY); 908 if (m_ec) 909 return err.report(m_ec); 910 911 auto from_st = from_fd.get_status(); 912 StatT const& from_stat = from_fd.get_stat(); 913 if (!is_regular_file(from_st)) { 914 if (not m_ec) 915 m_ec = make_error_code(errc::not_supported); 916 return err.report(m_ec); 917 } 918 919 const bool skip_existing = bool(copy_options::skip_existing & options); 920 const bool update_existing = bool(copy_options::update_existing & options); 921 const bool overwrite_existing = 922 bool(copy_options::overwrite_existing & options); 923 924 StatT to_stat_path; 925 file_status to_st = detail::posix_stat(to, to_stat_path, &m_ec); 926 if (!status_known(to_st)) 927 return err.report(m_ec); 928 929 const bool to_exists = exists(to_st); 930 if (to_exists && !is_regular_file(to_st)) 931 return err.report(errc::not_supported); 932 933 if (to_exists && detail::stat_equivalent(from_stat, to_stat_path)) 934 return err.report(errc::file_exists); 935 936 if (to_exists && skip_existing) 937 return false; 938 939 bool ShouldCopy = [&]() { 940 if (to_exists && update_existing) { 941 auto from_time = detail::extract_mtime(from_stat); 942 auto to_time = detail::extract_mtime(to_stat_path); 943 if (from_time.tv_sec < to_time.tv_sec) 944 return false; 945 if (from_time.tv_sec == to_time.tv_sec && 946 from_time.tv_nsec <= to_time.tv_nsec) 947 return false; 948 return true; 949 } 950 if (!to_exists || overwrite_existing) 951 return true; 952 return err.report(errc::file_exists); 953 }(); 954 if (!ShouldCopy) 955 return false; 956 957 // Don't truncate right away. We may not be opening the file we originally 958 // looked at; we'll check this later. 959 int to_open_flags = O_WRONLY | O_BINARY; 960 if (!to_exists) 961 to_open_flags |= O_CREAT; 962 FileDescriptor to_fd = FileDescriptor::create_with_status( 963 &to, m_ec, to_open_flags, from_stat.st_mode); 964 if (m_ec) 965 return err.report(m_ec); 966 967 if (to_exists) { 968 // Check that the file we initially stat'ed is equivalent to the one 969 // we opened. 970 // FIXME: report this better. 971 if (!detail::stat_equivalent(to_stat_path, to_fd.get_stat())) 972 return err.report(errc::bad_file_descriptor); 973 974 // Set the permissions and truncate the file we opened. 975 if (detail::posix_fchmod(to_fd, from_stat, m_ec)) 976 return err.report(m_ec); 977 if (detail::posix_ftruncate(to_fd, 0, m_ec)) 978 return err.report(m_ec); 979 } 980 981 if (!copy_file_impl(from_fd, to_fd, m_ec)) { 982 // FIXME: Remove the dest file if we failed, and it didn't exist previously. 983 return err.report(m_ec); 984 } 985 986 return true; 987 } 988 989 void __copy_symlink(const path& existing_symlink, const path& new_symlink, 990 error_code* ec) { 991 const path real_path(__read_symlink(existing_symlink, ec)); 992 if (ec && *ec) { 993 return; 994 } 995 #if defined(_LIBCPP_WIN32API) 996 error_code local_ec; 997 if (is_directory(real_path, local_ec)) 998 __create_directory_symlink(real_path, new_symlink, ec); 999 else 1000 #endif 1001 __create_symlink(real_path, new_symlink, ec); 1002 } 1003 1004 bool __create_directories(const path& p, error_code* ec) { 1005 ErrorHandler<bool> err("create_directories", ec, &p); 1006 1007 error_code m_ec; 1008 auto const st = detail::posix_stat(p, &m_ec); 1009 if (!status_known(st)) 1010 return err.report(m_ec); 1011 else if (is_directory(st)) 1012 return false; 1013 else if (exists(st)) 1014 return err.report(errc::file_exists); 1015 1016 const path parent = p.parent_path(); 1017 if (!parent.empty()) { 1018 const file_status parent_st = status(parent, m_ec); 1019 if (not status_known(parent_st)) 1020 return err.report(m_ec); 1021 if (not exists(parent_st)) { 1022 __create_directories(parent, ec); 1023 if (ec && *ec) { 1024 return false; 1025 } 1026 } 1027 } 1028 return __create_directory(p, ec); 1029 } 1030 1031 bool __create_directory(const path& p, error_code* ec) { 1032 ErrorHandler<bool> err("create_directory", ec, &p); 1033 1034 if (detail::mkdir(p.c_str(), static_cast<int>(perms::all)) == 0) 1035 return true; 1036 1037 if (errno == EEXIST) { 1038 error_code mec = capture_errno(); 1039 error_code ignored_ec; 1040 const file_status st = status(p, ignored_ec); 1041 if (!is_directory(st)) { 1042 err.report(mec); 1043 } 1044 } else { 1045 err.report(capture_errno()); 1046 } 1047 return false; 1048 } 1049 1050 bool __create_directory(path const& p, path const& attributes, error_code* ec) { 1051 ErrorHandler<bool> err("create_directory", ec, &p, &attributes); 1052 1053 StatT attr_stat; 1054 error_code mec; 1055 file_status st = detail::posix_stat(attributes, attr_stat, &mec); 1056 if (!status_known(st)) 1057 return err.report(mec); 1058 if (!is_directory(st)) 1059 return err.report(errc::not_a_directory, 1060 "the specified attribute path is invalid"); 1061 1062 if (detail::mkdir(p.c_str(), attr_stat.st_mode) == 0) 1063 return true; 1064 1065 if (errno != EEXIST) 1066 return err.report(capture_errno()); 1067 1068 mec = capture_errno(); 1069 error_code ignored_ec; 1070 st = status(p, ignored_ec); 1071 if (!is_directory(st)) 1072 return err.report(mec); 1073 return false; 1074 } 1075 1076 void __create_directory_symlink(path const& from, path const& to, 1077 error_code* ec) { 1078 ErrorHandler<void> err("create_directory_symlink", ec, &from, &to); 1079 if (detail::symlink_dir(from.c_str(), to.c_str()) == -1) 1080 return err.report(capture_errno()); 1081 } 1082 1083 void __create_hard_link(const path& from, const path& to, error_code* ec) { 1084 ErrorHandler<void> err("create_hard_link", ec, &from, &to); 1085 if (detail::link(from.c_str(), to.c_str()) == -1) 1086 return err.report(capture_errno()); 1087 } 1088 1089 void __create_symlink(path const& from, path const& to, error_code* ec) { 1090 ErrorHandler<void> err("create_symlink", ec, &from, &to); 1091 if (detail::symlink_file(from.c_str(), to.c_str()) == -1) 1092 return err.report(capture_errno()); 1093 } 1094 1095 path __current_path(error_code* ec) { 1096 ErrorHandler<path> err("current_path", ec); 1097 1098 #if defined(_LIBCPP_WIN32API) || defined(__GLIBC__) || defined(__APPLE__) 1099 // Common extension outside of POSIX getcwd() spec, without needing to 1100 // preallocate a buffer. Also supported by a number of other POSIX libcs. 1101 int size = 0; 1102 path::value_type* ptr = nullptr; 1103 typedef decltype(&::free) Deleter; 1104 Deleter deleter = &::free; 1105 #else 1106 auto size = ::pathconf(".", _PC_PATH_MAX); 1107 _LIBCPP_ASSERT(size >= 0, "pathconf returned a 0 as max size"); 1108 1109 auto buff = unique_ptr<path::value_type[]>(new path::value_type[size + 1]); 1110 path::value_type* ptr = buff.get(); 1111 1112 // Preallocated buffer, don't free the buffer in the second unique_ptr 1113 // below. 1114 struct Deleter { void operator()(void*) const {} }; 1115 Deleter deleter; 1116 #endif 1117 1118 unique_ptr<path::value_type, Deleter> hold(detail::getcwd(ptr, size), 1119 deleter); 1120 if (hold.get() == nullptr) 1121 return err.report(capture_errno(), "call to getcwd failed"); 1122 1123 return {hold.get()}; 1124 } 1125 1126 void __current_path(const path& p, error_code* ec) { 1127 ErrorHandler<void> err("current_path", ec, &p); 1128 if (detail::chdir(p.c_str()) == -1) 1129 err.report(capture_errno()); 1130 } 1131 1132 bool __equivalent(const path& p1, const path& p2, error_code* ec) { 1133 ErrorHandler<bool> err("equivalent", ec, &p1, &p2); 1134 1135 error_code ec1, ec2; 1136 StatT st1 = {}, st2 = {}; 1137 auto s1 = detail::posix_stat(p1.native(), st1, &ec1); 1138 if (!exists(s1)) 1139 return err.report(errc::not_supported); 1140 auto s2 = detail::posix_stat(p2.native(), st2, &ec2); 1141 if (!exists(s2)) 1142 return err.report(errc::not_supported); 1143 1144 return detail::stat_equivalent(st1, st2); 1145 } 1146 1147 uintmax_t __file_size(const path& p, error_code* ec) { 1148 ErrorHandler<uintmax_t> err("file_size", ec, &p); 1149 1150 error_code m_ec; 1151 StatT st; 1152 file_status fst = detail::posix_stat(p, st, &m_ec); 1153 if (!exists(fst) || !is_regular_file(fst)) { 1154 errc error_kind = 1155 is_directory(fst) ? errc::is_a_directory : errc::not_supported; 1156 if (!m_ec) 1157 m_ec = make_error_code(error_kind); 1158 return err.report(m_ec); 1159 } 1160 // is_regular_file(p) == true 1161 return static_cast<uintmax_t>(st.st_size); 1162 } 1163 1164 uintmax_t __hard_link_count(const path& p, error_code* ec) { 1165 ErrorHandler<uintmax_t> err("hard_link_count", ec, &p); 1166 1167 error_code m_ec; 1168 StatT st; 1169 detail::posix_stat(p, st, &m_ec); 1170 if (m_ec) 1171 return err.report(m_ec); 1172 return static_cast<uintmax_t>(st.st_nlink); 1173 } 1174 1175 bool __fs_is_empty(const path& p, error_code* ec) { 1176 ErrorHandler<bool> err("is_empty", ec, &p); 1177 1178 error_code m_ec; 1179 StatT pst; 1180 auto st = detail::posix_stat(p, pst, &m_ec); 1181 if (m_ec) 1182 return err.report(m_ec); 1183 else if (!is_directory(st) && !is_regular_file(st)) 1184 return err.report(errc::not_supported); 1185 else if (is_directory(st)) { 1186 auto it = ec ? directory_iterator(p, *ec) : directory_iterator(p); 1187 if (ec && *ec) 1188 return false; 1189 return it == directory_iterator{}; 1190 } else if (is_regular_file(st)) 1191 return static_cast<uintmax_t>(pst.st_size) == 0; 1192 1193 _LIBCPP_UNREACHABLE(); 1194 } 1195 1196 static file_time_type __extract_last_write_time(const path& p, const StatT& st, 1197 error_code* ec) { 1198 using detail::fs_time; 1199 ErrorHandler<file_time_type> err("last_write_time", ec, &p); 1200 1201 auto ts = detail::extract_mtime(st); 1202 if (!fs_time::is_representable(ts)) 1203 return err.report(errc::value_too_large); 1204 1205 return fs_time::convert_from_timespec(ts); 1206 } 1207 1208 file_time_type __last_write_time(const path& p, error_code* ec) { 1209 using namespace chrono; 1210 ErrorHandler<file_time_type> err("last_write_time", ec, &p); 1211 1212 error_code m_ec; 1213 StatT st; 1214 detail::posix_stat(p, st, &m_ec); 1215 if (m_ec) 1216 return err.report(m_ec); 1217 return __extract_last_write_time(p, st, ec); 1218 } 1219 1220 void __last_write_time(const path& p, file_time_type new_time, error_code* ec) { 1221 using detail::fs_time; 1222 ErrorHandler<void> err("last_write_time", ec, &p); 1223 1224 #if defined(_LIBCPP_WIN32API) 1225 TimeSpec ts; 1226 if (!fs_time::convert_to_timespec(ts, new_time)) 1227 return err.report(errc::value_too_large); 1228 detail::WinHandle h(p.c_str(), FILE_WRITE_ATTRIBUTES, 0); 1229 if (!h) 1230 return err.report(detail::make_windows_error(GetLastError())); 1231 FILETIME last_write = timespec_to_filetime(ts); 1232 if (!SetFileTime(h, nullptr, nullptr, &last_write)) 1233 return err.report(detail::make_windows_error(GetLastError())); 1234 #else 1235 error_code m_ec; 1236 array<TimeSpec, 2> tbuf; 1237 #if !defined(_LIBCPP_USE_UTIMENSAT) 1238 // This implementation has a race condition between determining the 1239 // last access time and attempting to set it to the same value using 1240 // ::utimes 1241 StatT st; 1242 file_status fst = detail::posix_stat(p, st, &m_ec); 1243 if (m_ec) 1244 return err.report(m_ec); 1245 tbuf[0] = detail::extract_atime(st); 1246 #else 1247 tbuf[0].tv_sec = 0; 1248 tbuf[0].tv_nsec = UTIME_OMIT; 1249 #endif 1250 if (!fs_time::convert_to_timespec(tbuf[1], new_time)) 1251 return err.report(errc::value_too_large); 1252 1253 detail::set_file_times(p, tbuf, m_ec); 1254 if (m_ec) 1255 return err.report(m_ec); 1256 #endif 1257 } 1258 1259 void __permissions(const path& p, perms prms, perm_options opts, 1260 error_code* ec) { 1261 ErrorHandler<void> err("permissions", ec, &p); 1262 1263 auto has_opt = [&](perm_options o) { return bool(o & opts); }; 1264 const bool resolve_symlinks = !has_opt(perm_options::nofollow); 1265 const bool add_perms = has_opt(perm_options::add); 1266 const bool remove_perms = has_opt(perm_options::remove); 1267 _LIBCPP_ASSERT( 1268 (add_perms + remove_perms + has_opt(perm_options::replace)) == 1, 1269 "One and only one of the perm_options constants replace, add, or remove " 1270 "is present in opts"); 1271 1272 bool set_sym_perms = false; 1273 prms &= perms::mask; 1274 if (!resolve_symlinks || (add_perms || remove_perms)) { 1275 error_code m_ec; 1276 file_status st = resolve_symlinks ? detail::posix_stat(p, &m_ec) 1277 : detail::posix_lstat(p, &m_ec); 1278 set_sym_perms = is_symlink(st); 1279 if (m_ec) 1280 return err.report(m_ec); 1281 _LIBCPP_ASSERT(st.permissions() != perms::unknown, 1282 "Permissions unexpectedly unknown"); 1283 if (add_perms) 1284 prms |= st.permissions(); 1285 else if (remove_perms) 1286 prms = st.permissions() & ~prms; 1287 } 1288 const auto real_perms = static_cast<detail::ModeT>(prms & perms::mask); 1289 1290 #if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD) 1291 const int flags = set_sym_perms ? AT_SYMLINK_NOFOLLOW : 0; 1292 if (detail::fchmodat(AT_FDCWD, p.c_str(), real_perms, flags) == -1) { 1293 return err.report(capture_errno()); 1294 } 1295 #else 1296 if (set_sym_perms) 1297 return err.report(errc::operation_not_supported); 1298 if (::chmod(p.c_str(), real_perms) == -1) { 1299 return err.report(capture_errno()); 1300 } 1301 #endif 1302 } 1303 1304 path __read_symlink(const path& p, error_code* ec) { 1305 ErrorHandler<path> err("read_symlink", ec, &p); 1306 1307 #if defined(PATH_MAX) || defined(MAX_SYMLINK_SIZE) 1308 struct NullDeleter { void operator()(void*) const {} }; 1309 #ifdef MAX_SYMLINK_SIZE 1310 const size_t size = MAX_SYMLINK_SIZE + 1; 1311 #else 1312 const size_t size = PATH_MAX + 1; 1313 #endif 1314 path::value_type stack_buff[size]; 1315 auto buff = std::unique_ptr<path::value_type[], NullDeleter>(stack_buff); 1316 #else 1317 StatT sb; 1318 if (detail::lstat(p.c_str(), &sb) == -1) { 1319 return err.report(capture_errno()); 1320 } 1321 const size_t size = sb.st_size + 1; 1322 auto buff = unique_ptr<path::value_type[]>(new path::value_type[size]); 1323 #endif 1324 detail::SSizeT ret; 1325 if ((ret = detail::readlink(p.c_str(), buff.get(), size)) == -1) 1326 return err.report(capture_errno()); 1327 _LIBCPP_ASSERT(ret > 0, "TODO"); 1328 if (static_cast<size_t>(ret) >= size) 1329 return err.report(errc::value_too_large); 1330 buff[ret] = 0; 1331 return {buff.get()}; 1332 } 1333 1334 bool __remove(const path& p, error_code* ec) { 1335 ErrorHandler<bool> err("remove", ec, &p); 1336 if (detail::remove(p.c_str()) == -1) { 1337 if (errno != ENOENT) 1338 err.report(capture_errno()); 1339 return false; 1340 } 1341 return true; 1342 } 1343 1344 namespace { 1345 1346 uintmax_t remove_all_impl(path const& p, error_code& ec) { 1347 const auto npos = static_cast<uintmax_t>(-1); 1348 const file_status st = __symlink_status(p, &ec); 1349 if (ec) 1350 return npos; 1351 uintmax_t count = 1; 1352 if (is_directory(st)) { 1353 for (directory_iterator it(p, ec); !ec && it != directory_iterator(); 1354 it.increment(ec)) { 1355 auto other_count = remove_all_impl(it->path(), ec); 1356 if (ec) 1357 return npos; 1358 count += other_count; 1359 } 1360 if (ec) 1361 return npos; 1362 } 1363 if (!__remove(p, &ec)) 1364 return npos; 1365 return count; 1366 } 1367 1368 } // end namespace 1369 1370 uintmax_t __remove_all(const path& p, error_code* ec) { 1371 ErrorHandler<uintmax_t> err("remove_all", ec, &p); 1372 1373 error_code mec; 1374 auto count = remove_all_impl(p, mec); 1375 if (mec) { 1376 if (mec == errc::no_such_file_or_directory) 1377 return 0; 1378 return err.report(mec); 1379 } 1380 return count; 1381 } 1382 1383 void __rename(const path& from, const path& to, error_code* ec) { 1384 ErrorHandler<void> err("rename", ec, &from, &to); 1385 if (detail::rename(from.c_str(), to.c_str()) == -1) 1386 err.report(capture_errno()); 1387 } 1388 1389 void __resize_file(const path& p, uintmax_t size, error_code* ec) { 1390 ErrorHandler<void> err("resize_file", ec, &p); 1391 if (detail::truncate(p.c_str(), static_cast< ::off_t>(size)) == -1) 1392 return err.report(capture_errno()); 1393 } 1394 1395 space_info __space(const path& p, error_code* ec) { 1396 ErrorHandler<void> err("space", ec, &p); 1397 space_info si; 1398 detail::StatVFS m_svfs = {}; 1399 if (detail::statvfs(p.c_str(), &m_svfs) == -1) { 1400 err.report(capture_errno()); 1401 si.capacity = si.free = si.available = static_cast<uintmax_t>(-1); 1402 return si; 1403 } 1404 // Multiply with overflow checking. 1405 auto do_mult = [&](uintmax_t& out, uintmax_t other) { 1406 out = other * m_svfs.f_frsize; 1407 if (other == 0 || out / other != m_svfs.f_frsize) 1408 out = static_cast<uintmax_t>(-1); 1409 }; 1410 do_mult(si.capacity, m_svfs.f_blocks); 1411 do_mult(si.free, m_svfs.f_bfree); 1412 do_mult(si.available, m_svfs.f_bavail); 1413 return si; 1414 } 1415 1416 file_status __status(const path& p, error_code* ec) { 1417 return detail::posix_stat(p, ec); 1418 } 1419 1420 file_status __symlink_status(const path& p, error_code* ec) { 1421 return detail::posix_lstat(p, ec); 1422 } 1423 1424 path __temp_directory_path(error_code* ec) { 1425 ErrorHandler<path> err("temp_directory_path", ec); 1426 1427 #if defined(_LIBCPP_WIN32API) 1428 wchar_t buf[MAX_PATH]; 1429 DWORD retval = GetTempPathW(MAX_PATH, buf); 1430 if (!retval) 1431 return err.report(detail::make_windows_error(GetLastError())); 1432 if (retval > MAX_PATH) 1433 return err.report(errc::filename_too_long); 1434 // GetTempPathW returns a path with a trailing slash, which we 1435 // shouldn't include for consistency. 1436 if (buf[retval-1] == L'\\') 1437 buf[retval-1] = L'\0'; 1438 path p(buf); 1439 #else 1440 const char* env_paths[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"}; 1441 const char* ret = nullptr; 1442 1443 for (auto& ep : env_paths) 1444 if ((ret = getenv(ep))) 1445 break; 1446 if (ret == nullptr) 1447 ret = "/tmp"; 1448 1449 path p(ret); 1450 #endif 1451 error_code m_ec; 1452 file_status st = detail::posix_stat(p, &m_ec); 1453 if (!status_known(st)) 1454 return err.report(m_ec, "cannot access path \"" PS_FMT "\"", p); 1455 1456 if (!exists(st) || !is_directory(st)) 1457 return err.report(errc::not_a_directory, "path \"" PS_FMT "\" is not a directory", 1458 p); 1459 1460 return p; 1461 } 1462 1463 path __weakly_canonical(const path& p, error_code* ec) { 1464 ErrorHandler<path> err("weakly_canonical", ec, &p); 1465 1466 if (p.empty()) 1467 return __canonical("", ec); 1468 1469 path result; 1470 path tmp; 1471 tmp.__reserve(p.native().size()); 1472 auto PP = PathParser::CreateEnd(p.native()); 1473 --PP; 1474 vector<string_view_t> DNEParts; 1475 1476 while (PP.State != PathParser::PS_BeforeBegin) { 1477 tmp.assign(createView(p.native().data(), &PP.RawEntry.back())); 1478 error_code m_ec; 1479 file_status st = __status(tmp, &m_ec); 1480 if (!status_known(st)) { 1481 return err.report(m_ec); 1482 } else if (exists(st)) { 1483 result = __canonical(tmp, ec); 1484 break; 1485 } 1486 DNEParts.push_back(*PP); 1487 --PP; 1488 } 1489 if (PP.State == PathParser::PS_BeforeBegin) 1490 result = __canonical("", ec); 1491 if (ec) 1492 ec->clear(); 1493 if (DNEParts.empty()) 1494 return result; 1495 for (auto It = DNEParts.rbegin(); It != DNEParts.rend(); ++It) 1496 result /= *It; 1497 return result.lexically_normal(); 1498 } 1499 1500 /////////////////////////////////////////////////////////////////////////////// 1501 // path definitions 1502 /////////////////////////////////////////////////////////////////////////////// 1503 1504 constexpr path::value_type path::preferred_separator; 1505 1506 path& path::replace_extension(path const& replacement) { 1507 path p = extension(); 1508 if (not p.empty()) { 1509 __pn_.erase(__pn_.size() - p.native().size()); 1510 } 1511 if (!replacement.empty()) { 1512 if (replacement.native()[0] != '.') { 1513 __pn_ += PS("."); 1514 } 1515 __pn_.append(replacement.__pn_); 1516 } 1517 return *this; 1518 } 1519 1520 /////////////////////////////////////////////////////////////////////////////// 1521 // path.decompose 1522 1523 string_view_t path::__root_name() const { 1524 auto PP = PathParser::CreateBegin(__pn_); 1525 if (PP.State == PathParser::PS_InRootName) 1526 return *PP; 1527 return {}; 1528 } 1529 1530 string_view_t path::__root_directory() const { 1531 auto PP = PathParser::CreateBegin(__pn_); 1532 if (PP.State == PathParser::PS_InRootName) 1533 ++PP; 1534 if (PP.State == PathParser::PS_InRootDir) 1535 return *PP; 1536 return {}; 1537 } 1538 1539 string_view_t path::__root_path_raw() const { 1540 auto PP = PathParser::CreateBegin(__pn_); 1541 if (PP.State == PathParser::PS_InRootName) { 1542 auto NextCh = PP.peek(); 1543 if (NextCh && isSeparator(*NextCh)) { 1544 ++PP; 1545 return createView(__pn_.data(), &PP.RawEntry.back()); 1546 } 1547 return PP.RawEntry; 1548 } 1549 if (PP.State == PathParser::PS_InRootDir) 1550 return *PP; 1551 return {}; 1552 } 1553 1554 static bool ConsumeRootName(PathParser *PP) { 1555 static_assert(PathParser::PS_BeforeBegin == 1 && 1556 PathParser::PS_InRootName == 2, 1557 "Values for enums are incorrect"); 1558 while (PP->State <= PathParser::PS_InRootName) 1559 ++(*PP); 1560 return PP->State == PathParser::PS_AtEnd; 1561 } 1562 1563 static bool ConsumeRootDir(PathParser* PP) { 1564 static_assert(PathParser::PS_BeforeBegin == 1 && 1565 PathParser::PS_InRootName == 2 && 1566 PathParser::PS_InRootDir == 3, "Values for enums are incorrect"); 1567 while (PP->State <= PathParser::PS_InRootDir) 1568 ++(*PP); 1569 return PP->State == PathParser::PS_AtEnd; 1570 } 1571 1572 string_view_t path::__relative_path() const { 1573 auto PP = PathParser::CreateBegin(__pn_); 1574 if (ConsumeRootDir(&PP)) 1575 return {}; 1576 return createView(PP.RawEntry.data(), &__pn_.back()); 1577 } 1578 1579 string_view_t path::__parent_path() const { 1580 if (empty()) 1581 return {}; 1582 // Determine if we have a root path but not a relative path. In that case 1583 // return *this. 1584 { 1585 auto PP = PathParser::CreateBegin(__pn_); 1586 if (ConsumeRootDir(&PP)) 1587 return __pn_; 1588 } 1589 // Otherwise remove a single element from the end of the path, and return 1590 // a string representing that path 1591 { 1592 auto PP = PathParser::CreateEnd(__pn_); 1593 --PP; 1594 if (PP.RawEntry.data() == __pn_.data()) 1595 return {}; 1596 --PP; 1597 return createView(__pn_.data(), &PP.RawEntry.back()); 1598 } 1599 } 1600 1601 string_view_t path::__filename() const { 1602 if (empty()) 1603 return {}; 1604 { 1605 PathParser PP = PathParser::CreateBegin(__pn_); 1606 if (ConsumeRootDir(&PP)) 1607 return {}; 1608 } 1609 return *(--PathParser::CreateEnd(__pn_)); 1610 } 1611 1612 string_view_t path::__stem() const { 1613 return parser::separate_filename(__filename()).first; 1614 } 1615 1616 string_view_t path::__extension() const { 1617 return parser::separate_filename(__filename()).second; 1618 } 1619 1620 //////////////////////////////////////////////////////////////////////////// 1621 // path.gen 1622 1623 enum PathPartKind : unsigned char { 1624 PK_None, 1625 PK_RootSep, 1626 PK_Filename, 1627 PK_Dot, 1628 PK_DotDot, 1629 PK_TrailingSep 1630 }; 1631 1632 static PathPartKind ClassifyPathPart(string_view_t Part) { 1633 if (Part.empty()) 1634 return PK_TrailingSep; 1635 if (Part == PS(".")) 1636 return PK_Dot; 1637 if (Part == PS("..")) 1638 return PK_DotDot; 1639 if (Part == PS("/")) 1640 return PK_RootSep; 1641 #if defined(_LIBCPP_WIN32API) 1642 if (Part == PS("\\")) 1643 return PK_RootSep; 1644 #endif 1645 return PK_Filename; 1646 } 1647 1648 path path::lexically_normal() const { 1649 if (__pn_.empty()) 1650 return *this; 1651 1652 using PartKindPair = pair<string_view_t, PathPartKind>; 1653 vector<PartKindPair> Parts; 1654 // Guess as to how many elements the path has to avoid reallocating. 1655 Parts.reserve(32); 1656 1657 // Track the total size of the parts as we collect them. This allows the 1658 // resulting path to reserve the correct amount of memory. 1659 size_t NewPathSize = 0; 1660 auto AddPart = [&](PathPartKind K, string_view_t P) { 1661 NewPathSize += P.size(); 1662 Parts.emplace_back(P, K); 1663 }; 1664 auto LastPartKind = [&]() { 1665 if (Parts.empty()) 1666 return PK_None; 1667 return Parts.back().second; 1668 }; 1669 1670 bool MaybeNeedTrailingSep = false; 1671 // Build a stack containing the remaining elements of the path, popping off 1672 // elements which occur before a '..' entry. 1673 for (auto PP = PathParser::CreateBegin(__pn_); PP; ++PP) { 1674 auto Part = *PP; 1675 PathPartKind Kind = ClassifyPathPart(Part); 1676 switch (Kind) { 1677 case PK_Filename: 1678 case PK_RootSep: { 1679 // Add all non-dot and non-dot-dot elements to the stack of elements. 1680 AddPart(Kind, Part); 1681 MaybeNeedTrailingSep = false; 1682 break; 1683 } 1684 case PK_DotDot: { 1685 // Only push a ".." element if there are no elements preceding the "..", 1686 // or if the preceding element is itself "..". 1687 auto LastKind = LastPartKind(); 1688 if (LastKind == PK_Filename) { 1689 NewPathSize -= Parts.back().first.size(); 1690 Parts.pop_back(); 1691 } else if (LastKind != PK_RootSep) 1692 AddPart(PK_DotDot, PS("..")); 1693 MaybeNeedTrailingSep = LastKind == PK_Filename; 1694 break; 1695 } 1696 case PK_Dot: 1697 case PK_TrailingSep: { 1698 MaybeNeedTrailingSep = true; 1699 break; 1700 } 1701 case PK_None: 1702 _LIBCPP_UNREACHABLE(); 1703 } 1704 } 1705 // [fs.path.generic]p6.8: If the path is empty, add a dot. 1706 if (Parts.empty()) 1707 return PS("."); 1708 1709 // [fs.path.generic]p6.7: If the last filename is dot-dot, remove any 1710 // trailing directory-separator. 1711 bool NeedTrailingSep = MaybeNeedTrailingSep && LastPartKind() == PK_Filename; 1712 1713 path Result; 1714 Result.__pn_.reserve(Parts.size() + NewPathSize + NeedTrailingSep); 1715 for (auto& PK : Parts) 1716 Result /= PK.first; 1717 1718 if (NeedTrailingSep) 1719 Result /= PS(""); 1720 1721 Result.make_preferred(); 1722 return Result; 1723 } 1724 1725 static int DetermineLexicalElementCount(PathParser PP) { 1726 int Count = 0; 1727 for (; PP; ++PP) { 1728 auto Elem = *PP; 1729 if (Elem == PS("..")) 1730 --Count; 1731 else if (Elem != PS(".") && Elem != PS("")) 1732 ++Count; 1733 } 1734 return Count; 1735 } 1736 1737 path path::lexically_relative(const path& base) const { 1738 { // perform root-name/root-directory mismatch checks 1739 auto PP = PathParser::CreateBegin(__pn_); 1740 auto PPBase = PathParser::CreateBegin(base.__pn_); 1741 auto CheckIterMismatchAtBase = [&]() { 1742 return PP.State != PPBase.State && 1743 (PP.inRootPath() || PPBase.inRootPath()); 1744 }; 1745 if (PP.inRootName() && PPBase.inRootName()) { 1746 if (*PP != *PPBase) 1747 return {}; 1748 } else if (CheckIterMismatchAtBase()) 1749 return {}; 1750 1751 if (PP.inRootPath()) 1752 ++PP; 1753 if (PPBase.inRootPath()) 1754 ++PPBase; 1755 if (CheckIterMismatchAtBase()) 1756 return {}; 1757 } 1758 1759 // Find the first mismatching element 1760 auto PP = PathParser::CreateBegin(__pn_); 1761 auto PPBase = PathParser::CreateBegin(base.__pn_); 1762 while (PP && PPBase && PP.State == PPBase.State && *PP == *PPBase) { 1763 ++PP; 1764 ++PPBase; 1765 } 1766 1767 // If there is no mismatch, return ".". 1768 if (!PP && !PPBase) 1769 return "."; 1770 1771 // Otherwise, determine the number of elements, 'n', which are not dot or 1772 // dot-dot minus the number of dot-dot elements. 1773 int ElemCount = DetermineLexicalElementCount(PPBase); 1774 if (ElemCount < 0) 1775 return {}; 1776 1777 // if n == 0 and (a == end() || a->empty()), returns path("."); otherwise 1778 if (ElemCount == 0 && (PP.atEnd() || *PP == PS(""))) 1779 return PS("."); 1780 1781 // return a path constructed with 'n' dot-dot elements, followed by the the 1782 // elements of '*this' after the mismatch. 1783 path Result; 1784 // FIXME: Reserve enough room in Result that it won't have to re-allocate. 1785 while (ElemCount--) 1786 Result /= PS(".."); 1787 for (; PP; ++PP) 1788 Result /= *PP; 1789 return Result; 1790 } 1791 1792 //////////////////////////////////////////////////////////////////////////// 1793 // path.comparisons 1794 static int CompareRootName(PathParser *LHS, PathParser *RHS) { 1795 if (!LHS->inRootName() && !RHS->inRootName()) 1796 return 0; 1797 1798 auto GetRootName = [](PathParser *Parser) -> string_view_t { 1799 return Parser->inRootName() ? **Parser : PS(""); 1800 }; 1801 int res = GetRootName(LHS).compare(GetRootName(RHS)); 1802 ConsumeRootName(LHS); 1803 ConsumeRootName(RHS); 1804 return res; 1805 } 1806 1807 static int CompareRootDir(PathParser *LHS, PathParser *RHS) { 1808 if (!LHS->inRootDir() && RHS->inRootDir()) 1809 return -1; 1810 else if (LHS->inRootDir() && !RHS->inRootDir()) 1811 return 1; 1812 else { 1813 ConsumeRootDir(LHS); 1814 ConsumeRootDir(RHS); 1815 return 0; 1816 } 1817 } 1818 1819 static int CompareRelative(PathParser *LHSPtr, PathParser *RHSPtr) { 1820 auto &LHS = *LHSPtr; 1821 auto &RHS = *RHSPtr; 1822 1823 int res; 1824 while (LHS && RHS) { 1825 if ((res = (*LHS).compare(*RHS)) != 0) 1826 return res; 1827 ++LHS; 1828 ++RHS; 1829 } 1830 return 0; 1831 } 1832 1833 static int CompareEndState(PathParser *LHS, PathParser *RHS) { 1834 if (LHS->atEnd() && !RHS->atEnd()) 1835 return -1; 1836 else if (!LHS->atEnd() && RHS->atEnd()) 1837 return 1; 1838 return 0; 1839 } 1840 1841 int path::__compare(string_view_t __s) const { 1842 auto LHS = PathParser::CreateBegin(__pn_); 1843 auto RHS = PathParser::CreateBegin(__s); 1844 int res; 1845 1846 if ((res = CompareRootName(&LHS, &RHS)) != 0) 1847 return res; 1848 1849 if ((res = CompareRootDir(&LHS, &RHS)) != 0) 1850 return res; 1851 1852 if ((res = CompareRelative(&LHS, &RHS)) != 0) 1853 return res; 1854 1855 return CompareEndState(&LHS, &RHS); 1856 } 1857 1858 //////////////////////////////////////////////////////////////////////////// 1859 // path.nonmembers 1860 size_t hash_value(const path& __p) noexcept { 1861 auto PP = PathParser::CreateBegin(__p.native()); 1862 size_t hash_value = 0; 1863 hash<string_view_t> hasher; 1864 while (PP) { 1865 hash_value = __hash_combine(hash_value, hasher(*PP)); 1866 ++PP; 1867 } 1868 return hash_value; 1869 } 1870 1871 //////////////////////////////////////////////////////////////////////////// 1872 // path.itr 1873 path::iterator path::begin() const { 1874 auto PP = PathParser::CreateBegin(__pn_); 1875 iterator it; 1876 it.__path_ptr_ = this; 1877 it.__state_ = static_cast<path::iterator::_ParserState>(PP.State); 1878 it.__entry_ = PP.RawEntry; 1879 it.__stashed_elem_.__assign_view(*PP); 1880 return it; 1881 } 1882 1883 path::iterator path::end() const { 1884 iterator it{}; 1885 it.__state_ = path::iterator::_AtEnd; 1886 it.__path_ptr_ = this; 1887 return it; 1888 } 1889 1890 path::iterator& path::iterator::__increment() { 1891 PathParser PP(__path_ptr_->native(), __entry_, __state_); 1892 ++PP; 1893 __state_ = static_cast<_ParserState>(PP.State); 1894 __entry_ = PP.RawEntry; 1895 __stashed_elem_.__assign_view(*PP); 1896 return *this; 1897 } 1898 1899 path::iterator& path::iterator::__decrement() { 1900 PathParser PP(__path_ptr_->native(), __entry_, __state_); 1901 --PP; 1902 __state_ = static_cast<_ParserState>(PP.State); 1903 __entry_ = PP.RawEntry; 1904 __stashed_elem_.__assign_view(*PP); 1905 return *this; 1906 } 1907 1908 #if defined(_LIBCPP_WIN32API) 1909 //////////////////////////////////////////////////////////////////////////// 1910 // Windows path conversions 1911 size_t __wide_to_char(const wstring &str, char *out, size_t outlen) { 1912 if (str.empty()) 1913 return 0; 1914 ErrorHandler<size_t> err("__wide_to_char", nullptr); 1915 UINT codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP; 1916 BOOL used_default = FALSE; 1917 int ret = WideCharToMultiByte(codepage, 0, str.data(), str.size(), out, 1918 outlen, nullptr, &used_default); 1919 if (ret <= 0 || used_default) 1920 return err.report(errc::illegal_byte_sequence); 1921 return ret; 1922 } 1923 1924 size_t __char_to_wide(const string &str, wchar_t *out, size_t outlen) { 1925 if (str.empty()) 1926 return 0; 1927 ErrorHandler<size_t> err("__char_to_wide", nullptr); 1928 UINT codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP; 1929 int ret = MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, str.data(), 1930 str.size(), out, outlen); 1931 if (ret <= 0) 1932 return err.report(errc::illegal_byte_sequence); 1933 return ret; 1934 } 1935 #endif 1936 1937 1938 /////////////////////////////////////////////////////////////////////////////// 1939 // directory entry definitions 1940 /////////////////////////////////////////////////////////////////////////////// 1941 1942 error_code directory_entry::__do_refresh() noexcept { 1943 __data_.__reset(); 1944 error_code failure_ec; 1945 1946 StatT full_st; 1947 file_status st = detail::posix_lstat(__p_, full_st, &failure_ec); 1948 if (!status_known(st)) { 1949 __data_.__reset(); 1950 return failure_ec; 1951 } 1952 1953 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) { 1954 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink; 1955 __data_.__type_ = st.type(); 1956 __data_.__non_sym_perms_ = st.permissions(); 1957 } else { // we have a symlink 1958 __data_.__sym_perms_ = st.permissions(); 1959 // Get the information about the linked entity. 1960 // Ignore errors from stat, since we don't want errors regarding symlink 1961 // resolution to be reported to the user. 1962 error_code ignored_ec; 1963 st = detail::posix_stat(__p_, full_st, &ignored_ec); 1964 1965 __data_.__type_ = st.type(); 1966 __data_.__non_sym_perms_ = st.permissions(); 1967 1968 // If we failed to resolve the link, then only partially populate the 1969 // cache. 1970 if (!status_known(st)) { 1971 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved; 1972 return error_code{}; 1973 } 1974 // Otherwise, we resolved the link, potentially as not existing. 1975 // That's OK. 1976 __data_.__cache_type_ = directory_entry::_RefreshSymlink; 1977 } 1978 1979 if (_VSTD_FS::is_regular_file(st)) 1980 __data_.__size_ = static_cast<uintmax_t>(full_st.st_size); 1981 1982 if (_VSTD_FS::exists(st)) { 1983 __data_.__nlink_ = static_cast<uintmax_t>(full_st.st_nlink); 1984 1985 // Attempt to extract the mtime, and fail if it's not representable using 1986 // file_time_type. For now we ignore the error, as we'll report it when 1987 // the value is actually used. 1988 error_code ignored_ec; 1989 __data_.__write_time_ = 1990 __extract_last_write_time(__p_, full_st, &ignored_ec); 1991 } 1992 1993 return failure_ec; 1994 } 1995 1996 _LIBCPP_END_NAMESPACE_FILESYSTEM 1997