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