1 //===----------------------------------------------------------------------===////
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===////
9 #ifndef FILESYSTEM_COMMON_H
10 #define FILESYSTEM_COMMON_H
21 #include <sys/statvfs.h>
22 #include <sys/time.h> // for ::utimes as used in __last_write_time
23 #include <fcntl.h> /* values for fchmodat */
25 #include "../include/apple_availability.h"
27 #if !defined(__APPLE__)
28 // We can use the presence of UTIME_OMIT to detect platforms that provide
30 #if defined(UTIME_OMIT)
31 #define _LIBCPP_USE_UTIMENSAT
36 #pragma GCC diagnostic push
37 #pragma GCC diagnostic ignored "-Wunused-function"
40 _LIBCPP_BEGIN_NAMESPACE_FILESYSTEM
45 static string format_string_imp(const char* msg, ...) {
46 // we might need a second shot at this, so pre-emptivly make a copy
50 GuardVAList(va_list& target) : target(target), active(true) {}
63 GuardVAList args_guard(args);
66 va_copy(args_cp, args);
67 GuardVAList args_copy_guard(args_cp);
71 array<char, 256> local_buff;
72 size_t size_with_null = local_buff.size();
73 auto ret = ::vsnprintf(local_buff.data(), size_with_null, msg, args_cp);
75 args_copy_guard.clear();
77 // handle empty expansion
80 if (static_cast<size_t>(ret) < size_with_null) {
81 result.assign(local_buff.data(), static_cast<size_t>(ret));
85 // we did not provide a long enough buffer on our first attempt. The
86 // return value is the number of bytes (excluding the null byte) that are
87 // needed for formatting.
88 size_with_null = static_cast<size_t>(ret) + 1;
89 result.__resize_default_init(size_with_null - 1);
90 ret = ::vsnprintf(&result[0], size_with_null, msg, args);
91 _LIBCPP_ASSERT(static_cast<size_t>(ret) == (size_with_null - 1), "TODO");
96 const char* unwrap(string const& s) { return s.c_str(); }
97 const char* unwrap(path const& p) { return p.native().c_str(); }
99 Arg const& unwrap(Arg const& a) {
100 static_assert(!is_class<Arg>::value, "cannot pass class here");
104 template <class... Args>
105 string format_string(const char* fmt, Args const&... args) {
106 return format_string_imp(fmt, unwrap(args)...);
109 error_code capture_errno() {
110 _LIBCPP_ASSERT(errno, "Expected errno to be non-zero");
111 return error_code(errno, generic_category());
117 _LIBCPP_CONSTEXPR_AFTER_CXX11 void error_value<void>() {}
119 bool error_value<bool>() {
123 uintmax_t error_value<uintmax_t>() {
124 return uintmax_t(-1);
127 _LIBCPP_CONSTEXPR_AFTER_CXX11 file_time_type error_value<file_time_type>() {
128 return file_time_type::min();
131 path error_value<path>() {
136 struct ErrorHandler {
137 const char* func_name;
138 error_code* ec = nullptr;
139 const path* p1 = nullptr;
140 const path* p2 = nullptr;
142 ErrorHandler(const char* fname, error_code* ec, const path* p1 = nullptr,
143 const path* p2 = nullptr)
144 : func_name(fname), ec(ec), p1(p1), p2(p2) {
149 T report(const error_code& m_ec) const {
152 return error_value<T>();
154 string what = string("in ") + func_name;
155 switch (bool(p1) + bool(p2)) {
157 __throw_filesystem_error(what, m_ec);
159 __throw_filesystem_error(what, *p1, m_ec);
161 __throw_filesystem_error(what, *p1, *p2, m_ec);
163 _LIBCPP_UNREACHABLE();
166 template <class... Args>
167 T report(const error_code& m_ec, const char* msg, Args const&... args) const {
170 return error_value<T>();
173 string("in ") + func_name + ": " + format_string(msg, args...);
174 switch (bool(p1) + bool(p2)) {
176 __throw_filesystem_error(what, m_ec);
178 __throw_filesystem_error(what, *p1, m_ec);
180 __throw_filesystem_error(what, *p1, *p2, m_ec);
182 _LIBCPP_UNREACHABLE();
185 T report(errc const& err) const { return report(make_error_code(err)); }
187 template <class... Args>
188 T report(errc const& err, const char* msg, Args const&... args) const {
189 return report(make_error_code(err), msg, args...);
193 ErrorHandler(ErrorHandler const&) = delete;
194 ErrorHandler& operator=(ErrorHandler const&) = delete;
197 using chrono::duration;
198 using chrono::duration_cast;
200 using TimeSpec = struct ::timespec;
201 using StatT = struct ::stat;
203 template <class FileTimeT, class TimeT,
204 bool IsFloat = is_floating_point<typename FileTimeT::rep>::value>
205 struct time_util_base {
206 using rep = typename FileTimeT::rep;
207 using fs_duration = typename FileTimeT::duration;
208 using fs_seconds = duration<rep>;
209 using fs_nanoseconds = duration<rep, nano>;
210 using fs_microseconds = duration<rep, micro>;
212 static constexpr rep max_seconds =
213 duration_cast<fs_seconds>(FileTimeT::duration::max()).count();
215 static constexpr rep max_nsec =
216 duration_cast<fs_nanoseconds>(FileTimeT::duration::max() -
217 fs_seconds(max_seconds))
220 static constexpr rep min_seconds =
221 duration_cast<fs_seconds>(FileTimeT::duration::min()).count();
223 static constexpr rep min_nsec_timespec =
224 duration_cast<fs_nanoseconds>(
225 (FileTimeT::duration::min() - fs_seconds(min_seconds)) +
230 #if _LIBCPP_STD_VER > 11 && !defined(_LIBCPP_HAS_NO_CXX14_CONSTEXPR)
231 static constexpr fs_duration get_min_nsecs() {
232 return duration_cast<fs_duration>(
233 fs_nanoseconds(min_nsec_timespec) -
234 duration_cast<fs_nanoseconds>(fs_seconds(1)));
236 // Static assert that these values properly round trip.
237 static_assert(fs_seconds(min_seconds) + get_min_nsecs() ==
238 FileTimeT::duration::min(),
239 "value doesn't roundtrip");
241 static constexpr bool check_range() {
242 // This kinda sucks, but it's what happens when we don't have __int128_t.
243 if (sizeof(TimeT) == sizeof(rep)) {
244 typedef duration<long long, ratio<3600 * 24 * 365> > Years;
245 return duration_cast<Years>(fs_seconds(max_seconds)) > Years(250) &&
246 duration_cast<Years>(fs_seconds(min_seconds)) < Years(-250);
248 return max_seconds >= numeric_limits<TimeT>::max() &&
249 min_seconds <= numeric_limits<TimeT>::min();
251 static_assert(check_range(), "the representable range is unacceptable small");
255 template <class FileTimeT, class TimeT>
256 struct time_util_base<FileTimeT, TimeT, true> {
257 using rep = typename FileTimeT::rep;
258 using fs_duration = typename FileTimeT::duration;
259 using fs_seconds = duration<rep>;
260 using fs_nanoseconds = duration<rep, nano>;
261 using fs_microseconds = duration<rep, micro>;
263 static const rep max_seconds;
264 static const rep max_nsec;
265 static const rep min_seconds;
266 static const rep min_nsec_timespec;
269 template <class FileTimeT, class TimeT>
270 const typename FileTimeT::rep
271 time_util_base<FileTimeT, TimeT, true>::max_seconds =
272 duration_cast<fs_seconds>(FileTimeT::duration::max()).count();
274 template <class FileTimeT, class TimeT>
275 const typename FileTimeT::rep time_util_base<FileTimeT, TimeT, true>::max_nsec =
276 duration_cast<fs_nanoseconds>(FileTimeT::duration::max() -
277 fs_seconds(max_seconds))
280 template <class FileTimeT, class TimeT>
281 const typename FileTimeT::rep
282 time_util_base<FileTimeT, TimeT, true>::min_seconds =
283 duration_cast<fs_seconds>(FileTimeT::duration::min()).count();
285 template <class FileTimeT, class TimeT>
286 const typename FileTimeT::rep
287 time_util_base<FileTimeT, TimeT, true>::min_nsec_timespec =
288 duration_cast<fs_nanoseconds>((FileTimeT::duration::min() -
289 fs_seconds(min_seconds)) +
293 template <class FileTimeT, class TimeT, class TimeSpecT>
294 struct time_util : time_util_base<FileTimeT, TimeT> {
295 using Base = time_util_base<FileTimeT, TimeT>;
296 using Base::max_nsec;
297 using Base::max_seconds;
298 using Base::min_nsec_timespec;
299 using Base::min_seconds;
301 using typename Base::fs_duration;
302 using typename Base::fs_microseconds;
303 using typename Base::fs_nanoseconds;
304 using typename Base::fs_seconds;
307 template <class CType, class ChronoType>
308 static _LIBCPP_CONSTEXPR_AFTER_CXX11 bool checked_set(CType* out,
310 using Lim = numeric_limits<CType>;
311 if (time > Lim::max() || time < Lim::min())
313 *out = static_cast<CType>(time);
317 static _LIBCPP_CONSTEXPR_AFTER_CXX11 bool is_representable(TimeSpecT tm) {
318 if (tm.tv_sec >= 0) {
319 return tm.tv_sec < max_seconds ||
320 (tm.tv_sec == max_seconds && tm.tv_nsec <= max_nsec);
321 } else if (tm.tv_sec == (min_seconds - 1)) {
322 return tm.tv_nsec >= min_nsec_timespec;
324 return tm.tv_sec >= min_seconds;
328 static _LIBCPP_CONSTEXPR_AFTER_CXX11 bool is_representable(FileTimeT tm) {
329 auto secs = duration_cast<fs_seconds>(tm.time_since_epoch());
330 auto nsecs = duration_cast<fs_nanoseconds>(tm.time_since_epoch() - secs);
331 if (nsecs.count() < 0) {
332 secs = secs + fs_seconds(1);
333 nsecs = nsecs + fs_seconds(1);
335 using TLim = numeric_limits<TimeT>;
336 if (secs.count() >= 0)
337 return secs.count() <= TLim::max();
338 return secs.count() >= TLim::min();
341 static _LIBCPP_CONSTEXPR_AFTER_CXX11 FileTimeT
342 convert_from_timespec(TimeSpecT tm) {
343 if (tm.tv_sec >= 0 || tm.tv_nsec == 0) {
344 return FileTimeT(fs_seconds(tm.tv_sec) +
345 duration_cast<fs_duration>(fs_nanoseconds(tm.tv_nsec)));
346 } else { // tm.tv_sec < 0
347 auto adj_subsec = duration_cast<fs_duration>(fs_seconds(1) -
348 fs_nanoseconds(tm.tv_nsec));
349 auto Dur = fs_seconds(tm.tv_sec + 1) - adj_subsec;
350 return FileTimeT(Dur);
354 template <class SubSecT>
355 static _LIBCPP_CONSTEXPR_AFTER_CXX11 bool
356 set_times_checked(TimeT* sec_out, SubSecT* subsec_out, FileTimeT tp) {
357 auto dur = tp.time_since_epoch();
358 auto sec_dur = duration_cast<fs_seconds>(dur);
359 auto subsec_dur = duration_cast<fs_nanoseconds>(dur - sec_dur);
360 // The tv_nsec and tv_usec fields must not be negative so adjust accordingly
361 if (subsec_dur.count() < 0) {
362 if (sec_dur.count() > min_seconds) {
363 sec_dur = sec_dur - fs_seconds(1);
364 subsec_dur = subsec_dur + fs_seconds(1);
366 subsec_dur = fs_nanoseconds::zero();
369 return checked_set(sec_out, sec_dur.count()) &&
370 checked_set(subsec_out, subsec_dur.count());
372 static _LIBCPP_CONSTEXPR_AFTER_CXX11 bool convert_to_timespec(TimeSpecT& dest,
374 if (!is_representable(tp))
376 return set_times_checked(&dest.tv_sec, &dest.tv_nsec, tp);
380 using fs_time = time_util<file_time_type, time_t, TimeSpec>;
382 #if defined(__APPLE__)
383 TimeSpec extract_mtime(StatT const& st) { return st.st_mtimespec; }
384 TimeSpec extract_atime(StatT const& st) { return st.st_atimespec; }
386 TimeSpec extract_mtime(StatT const& st) { return st.st_mtim; }
387 TimeSpec extract_atime(StatT const& st) { return st.st_atim; }
390 // allow the utimes implementation to compile even it we're not going
393 bool posix_utimes(const path& p, std::array<TimeSpec, 2> const& TS,
395 using namespace chrono;
396 auto Convert = [](long nsec) {
397 using int_type = decltype(std::declval< ::timeval>().tv_usec);
398 auto dur = duration_cast<microseconds>(nanoseconds(nsec)).count();
399 return static_cast<int_type>(dur);
401 struct ::timeval ConvertedTS[2] = {{TS[0].tv_sec, Convert(TS[0].tv_nsec)},
402 {TS[1].tv_sec, Convert(TS[1].tv_nsec)}};
403 if (::utimes(p.c_str(), ConvertedTS) == -1) {
404 ec = capture_errno();
410 #if defined(_LIBCPP_USE_UTIMENSAT)
411 bool posix_utimensat(const path& p, std::array<TimeSpec, 2> const& TS,
413 if (::utimensat(AT_FDCWD, p.c_str(), TS.data(), 0) == -1) {
414 ec = capture_errno();
421 bool set_file_times(const path& p, std::array<TimeSpec, 2> const& TS,
423 #if !defined(_LIBCPP_USE_UTIMENSAT)
424 return posix_utimes(p, TS, ec);
426 return posix_utimensat(p, TS, ec);
431 } // end namespace detail
433 _LIBCPP_END_NAMESPACE_FILESYSTEM
435 #endif // FILESYSTEM_COMMON_H