]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/libc++/src/experimental/filesystem/operations.cpp
Merge libc++ r291274, and update the library Makefile.
[FreeBSD/FreeBSD.git] / contrib / libc++ / src / experimental / filesystem / operations.cpp
1 //===--------------------- filesystem/ops.cpp -----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is dual licensed under the MIT and the University of Illinois Open
6 // Source Licenses. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "experimental/filesystem"
11 #include "iterator"
12 #include "fstream"
13 #include "type_traits"
14 #include "random"  /* for unique_path */
15 #include "cstdlib"
16 #include "climits"
17
18 #include <unistd.h>
19 #include <sys/stat.h>
20 #include <sys/statvfs.h>
21 #include <fcntl.h>  /* values for fchmodat */
22 #if !defined(UTIME_OMIT)
23 #include <sys/time.h> // for ::utimes as used in __last_write_time
24 #endif
25
26 _LIBCPP_BEGIN_NAMESPACE_EXPERIMENTAL_FILESYSTEM
27
28 filesystem_error::~filesystem_error() {}
29
30
31 //                       POSIX HELPERS
32
33 namespace detail { namespace  {
34
35 using value_type = path::value_type;
36 using string_type = path::string_type;
37
38
39
40 inline std::error_code capture_errno() {
41     _LIBCPP_ASSERT(errno, "Expected errno to be non-zero");
42     std::error_code m_ec(errno, std::generic_category());
43     return m_ec;
44 }
45
46 void set_or_throw(std::error_code const& m_ec, std::error_code* ec,
47                   const char* msg, path const& p = {}, path const& p2 = {})
48 {
49     if (ec) {
50         *ec = m_ec;
51     } else {
52         string msg_s("std::experimental::filesystem::");
53         msg_s += msg;
54         __throw_filesystem_error(msg_s, p, p2, m_ec);
55     }
56 }
57
58 void set_or_throw(std::error_code* ec, const char* msg,
59                   path const& p = {}, path const& p2 = {})
60 {
61     return set_or_throw(capture_errno(), ec, msg, p, p2);
62 }
63
64 perms posix_get_perms(const struct ::stat & st) noexcept {
65     return static_cast<perms>(st.st_mode) & perms::mask;
66 }
67
68 ::mode_t posix_convert_perms(perms prms) {
69     return static_cast< ::mode_t>(prms & perms::mask);
70 }
71
72 file_status create_file_status(std::error_code& m_ec, path const& p,
73                                struct ::stat& path_stat,
74                                std::error_code* ec)
75 {
76     if (ec) *ec = m_ec;
77     if (m_ec && (m_ec.value() == ENOENT || m_ec.value() == ENOTDIR)) {
78         return file_status(file_type::not_found);
79     }
80     else if (m_ec) {
81         set_or_throw(m_ec, ec, "posix_stat", p);
82         return file_status(file_type::none);
83     }
84     // else
85
86     file_status fs_tmp;
87     auto const mode = path_stat.st_mode;
88     if      (S_ISLNK(mode))  fs_tmp.type(file_type::symlink);
89     else if (S_ISREG(mode))  fs_tmp.type(file_type::regular);
90     else if (S_ISDIR(mode))  fs_tmp.type(file_type::directory);
91     else if (S_ISBLK(mode))  fs_tmp.type(file_type::block);
92     else if (S_ISCHR(mode))  fs_tmp.type(file_type::character);
93     else if (S_ISFIFO(mode)) fs_tmp.type(file_type::fifo);
94     else if (S_ISSOCK(mode)) fs_tmp.type(file_type::socket);
95     else                     fs_tmp.type(file_type::unknown);
96
97     fs_tmp.permissions(detail::posix_get_perms(path_stat));
98     return fs_tmp;
99 }
100
101 file_status posix_stat(path const & p, struct ::stat& path_stat,
102                        std::error_code* ec)
103 {
104     std::error_code m_ec;
105     if (::stat(p.c_str(), &path_stat) == -1)
106         m_ec = detail::capture_errno();
107     return create_file_status(m_ec, p, path_stat, ec);
108 }
109
110 file_status posix_stat(path const & p, std::error_code* ec) {
111     struct ::stat path_stat;
112     return posix_stat(p, path_stat, ec);
113 }
114
115 file_status posix_lstat(path const & p, struct ::stat & path_stat,
116                         std::error_code* ec)
117 {
118     std::error_code m_ec;
119     if (::lstat(p.c_str(), &path_stat) == -1)
120         m_ec = detail::capture_errno();
121     return create_file_status(m_ec, p, path_stat, ec);
122 }
123
124 file_status posix_lstat(path const & p, std::error_code* ec) {
125     struct ::stat path_stat;
126     return posix_lstat(p, path_stat, ec);
127 }
128
129 bool stat_equivalent(struct ::stat& st1, struct ::stat& st2) {
130     return (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino);
131 }
132
133 //                           DETAIL::MISC
134
135
136 bool copy_file_impl(const path& from, const path& to, perms from_perms,
137                     std::error_code *ec)
138 {
139     std::ifstream in(from.c_str(), std::ios::binary);
140     std::ofstream out(to.c_str(),  std::ios::binary);
141
142     if (in.good() && out.good()) {
143         using InIt = std::istreambuf_iterator<char>;
144         using OutIt = std::ostreambuf_iterator<char>;
145         InIt bin(in);
146         InIt ein;
147         OutIt bout(out);
148         std::copy(bin, ein, bout);
149     }
150     if (out.fail() || in.fail()) {
151         set_or_throw(make_error_code(errc::operation_not_permitted),
152                      ec, "copy_file", from, to);
153         return false;
154     }
155     __permissions(to, from_perms, ec);
156     // TODO what if permissions fails?
157     return true;
158 }
159
160 }} // end namespace detail
161
162 using detail::set_or_throw;
163
164 path __canonical(path const & orig_p, const path& base, std::error_code *ec)
165 {
166     path p = absolute(orig_p, base);
167     char buff[PATH_MAX + 1];
168     char *ret;
169     if ((ret = ::realpath(p.c_str(), buff)) == nullptr) {
170         set_or_throw(ec, "canonical", orig_p, base);
171         return {};
172     }
173     if (ec) ec->clear();
174     return {ret};
175 }
176
177 void __copy(const path& from, const path& to, copy_options options,
178             std::error_code *ec)
179 {
180     const bool sym_status = bool(options &
181         (copy_options::create_symlinks | copy_options::skip_symlinks));
182
183     const bool sym_status2 = bool(options &
184         copy_options::copy_symlinks);
185
186     std::error_code m_ec;
187     struct ::stat f_st = {};
188     const file_status f = sym_status || sym_status2
189                                      ? detail::posix_lstat(from, f_st, &m_ec)
190                                      : detail::posix_stat(from,  f_st, &m_ec);
191     if (m_ec)
192         return set_or_throw(m_ec, ec, "copy", from, to);
193
194     struct ::stat t_st = {};
195     const file_status t = sym_status ? detail::posix_lstat(to, t_st, &m_ec)
196                                      : detail::posix_stat(to, t_st, &m_ec);
197
198     if (not status_known(t))
199         return set_or_throw(m_ec, ec, "copy", from, to);
200
201     if (!exists(f) || is_other(f) || is_other(t)
202         || (is_directory(f) && is_regular_file(t))
203         || detail::stat_equivalent(f_st, t_st))
204     {
205         return set_or_throw(make_error_code(errc::function_not_supported),
206                             ec, "copy", from, to);
207     }
208
209     if (ec) ec->clear();
210
211     if (is_symlink(f)) {
212         if (bool(copy_options::skip_symlinks & options)) {
213             // do nothing
214         } else if (not exists(t)) {
215             __copy_symlink(from, to, ec);
216         } else {
217             set_or_throw(make_error_code(errc::file_exists),
218                          ec, "copy", from, to);
219         }
220         return;
221     }
222     else if (is_regular_file(f)) {
223         if (bool(copy_options::directories_only & options)) {
224             // do nothing
225         }
226         else if (bool(copy_options::create_symlinks & options)) {
227             __create_symlink(from, to, ec);
228         }
229         else if (bool(copy_options::create_hard_links & options)) {
230             __create_hard_link(from, to, ec);
231         }
232         else if (is_directory(t)) {
233             __copy_file(from, to / from.filename(), options, ec);
234         } else {
235             __copy_file(from, to, options, ec);
236         }
237         return;
238     }
239     else if (is_directory(f) && bool(copy_options::create_symlinks & options)) {
240         return set_or_throw(make_error_code(errc::is_a_directory), ec, "copy");
241     }
242     else if (is_directory(f) && (bool(copy_options::recursive & options) ||
243              copy_options::none == options)) {
244
245         if (!exists(t)) {
246             // create directory to with attributes from 'from'.
247             __create_directory(to, from, ec);
248             if (ec && *ec) { return; }
249         }
250         directory_iterator it = ec ? directory_iterator(from, *ec)
251                                    : directory_iterator(from);
252         if (ec && *ec) { return; }
253         std::error_code m_ec;
254         for (; it != directory_iterator(); it.increment(m_ec)) {
255             if (m_ec) return set_or_throw(m_ec, ec, "copy", from, to);
256             __copy(it->path(), to / it->path().filename(),
257                    options | copy_options::__in_recursive_copy, ec);
258             if (ec && *ec) { return; }
259         }
260     }
261 }
262
263
264 bool __copy_file(const path& from, const path& to, copy_options options,
265                  std::error_code *ec)
266 {
267     if (ec) ec->clear();
268
269     std::error_code m_ec;
270     auto from_st = detail::posix_stat(from, &m_ec);
271     if (not is_regular_file(from_st)) {
272         if (not m_ec)
273             m_ec = make_error_code(errc::not_supported);
274         set_or_throw(m_ec, ec, "copy_file", from, to);
275         return false;
276     }
277
278     auto to_st = detail::posix_stat(to, &m_ec);
279     if (!status_known(to_st)) {
280         set_or_throw(m_ec, ec, "copy_file", from, to);
281         return false;
282     }
283
284     const bool to_exists = exists(to_st);
285     if (to_exists && !is_regular_file(to_st)) {
286         set_or_throw(make_error_code(errc::not_supported), ec, "copy_file", from, to);
287         return false;
288     }
289     if (to_exists && bool(copy_options::skip_existing & options)) {
290         return false;
291     }
292     else if (to_exists && bool(copy_options::update_existing & options)) {
293         auto from_time = __last_write_time(from, ec);
294         if (ec && *ec) { return false; }
295         auto to_time = __last_write_time(to, ec);
296         if (ec && *ec) { return false; }
297         if (from_time <= to_time) {
298             return false;
299         }
300         return detail::copy_file_impl(from, to, from_st.permissions(), ec);
301     }
302     else if (!to_exists || bool(copy_options::overwrite_existing & options)) {
303         return detail::copy_file_impl(from, to, from_st.permissions(), ec);
304     }
305     else {
306         set_or_throw(make_error_code(errc::file_exists), ec, "copy", from, to);
307         return false;
308     }
309
310     _LIBCPP_UNREACHABLE();
311 }
312
313 void __copy_symlink(const path& existing_symlink, const path& new_symlink,
314                     std::error_code *ec)
315 {
316     const path real_path(__read_symlink(existing_symlink, ec));
317     if (ec && *ec) { return; }
318     // NOTE: proposal says you should detect if you should call
319     // create_symlink or create_directory_symlink. I don't think this
320     // is needed with POSIX
321     __create_symlink(real_path, new_symlink, ec);
322 }
323
324
325 bool __create_directories(const path& p, std::error_code *ec)
326 {
327     std::error_code m_ec;
328     auto const st = detail::posix_stat(p, &m_ec);
329     if (!status_known(st)) {
330         set_or_throw(m_ec, ec, "create_directories", p);
331         return false;
332     }
333     else if (is_directory(st)) {
334         if (ec) ec->clear();
335         return false;
336     }
337     else if (exists(st)) {
338         set_or_throw(make_error_code(errc::file_exists),
339                      ec, "create_directories", p);
340         return false;
341     }
342
343     const path parent = p.parent_path();
344     if (!parent.empty()) {
345         const file_status parent_st = status(parent, m_ec);
346         if (not status_known(parent_st)) {
347             set_or_throw(m_ec, ec, "create_directories", p);
348             return false;
349         }
350         if (not exists(parent_st)) {
351             __create_directories(parent, ec);
352             if (ec && *ec) { return false; }
353         }
354     }
355     return __create_directory(p, ec);
356 }
357
358 bool __create_directory(const path& p, std::error_code *ec)
359 {
360     if (ec) ec->clear();
361     if (::mkdir(p.c_str(), static_cast<int>(perms::all)) == 0)
362         return true;
363     if (errno != EEXIST || !is_directory(p))
364         set_or_throw(ec, "create_directory", p);
365     return false;
366 }
367
368 bool __create_directory(path const & p, path const & attributes,
369                         std::error_code *ec)
370 {
371     struct ::stat attr_stat;
372     std::error_code mec;
373     auto st = detail::posix_stat(attributes, attr_stat, &mec);
374     if (!status_known(st)) {
375         set_or_throw(mec, ec, "create_directory", p, attributes);
376         return false;
377     }
378     if (ec) ec->clear();
379     if (::mkdir(p.c_str(), attr_stat.st_mode) == 0)
380         return true;
381     if (errno != EEXIST || !is_directory(p))
382         set_or_throw(ec, "create_directory", p, attributes);
383     return false;
384 }
385
386 void __create_directory_symlink(path const & from, path const & to,
387                                 std::error_code *ec){
388     if (::symlink(from.c_str(), to.c_str()) != 0)
389         set_or_throw(ec, "create_directory_symlink", from, to);
390     else if (ec)
391         ec->clear();
392 }
393
394 void __create_hard_link(const path& from, const path& to, std::error_code *ec){
395     if (::link(from.c_str(), to.c_str()) == -1)
396         set_or_throw(ec, "create_hard_link", from, to);
397     else if (ec)
398         ec->clear();
399 }
400
401 void __create_symlink(path const & from, path const & to, std::error_code *ec) {
402
403     if (::symlink(from.c_str(), to.c_str()) == -1)
404         set_or_throw(ec, "create_symlink", from, to);
405     else if (ec)
406         ec->clear();
407 }
408
409 path __current_path(std::error_code *ec) {
410     auto size = ::pathconf(".", _PC_PATH_MAX);
411     _LIBCPP_ASSERT(size >= 0, "pathconf returned a 0 as max size");
412
413     auto buff = std::unique_ptr<char[]>(new char[size + 1]);
414     char* ret;
415     if ((ret = ::getcwd(buff.get(), static_cast<size_t>(size))) == nullptr) {
416         set_or_throw(ec, "current_path");
417         return {};
418     }
419     if (ec) ec->clear();
420     return {buff.get()};
421 }
422
423 void __current_path(const path& p, std::error_code *ec) {
424     if (::chdir(p.c_str()) == -1)
425         set_or_throw(ec, "current_path", p);
426     else if (ec)
427         ec->clear();
428 }
429
430 bool __equivalent(const path& p1, const path& p2, std::error_code *ec)
431 {
432     std::error_code ec1, ec2;
433     struct ::stat st1 = {};
434     struct ::stat st2 = {};
435     auto s1 = detail::posix_stat(p1.native(), st1, &ec1);
436     auto s2 = detail::posix_stat(p2.native(), st2, &ec2);
437
438     if ((!exists(s1) && !exists(s2)) || (is_other(s1) && is_other(s2))) {
439         set_or_throw(make_error_code(errc::not_supported), ec,
440                      "equivalent", p1, p2);
441         return false;
442     }
443     if (ec) ec->clear();
444     return (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino);
445 }
446
447
448 std::uintmax_t __file_size(const path& p, std::error_code *ec)
449 {
450     std::error_code m_ec;
451     struct ::stat st;
452     file_status fst = detail::posix_stat(p, st, &m_ec);
453     if (!exists(fst) || !is_regular_file(fst)) {
454         if (!m_ec)
455             m_ec = make_error_code(errc::not_supported);
456         set_or_throw(m_ec, ec, "file_size", p);
457         return static_cast<uintmax_t>(-1);
458     }
459     // is_regular_file(p) == true
460     if (ec) ec->clear();
461     return static_cast<std::uintmax_t>(st.st_size);
462 }
463
464 std::uintmax_t __hard_link_count(const path& p, std::error_code *ec)
465 {
466     std::error_code m_ec;
467     struct ::stat st;
468     detail::posix_stat(p, st, &m_ec);
469     if (m_ec) {
470         set_or_throw(m_ec, ec, "hard_link_count", p);
471         return static_cast<std::uintmax_t>(-1);
472     }
473     if (ec) ec->clear();
474     return static_cast<std::uintmax_t>(st.st_nlink);
475 }
476
477
478 bool __fs_is_empty(const path& p, std::error_code *ec)
479 {
480     if (ec) ec->clear();
481     std::error_code m_ec;
482     struct ::stat pst;
483     auto st = detail::posix_stat(p, pst, &m_ec);
484     if (m_ec) {
485         set_or_throw(m_ec, ec, "is_empty", p);
486         return false;
487     }
488     else if (!is_directory(st) && !is_regular_file(st)) {
489         m_ec = make_error_code(errc::not_supported);
490         set_or_throw(m_ec, ec, "is_empty");
491         return false;
492     }
493     else if (is_directory(st)) {
494         auto it = ec ? directory_iterator(p, *ec) : directory_iterator(p);
495         if (ec && *ec)
496             return false;
497         return it == directory_iterator{};
498     }
499     else if (is_regular_file(st))
500         return static_cast<std::uintmax_t>(pst.st_size) == 0;
501
502     _LIBCPP_UNREACHABLE();
503 }
504
505
506 namespace detail { namespace {
507
508 using namespace std::chrono;
509
510 template <class CType, class ChronoType>
511 bool checked_set(CType* out, ChronoType time) {
512     using Lim = numeric_limits<CType>;
513     if (time > Lim::max() || time < Lim::min())
514         return false;
515     *out = static_cast<CType>(time);
516     return true;
517 }
518
519 using TimeSpec = struct ::timespec;
520 using StatT = struct ::stat;
521
522 #if defined(__APPLE__)
523 TimeSpec extract_mtime(StatT const& st) { return st.st_mtimespec; }
524 TimeSpec extract_atime(StatT const& st) { return st.st_atimespec; }
525 #else
526 TimeSpec extract_mtime(StatT const& st) { return st.st_mtim; }
527 __attribute__((unused)) // Suppress warning
528 TimeSpec extract_atime(StatT const& st) { return st.st_atim; }
529 #endif
530
531 constexpr auto max_seconds = duration_cast<seconds>(
532     file_time_type::duration::max()).count();
533
534 constexpr auto max_nsec = duration_cast<nanoseconds>(
535     file_time_type::duration::max() - seconds(max_seconds)).count();
536
537 constexpr auto min_seconds = duration_cast<seconds>(
538     file_time_type::duration::min()).count();
539
540 constexpr auto min_nsec_timespec = duration_cast<nanoseconds>(
541     (file_time_type::duration::min() - seconds(min_seconds)) + seconds(1)).count();
542
543 // Static assert that these values properly round trip.
544 static_assert((seconds(min_seconds) + duration_cast<microseconds>(nanoseconds(min_nsec_timespec)))
545                   - duration_cast<microseconds>(seconds(1))
546                   == file_time_type::duration::min(), "");
547
548 constexpr auto max_time_t = numeric_limits<time_t>::max();
549 constexpr auto min_time_t = numeric_limits<time_t>::min();
550
551 #if !defined(__LP64__) && defined(__clang__)
552 #pragma clang diagnostic push
553 #pragma clang diagnostic ignored "-Wtautological-constant-out-of-range-compare"
554 #endif
555
556 _LIBCPP_CONSTEXPR_AFTER_CXX11
557 bool is_representable(TimeSpec const& tm) {
558   if (tm.tv_sec >= 0) {
559     return (tm.tv_sec < max_seconds) ||
560         (tm.tv_sec == max_seconds && tm.tv_nsec <= max_nsec);
561   } else if (tm.tv_sec == (min_seconds - 1)) {
562      return tm.tv_nsec >= min_nsec_timespec;
563   } else {
564     return (tm.tv_sec >= min_seconds);
565   }
566 }
567 #ifndef _LIBCPP_HAS_NO_CXX14_CONSTEXPR
568 #if defined(__LP64__)
569 static_assert(is_representable({max_seconds, max_nsec}), "");
570 static_assert(!is_representable({max_seconds + 1, 0}), "");
571 static_assert(!is_representable({max_seconds, max_nsec + 1}), "");
572 static_assert(!is_representable({max_time_t, 0}), "");
573 static_assert(is_representable({min_seconds, 0}), "");
574 static_assert(is_representable({min_seconds - 1, min_nsec_timespec}), "");
575 static_assert(is_representable({min_seconds - 1, min_nsec_timespec + 1}), "");
576 static_assert(!is_representable({min_seconds - 1, min_nsec_timespec - 1}), "");
577 static_assert(!is_representable({min_time_t, 999999999}), "");
578 #else
579 static_assert(is_representable({max_time_t, 999999999}), "");
580 static_assert(is_representable({max_time_t, 1000000000}), "");
581 static_assert(is_representable({min_time_t, 0}), "");
582 #endif
583 #endif
584
585 _LIBCPP_CONSTEXPR_AFTER_CXX11
586 bool is_representable(file_time_type const& tm) {
587   auto secs = duration_cast<seconds>(tm.time_since_epoch());
588   auto nsecs = duration_cast<nanoseconds>(tm.time_since_epoch() - secs);
589   if (nsecs.count() < 0) {
590     secs = secs +  seconds(1);
591     nsecs = nsecs + seconds(1);
592   }
593   using TLim = numeric_limits<time_t>;
594   if (secs.count() >= 0)
595     return secs.count() <= TLim::max();
596   return secs.count() >= TLim::min();
597 }
598 #ifndef _LIBCPP_HAS_NO_CXX14_CONSTEXPR
599 #if defined(__LP64__)
600 static_assert(is_representable(file_time_type::max()), "");
601 static_assert(is_representable(file_time_type::min()), "");
602 #else
603 static_assert(!is_representable(file_time_type::max()), "");
604 static_assert(!is_representable(file_time_type::min()), "");
605 static_assert(is_representable(file_time_type(seconds(max_time_t))), "");
606 static_assert(is_representable(file_time_type(seconds(min_time_t))), "");
607 #endif
608 #endif
609
610 _LIBCPP_CONSTEXPR_AFTER_CXX11
611 file_time_type convert_timespec(TimeSpec const& tm) {
612   auto adj_msec = duration_cast<microseconds>(nanoseconds(tm.tv_nsec));
613   if (tm.tv_sec >= 0) {
614     auto Dur = seconds(tm.tv_sec) + microseconds(adj_msec);
615     return file_time_type(Dur);
616   } else if (duration_cast<microseconds>(nanoseconds(tm.tv_nsec)).count() == 0) {
617     return file_time_type(seconds(tm.tv_sec));
618   } else { // tm.tv_sec < 0
619     auto adj_subsec = duration_cast<microseconds>(seconds(1) - nanoseconds(tm.tv_nsec));
620     auto Dur = seconds(tm.tv_sec + 1) - adj_subsec;
621     return file_time_type(Dur);
622   }
623 }
624 #ifndef _LIBCPP_HAS_NO_CXX14_CONSTEXPR
625 #if defined(__LP64__)
626 static_assert(convert_timespec({max_seconds, max_nsec}) == file_time_type::max(), "");
627 static_assert(convert_timespec({max_seconds, max_nsec - 1}) < file_time_type::max(), "");
628 static_assert(convert_timespec({max_seconds - 1, 999999999}) < file_time_type::max(), "");
629 static_assert(convert_timespec({min_seconds - 1, min_nsec_timespec}) == file_time_type::min(), "");
630 static_assert(convert_timespec({min_seconds - 1, min_nsec_timespec + 1}) > file_time_type::min(), "");
631 static_assert(convert_timespec({min_seconds , 0}) > file_time_type::min(), "");
632 #else
633 // FIXME add tests for 32 bit builds
634 #endif
635 #endif
636
637 #if !defined(__LP64__) && defined(__clang__)
638 #pragma clang diagnostic pop
639 #endif
640
641 template <class SubSecDurT, class SubSecT>
642 bool set_times_checked(time_t* sec_out, SubSecT* subsec_out, file_time_type tp) {
643     using namespace chrono;
644     auto dur = tp.time_since_epoch();
645     auto sec_dur = duration_cast<seconds>(dur);
646     auto subsec_dur = duration_cast<SubSecDurT>(dur - sec_dur);
647     // The tv_nsec and tv_usec fields must not be negative so adjust accordingly
648     if (subsec_dur.count() < 0) {
649         if (sec_dur.count() > min_seconds) {
650             sec_dur -= seconds(1);
651             subsec_dur += seconds(1);
652         } else {
653             subsec_dur = SubSecDurT::zero();
654         }
655     }
656     return checked_set(sec_out, sec_dur.count())
657         && checked_set(subsec_out, subsec_dur.count());
658 }
659
660 }} // end namespace detail
661
662 file_time_type __last_write_time(const path& p, std::error_code *ec)
663 {
664     using namespace ::std::chrono;
665     std::error_code m_ec;
666     struct ::stat st;
667     detail::posix_stat(p, st, &m_ec);
668     if (m_ec) {
669         set_or_throw(m_ec, ec, "last_write_time", p);
670         return file_time_type::min();
671     }
672     if (ec) ec->clear();
673     auto ts = detail::extract_mtime(st);
674     if (!detail::is_representable(ts)) {
675         set_or_throw(error_code(EOVERFLOW, generic_category()), ec,
676                      "last_write_time", p);
677         return file_time_type::min();
678     }
679     return detail::convert_timespec(ts);
680 }
681
682 void __last_write_time(const path& p, file_time_type new_time,
683                        std::error_code *ec)
684 {
685     using namespace std::chrono;
686     std::error_code m_ec;
687
688     // We can use the presence of UTIME_OMIT to detect platforms that do not
689     // provide utimensat.
690 #if !defined(UTIME_OMIT)
691     // This implementation has a race condition between determining the
692     // last access time and attempting to set it to the same value using
693     // ::utimes
694     struct ::stat st;
695     file_status fst = detail::posix_stat(p, st, &m_ec);
696     if (m_ec && !status_known(fst)) {
697         set_or_throw(m_ec, ec, "last_write_time", p);
698         return;
699     }
700     auto atime = detail::extract_atime(st);
701     struct ::timeval tbuf[2];
702     tbuf[0].tv_sec = atime.tv_sec;
703     tbuf[0].tv_usec = duration_cast<microseconds>(nanoseconds(atime.tv_nsec)).count();
704     const bool overflowed = !detail::set_times_checked<microseconds>(
705         &tbuf[1].tv_sec, &tbuf[1].tv_usec, new_time);
706
707     if (overflowed) {
708         set_or_throw(make_error_code(errc::invalid_argument), ec,
709                      "last_write_time", p);
710         return;
711     }
712     if (::utimes(p.c_str(), tbuf) == -1) {
713         m_ec = detail::capture_errno();
714     }
715 #else
716     struct ::timespec tbuf[2];
717     tbuf[0].tv_sec = 0;
718     tbuf[0].tv_nsec = UTIME_OMIT;
719
720     const bool overflowed = !detail::set_times_checked<nanoseconds>(
721         &tbuf[1].tv_sec, &tbuf[1].tv_nsec, new_time);
722     if (overflowed) {
723         set_or_throw(make_error_code(errc::invalid_argument),
724             ec, "last_write_time", p);
725         return;
726     }
727     if (::utimensat(AT_FDCWD, p.c_str(), tbuf, 0) == -1) {
728         m_ec = detail::capture_errno();
729     }
730 #endif
731     if (m_ec)
732         set_or_throw(m_ec, ec, "last_write_time", p);
733     else if (ec)
734         ec->clear();
735 }
736
737
738 void __permissions(const path& p, perms prms, std::error_code *ec)
739 {
740
741     const bool resolve_symlinks = !bool(perms::symlink_nofollow & prms);
742     const bool add_perms = bool(perms::add_perms & prms);
743     const bool remove_perms = bool(perms::remove_perms & prms);
744     _LIBCPP_ASSERT(!(add_perms && remove_perms),
745                    "Both add_perms and remove_perms are set");
746
747     bool set_sym_perms = false;
748     prms &= perms::mask;
749     if (!resolve_symlinks || (add_perms || remove_perms)) {
750         std::error_code m_ec;
751         file_status st = resolve_symlinks ? detail::posix_stat(p, &m_ec)
752                                           : detail::posix_lstat(p, &m_ec);
753         set_sym_perms = is_symlink(st);
754         if (m_ec) return set_or_throw(m_ec, ec, "permissions", p);
755         _LIBCPP_ASSERT(st.permissions() != perms::unknown,
756                        "Permissions unexpectedly unknown");
757         if (add_perms)
758             prms |= st.permissions();
759         else if (remove_perms)
760            prms = st.permissions() & ~prms;
761     }
762     const auto real_perms = detail::posix_convert_perms(prms);
763
764 # if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD)
765     const int flags = set_sym_perms ? AT_SYMLINK_NOFOLLOW : 0;
766     if (::fchmodat(AT_FDCWD, p.c_str(), real_perms, flags) == -1) {
767         return set_or_throw(ec, "permissions", p);
768     }
769 # else
770     if (set_sym_perms)
771         return set_or_throw(make_error_code(errc::operation_not_supported),
772                             ec, "permissions", p);
773     if (::chmod(p.c_str(), real_perms) == -1) {
774         return set_or_throw(ec, "permissions", p);
775     }
776 # endif
777     if (ec) ec->clear();
778 }
779
780
781 path __read_symlink(const path& p, std::error_code *ec) {
782     char buff[PATH_MAX + 1];
783     std::error_code m_ec;
784     ::ssize_t ret;
785     if ((ret = ::readlink(p.c_str(), buff, PATH_MAX)) == -1) {
786         set_or_throw(ec, "read_symlink", p);
787         return {};
788     }
789     _LIBCPP_ASSERT(ret <= PATH_MAX, "TODO");
790     _LIBCPP_ASSERT(ret > 0, "TODO");
791     if (ec) ec->clear();
792     buff[ret] = 0;
793     return {buff};
794 }
795
796
797 bool __remove(const path& p, std::error_code *ec) {
798     if (ec) ec->clear();
799     if (::remove(p.c_str()) == -1) {
800         set_or_throw(ec, "remove", p);
801         return false;
802     }
803     return true;
804 }
805
806 namespace {
807
808 std::uintmax_t remove_all_impl(path const & p, std::error_code& ec)
809 {
810     const auto npos = static_cast<std::uintmax_t>(-1);
811     const file_status st = __symlink_status(p, &ec);
812     if (ec) return npos;
813      std::uintmax_t count = 1;
814     if (is_directory(st)) {
815         for (directory_iterator it(p, ec); !ec && it != directory_iterator();
816              it.increment(ec)) {
817             auto other_count = remove_all_impl(it->path(), ec);
818             if (ec) return npos;
819             count += other_count;
820         }
821         if (ec) return npos;
822     }
823     if (!__remove(p, &ec)) return npos;
824     return count;
825 }
826
827 } // end namespace
828
829 std::uintmax_t __remove_all(const path& p, std::error_code *ec) {
830     std::error_code mec;
831     auto count = remove_all_impl(p, mec);
832     if (mec) {
833         set_or_throw(mec, ec, "remove_all", p);
834         return static_cast<std::uintmax_t>(-1);
835     }
836     if (ec) ec->clear();
837     return count;
838 }
839
840 void __rename(const path& from, const path& to, std::error_code *ec) {
841     if (::rename(from.c_str(), to.c_str()) == -1)
842         set_or_throw(ec, "rename", from, to);
843     else if (ec)
844         ec->clear();
845 }
846
847 void __resize_file(const path& p, std::uintmax_t size, std::error_code *ec) {
848     if (::truncate(p.c_str(), static_cast<long>(size)) == -1)
849         set_or_throw(ec, "resize_file", p);
850     else if (ec)
851         ec->clear();
852 }
853
854 space_info __space(const path& p, std::error_code *ec) {
855     space_info si;
856     struct statvfs m_svfs = {};
857     if (::statvfs(p.c_str(), &m_svfs) == -1)  {
858         set_or_throw(ec, "space", p);
859         si.capacity = si.free = si.available =
860             static_cast<std::uintmax_t>(-1);
861         return si;
862     }
863     if (ec) ec->clear();
864     // Multiply with overflow checking.
865     auto do_mult = [&](std::uintmax_t& out, std::uintmax_t other) {
866       out = other * m_svfs.f_frsize;
867       if (other == 0 || out / other != m_svfs.f_frsize)
868           out = static_cast<std::uintmax_t>(-1);
869     };
870     do_mult(si.capacity, m_svfs.f_blocks);
871     do_mult(si.free, m_svfs.f_bfree);
872     do_mult(si.available, m_svfs.f_bavail);
873     return si;
874 }
875
876 file_status __status(const path& p, std::error_code *ec) {
877     return detail::posix_stat(p, ec);
878 }
879
880 file_status __symlink_status(const path& p, std::error_code *ec) {
881     return detail::posix_lstat(p, ec);
882 }
883
884 path __system_complete(const path& p, std::error_code *ec) {
885     if (ec) ec->clear();
886     return absolute(p, current_path());
887 }
888
889 path __temp_directory_path(std::error_code *ec) {
890     const char* env_paths[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
891     const char* ret = nullptr;
892     for (auto & ep : env_paths)  {
893         if ((ret = std::getenv(ep)))
894             break;
895     }
896     path p(ret ? ret : "/tmp");
897     std::error_code m_ec;
898     if (is_directory(p, m_ec)) {
899         if (ec) ec->clear();
900         return p;
901     }
902     if (!m_ec || m_ec == make_error_code(errc::no_such_file_or_directory))
903         m_ec = make_error_code(errc::not_a_directory);
904     set_or_throw(m_ec, ec, "temp_directory_path");
905     return {};
906 }
907
908 // An absolute path is composed according to the table in [fs.op.absolute].
909 path absolute(const path& p, const path& base) {
910     auto root_name = p.root_name();
911     auto root_dir = p.root_directory();
912
913     if (!root_name.empty() && !root_dir.empty())
914       return p;
915
916     auto abs_base = base.is_absolute() ? base : absolute(base);
917
918     /* !has_root_name && !has_root_dir */
919     if (root_name.empty() && root_dir.empty())
920     {
921       return abs_base / p;
922     }
923     else if (!root_name.empty()) /* has_root_name && !has_root_dir */
924     {
925       return  root_name / abs_base.root_directory()
926               /
927               abs_base.relative_path() / p.relative_path();
928     }
929     else /* !has_root_name && has_root_dir */
930     {
931       if (abs_base.has_root_name())
932         return abs_base.root_name() / p;
933       // else p is absolute,  return outside of block
934     }
935     return p;
936 }
937
938 _LIBCPP_END_NAMESPACE_EXPERIMENTAL_FILESYSTEM