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