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