1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include <__config>
10#include <__system_error/throw_system_error.h>
11#include <cerrno>
12#include <chrono>
13#include <filesystem>
14#include <ratio>
15#include <time.h>
16
17#if defined(_LIBCPP_WIN32API)
18# include "time_utils.h"
19#endif
20
21#if defined(_LIBCPP_WIN32API)
22# define WIN32_LEAN_AND_MEAN
23# define NOMINMAX
24# include <windows.h>
25#endif
26
27#if __has_include(<unistd.h>)
28# include <unistd.h> // _POSIX_TIMERS
29#endif
30
31#if __has_include(<sys/time.h>)
32# include <sys/time.h> // for gettimeofday and timeval
33#endif
34
35#if _LIBCPP_LIBC_LLVM_LIBC
36# define _LIBCPP_HAS_TIMESPEC_GET
37#endif
38
39#if defined(__APPLE__) || defined(__gnu_hurd__) || defined(__AMDGPU__) || defined(__NVPTX__) || \
40 (defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0)
41# define _LIBCPP_HAS_CLOCK_GETTIME
42#endif
43
44_LIBCPP_BEGIN_NAMESPACE_FILESYSTEM
45_LIBCPP_BEGIN_EXPLICIT_ABI_ANNOTATIONS
46
47_LIBCPP_DIAGNOSTIC_PUSH
48_LIBCPP_CLANG_DIAGNOSTIC_IGNORED("-Wdeprecated")
49const bool _FilesystemClock::is_steady;
50_LIBCPP_DIAGNOSTIC_POP
51
52_FilesystemClock::time_point _FilesystemClock::now() noexcept {
53 typedef chrono::duration<rep> __secs;
54#if defined(_LIBCPP_WIN32API)
55 typedef chrono::duration<rep, nano> __nsecs;
56 FILETIME time;
57 GetSystemTimeAsFileTime(&time);
58 detail::TimeSpec tp = detail::filetime_to_timespec(time);
59 return time_point(__secs(tp.tv_sec) + chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
60#elif defined(_LIBCPP_HAS_TIMESPEC_GET)
61 typedef chrono::duration<rep, nano> __nsecs;
62 struct timespec ts;
63 if (timespec_get(&ts, TIME_UTC) != TIME_UTC)
64 std::__throw_system_error(errno, "timespec_get(TIME_UTC) failed");
65 return time_point(__secs(ts.tv_sec) + chrono::duration_cast<duration>(__nsecs(ts.tv_nsec)));
66#elif defined(_LIBCPP_HAS_CLOCK_GETTIME)
67 typedef chrono::duration<rep, nano> __nsecs;
68 struct timespec tp;
69 if (0 != clock_gettime(CLOCK_REALTIME, tp: &tp))
70 std::__throw_system_error(errno, what_arg: "clock_gettime(CLOCK_REALTIME) failed");
71 return time_point(__secs(tp.tv_sec) + chrono::duration_cast<duration>(fd: __nsecs(tp.tv_nsec)));
72#else
73 typedef chrono::duration<rep, micro> __microsecs;
74 timeval tv;
75 gettimeofday(&tv, 0);
76 return time_point(__secs(tv.tv_sec) + __microsecs(tv.tv_usec));
77#endif
78}
79
80_LIBCPP_END_EXPLICIT_ABI_ANNOTATIONS
81_LIBCPP_END_NAMESPACE_FILESYSTEM
82