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