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