blob: 9abef1a5e5b8c8a152ce18703dee94bf16b0101c [file]
/*
Copyright (c) 2026 mingw-w64 project
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#define WINPTHREAD_TIME_DECL WINPTHREAD_API
#include "misc.h"
#include <assert.h>
#include <errno.h>
#include <stdint.h>
#include <time.h>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
/**
* File Summary:
*
* This file contains all time-related definitions used by the library,
* as well as public functions declared in pthread_time.h.
*/
/**
* Reference:
*
* nanosleep():
* <https://pubs.opengroup.org/onlinepubs/9799919799.2024edition/functions/nanosleep.html>
*
* clock_getres(), clock_gettime(), clock_settime():
* <https://pubs.opengroup.org/onlinepubs/9799919799.2024edition/functions/clock_getres.html>
*
* clock_nanosleep():
* <https://pubs.opengroup.org/onlinepubs/9799919799.2024edition/functions/clock_nanosleep.html>
*
* clock_getcpuclockid():
* <https://pubs.opengroup.org/onlinepubs/9799919799.2024edition/functions/clock_getcpuclockid.html>
*
* This following functions are not implemented:
*
* - clock_getcpuclockid()
*/
#define POW10_3 1000
#define POW10_4 10000
#define POW10_6 1000000
#define POW10_7 10000000
#define POW10_9 1000000000
/**
* This is the maximum amount of milliseconds `nanosleep` can sleep at a time.
*/
#define MAX_SLEEP_IN_MS (INFINITE - 1)
/**
* Number of 100ns intervals between the beginning of the Windows epoch
* (Jan. 1, 1601) and the Unix epoch (Jan. 1, 1970)
*/
#define DELTA_EPOCH_IN_100NS INT64_C(116444736000000000)
/**
* This is the maximum `FILETIME` value that can be passed to
* `FileTimeToSystemTime`.
*/
#define FILETIME_TO_SYSTEMTIME_MAX UINT64_C(0x7FFFFFFFFFFFFFFF)
/*******************************************************************************
* In order to provide the best coverage in terms of backward compatibility
* and feature support, we lookup functions which may not be available on older
* Windows versions at runtime, and use them if they are available.
*
* If some function is not available, we provide a simple replacement or stub.
*/
#if WINPTHREADS_WINNT < WINPTHREADS_WINNT_WIN8
#define RUNTIME_CHECKS
#endif
/**
* Function type corresponding to `GetProcessTimes` and `GetThreadTimes`.
*/
typedef BOOL (WINAPI *FuncGetTimes) (HANDLE, FILETIME *, FILETIME *, FILETIME *, FILETIME *);
/**
* Function type corresponding to `GetSystemTimeAsFileTime` and
* `GetSystemTimePreciseAsFileTime`.
*/
typedef VOID (WINAPI *FuncGetSystemTimeAsFileTime) (FILETIME *);
/**
* Function type corresponding to `GetSystemTimeAdjustment`.
*/
typedef BOOL (WINAPI *FuncGetSystemTimeAdjustment) (DWORD *, DWORD *, BOOL *);
/**
* Function type corresponding to `GetTickCount64`.
*/
typedef ULONGLONG (WINAPI *FuncGetTickCount64) (VOID);
#ifdef RUNTIME_CHECKS
/**
* Functions which are looked up at runtime.
*/
typedef struct TimeApi {
#if WINPTHREADS_WINNT < WINPTHREADS_WINNT_NT_3_51
/**
* Function `GetSystemTimeAsFileTime` is available since Windows NT 3.51.
*/
FuncGetSystemTimeAsFileTime PtrGetSystemTimeAsFileTime;
#endif
#if WINPTHREADS_WINNT < WINPTHREADS_WINNT_WIN8
/**
* Function `GetSystemTimePreciseAsFileTime` is available since Windows 8.
*/
FuncGetSystemTimeAsFileTime PtrGetSystemTimePreciseAsFileTime;
#endif
#if WINPTHREADS_WINNT < WINPTHREADS_WINNT_NT_3_5
/**
* Function `GetSystemTimeAdjustment` is available since Windows NT 3.5.
*/
FuncGetSystemTimeAdjustment PtrGetSystemTimeAdjustment;
#endif
#if WINPTHREADS_WINNT < WINPTHREADS_WINNT_VISTA
/**
* Function `GetTickCount64` is available since Windows Vista.
*/
FuncGetTickCount64 PtrGetTickCount64;
#endif
} TimeApi;
static TimeApi WinpthreadsTimeApi;
#if WINPTHREADS_WINNT < WINPTHREADS_WINNT_NT_3_5
#define GetSystemTimeAdjustment WinpthreadsTimeApi.PtrGetSystemTimeAdjustment
#endif
#if WINPTHREADS_WINNT < WINPTHREADS_WINNT_NT_3_51
#define GetSystemTimeAsFileTime WinpthreadsTimeApi.PtrGetSystemTimeAsFileTime
#endif
#if WINPTHREADS_WINNT < WINPTHREADS_WINNT_VISTA
#define GetTickCount64 WinpthreadsTimeApi.PtrGetTickCount64
#endif
#if WINPTHREADS_WINNT < WINPTHREADS_WINNT_WIN8
#define GetSystemTimePreciseAsFileTime WinpthreadsTimeApi.PtrGetSystemTimePreciseAsFileTime
#endif
#endif /* RUNTIME_CHECKS */
#if WINPTHREADS_WINNT < WINPTHREADS_WINNT_NT_3_51
/**
* Replacement for `GetSystemTimeAsFileTime`;
* a wrapper around `GetSystemTime` and `SystemTimeToFileTime`
*/
static VOID WINAPI WinpthreadsGetSystemTimeAsFileTime (FILETIME *fileTime) {
SYSTEMTIME systemTime;
GetSystemTime (&systemTime);
/**
* If call to `SystemTimeToFileTime` fails, store Unix epoch in `fileTime`.
*/
if (unlikely (!SystemTimeToFileTime (&systemTime, fileTime))) {
fileTime->dwHighDateTime = (ULARGE_INTEGER) {.QuadPart = DELTA_EPOCH_IN_100NS}.HighPart;
fileTime->dwLowDateTime = (ULARGE_INTEGER) {.QuadPart = DELTA_EPOCH_IN_100NS}.LowPart;
}
}
#endif
#if WINPTHREADS_WINNT < WINPTHREADS_WINNT_NT_3_5
/**
* Replacement for `GetSystemTimeAdjustment`;
* a simple stab that always fails.
*/
static BOOL WINAPI WinpthreadsGetSystemTimeAdjustment (DWORD *adjustment, DWORD *increment, BOOL *disable) {
SetLastError (ERROR_CALL_NOT_IMPLEMENTED);
return FALSE;
UNREFERENCED_PARAMETER (adjustment);
UNREFERENCED_PARAMETER (increment);
UNREFERENCED_PARAMETER (disable);
}
#endif
#if WINPTHREADS_WINNT < WINPTHREADS_WINNT_VISTA
/**
* Replacement for `GetTickCount64`;
* a simple wrapper around `GetTickCount`.
*/
static ULONGLONG WINAPI WinpthreadsGetTickCount64 (VOID) {
return GetTickCount ();
}
#endif
/**
* Function type for internal implementation of `clock_gettime` and
* `clock_getres` for a specific clock (`clockid_t`) type.
*
* The first argument, if non-NULL, receives the time.
* The second argument, if non-NULL, receives the clock resolution.
*
* Returns zero on success and an error-code on failure.
*/
typedef int (* FuncWinpthreadsTimeImpl) (struct _timespec64 *, struct _timespec64 *);
/**
* Implementation for `CLOCK_REALTIME` using `GetSystemTimeAsFileTime`.
*
* This function always succeeds.
*/
static int WinpthreadsTimeImplRealtime (struct _timespec64 *, struct _timespec64 *);
/**
* Implementation for `CLOCK_REALTIME` using `GetSystemTimePreciseAsFileTime`.
*
* This function always succeeds.
*/
static int WinpthreadsTimeImplRealtimePrecise (struct _timespec64 *, struct _timespec64 *);
/**
* Implementation for `CLOCK_MONOTONIC` using `GetTickCount*`.
*
* This function always succeeds.
*/
static int WinpthreadsTimeImplMonotonicFromTickCount (struct _timespec64 *, struct _timespec64 *);
/**
* Implementation for `CLOCK_MONOTONIC` using `QueryPerformanceCounter`.
*
* This function always succeeds.
*
* In an unlikely case when call to `QueryPerformanceCounter` fails,
* this function simply forwards to `WinpthreadsTimeImplMonotonicFromTickCount`.
*/
static int WinpthreadsTimeImplMonotonicFromPerformanceCounter (struct _timespec64 *, struct _timespec64 *);
/**
* Implementation for `CLOCK_PROCESS_CPUTIME_ID`.
*
* This function always fails on Win9x systems.
*/
static int WinpthreadsTimeImplProcessCpuTime (struct _timespec64 *time, struct _timespec64 *res);
/**
* Implementation for `CLOCK_THREAD_CPUTIME_ID`.
*
* This function always fails on Win9x systems.
*/
static int WinpthreadsTimeImplThreadCpuTime (struct _timespec64 *time, struct _timespec64 *res);
/**
* Time-related data.
*/
typedef struct TimeImpl {
/**
* If set, then `GetSystemTimePreciseAsFileTime` is available.
*/
#define HIGH_RESOLUTION_SYSTEM_TIME 0x01
/**
* If set, then the performance counter is supported.
*/
#define HIGH_RESOLUTION_WINDOWS_TIME 0x02
int Flags;
/**
* Data related to the system clock. By the system clock, we refer to
* `GetSystemTime[AsFileTime]` functions.
*/
struct {
/**
* Resolution of the system clock, in nanoseconds.
*
* System clock resolution is set at boot time, which means we can obtain
* this value once and then treat it as a constant at runtime.
*/
long Resolution;
} SystemClock;
/**
* Data related to the system timer. By the system timer, we refer to
* `GetTickCount*` functions.
*/
struct {
/**
* Resolution of the system timer, in nanoseconds.
*
* System timer resolution is set at boot time, which means we can obtain
* this value once and then treat it as a constant at runtime.
*/
long Resolution;
} SystemTimer;
/**
* Data related to the performance counter.
*/
struct {
/**
* Frequency of the performance counter as returned by
* `QueryPerformanceFrequency`.
*
* This value is set once at boot time, which means we can obtain
* this value once and then treat it as a constant at runtime.
*/
__int64 Frequency;
/**
* Resolution of the performance counter , in nanoseconds.
*/
long Resolution;
} PerformanceCounter;
/**
* Implementation for `CLOCK_REALTIME`.
*
* 1. Implementation using `GetSystemTimePreciseAsFileTime`.
*
* This is the preferred implementation; it is used when both
* `GetSystemTimePreciseAsFileTime` is available and the performance counter
* is supported.
*
* This implementation provides <1us resolution.
*
* 2. Implementation using `GetSystemTimeAsFileTime`.
*
* This implementation is used when either `GetSystemTimePreciseAsFileTime`
* is not available or the performance counter is not supported.
*
* This implementation provides the same resolution as the system clock.
*/
FuncWinpthreadsTimeImpl TimeImplRealtime;
/**
* Implementation for `CLOCK_MONOTONIC`.
*
* 1. Implementation using `QueryPerformanceCounter`.
*
* This is the preferred implementation and is always used when
* the performance counter is supported.
*
* This implementation provides <1us resolution.
*
* 2. Implementation using `GetTickCount*`.
*
* This implementation is only used when the performance counter
* is not supported.
*
* This implementation provides the same resolution as the system timer.
*
* On pre-Vista systems, where `GetTickCount64` is not available,
* we use `GetTickCount`, which wraps around to zero after ~49 days.
*
* The issues resulting from using `GetTickCount*` shall not affect modern
* systems since the performance counter is always supported starting
* with Windows XP.
*/
FuncWinpthreadsTimeImpl TimeImplMonotonic;
} TimeImpl;
#if WINPTHREADS_WINNT >= WINPTHREADS_WINNT_WIN8
#define WINPTHREADS_DEFAULT_TIME_API_FLAGS (HIGH_RESOLUTION_SYSTEM_TIME)
#else
#define WINPTHREADS_DEFAULT_TIME_API_FLAGS (0)
#endif
static TimeImpl WinpthreadsTimeImpl = {
.Flags = WINPTHREADS_DEFAULT_TIME_API_FLAGS,
.SystemClock.Resolution = 0,
.PerformanceCounter.Frequency = 0,
.PerformanceCounter.Resolution = 0,
.TimeImplRealtime = WinpthreadsTimeImplRealtime,
.TimeImplMonotonic = WinpthreadsTimeImplMonotonicFromTickCount,
};
/**
* Check if `bit` is set in `WinpthreadsTimeImpl.Flags`
*/
#define WINPTHREADS_TIME_HAVE(bit) (WinpthreadsTimeImpl.Flags & (bit))
void winpthreads_time_init (void) {
#ifdef RUNTIME_CHECKS
HMODULE kernel32 = WINPTHREADS_AW (GetModuleHandle) (WINPTHREADS_TEXT ("kernel32.dll"));
#if WINPTHREADS_WINNT < WINPTHREADS_WINNT_NT_3_51
FuncGetSystemTimeAsFileTime ptrGetSystemTimeAsFileTime = NULL;
#endif
#if WINPTHREADS_WINNT < WINPTHREADS_WINNT_WIN8
FuncGetSystemTimeAsFileTime ptrGetSystemTimePreciseAsFileTime = NULL;
#endif
#if WINPTHREADS_WINNT < WINPTHREADS_WINNT_NT_3_5
FuncGetSystemTimeAdjustment ptrGetSystemTimeAdjustment = NULL;
#endif
#if WINPTHREADS_WINNT < WINPTHREADS_WINNT_VISTA
FuncGetTickCount64 ptrGetTickCount64 = NULL;
#endif
if (kernel32 != NULL) {
#if WINPTHREADS_WINNT < WINPTHREADS_WINNT_NT_3_51
ptrGetSystemTimeAsFileTime = (FuncGetSystemTimeAsFileTime) (UINT_PTR) GetProcAddress (kernel32, "GetSystemTimeAsFileTime");
#endif
#if WINPTHREADS_WINNT < WINPTHREADS_WINNT_WIN8
ptrGetSystemTimePreciseAsFileTime = (FuncGetSystemTimeAsFileTime) (UINT_PTR) GetProcAddress (kernel32, "GetSystemTimePreciseAsFileTime");
#endif
#if WINPTHREADS_WINNT < WINPTHREADS_WINNT_NT_3_5
ptrGetSystemTimeAdjustment = (FuncGetSystemTimeAdjustment) (UINT_PTR) GetProcAddress (kernel32, "GetSystemTimeAdjustment");
#endif
#if WINPTHREADS_WINNT < WINPTHREADS_WINNT_VISTA
ptrGetTickCount64 = (FuncGetTickCount64) (UINT_PTR) GetProcAddress (kernel32, "GetTickCount64");
#endif
}
#if WINPTHREADS_WINNT < WINPTHREADS_WINNT_NT_3_51
if (ptrGetSystemTimeAsFileTime != NULL) {
WinpthreadsTimeApi.PtrGetSystemTimeAsFileTime = ptrGetSystemTimeAsFileTime;
} else {
WinpthreadsTimeApi.PtrGetSystemTimeAsFileTime = WinpthreadsGetSystemTimeAsFileTime;
}
#endif
#if WINPTHREADS_WINNT < WINPTHREADS_WINNT_WIN8
if (ptrGetSystemTimePreciseAsFileTime != NULL) {
WinpthreadsTimeImpl.Flags |= HIGH_RESOLUTION_SYSTEM_TIME;
WinpthreadsTimeApi.PtrGetSystemTimePreciseAsFileTime = ptrGetSystemTimePreciseAsFileTime;
} else {
WinpthreadsTimeApi.PtrGetSystemTimePreciseAsFileTime = GetSystemTimeAsFileTime;
}
#endif
#if WINPTHREADS_WINNT < WINPTHREADS_WINNT_NT_3_5
if (ptrGetSystemTimeAdjustment != NULL) {
WinpthreadsTimeApi.PtrGetSystemTimeAdjustment = ptrGetSystemTimeAdjustment;
} else {
WinpthreadsTimeApi.PtrGetSystemTimeAdjustment = WinpthreadsGetSystemTimeAdjustment;
}
#endif
#if WINPTHREADS_WINNT < WINPTHREADS_WINNT_VISTA
if (ptrGetTickCount64 != NULL) {
WinpthreadsTimeApi.PtrGetTickCount64 = ptrGetTickCount64;
} else {
WinpthreadsTimeApi.PtrGetTickCount64 = WinpthreadsGetTickCount64;
}
#endif
#endif /* RUNTIME_CHECKS */
/**
* Obtain resolution of the system clock.
*
* Function `GetSystemTimeAdjustment` is not available on NT 3.1;
* this function is available on Win9x, but it always fails with
* `ERROR_CALL_NOT_IMPLEMENTED`.
*
* On Windows NT 3.1, resolution of the system clock is 15ms.
*
* On Win9x, according to Microsoft documentation, resolution of the system
* clock is 55ms; this is true for system time as returned by `GetSystemTime*`
* functions, but not for "windows time" returned by `GetTickCount`.
*
* NOTE: we do not use `GetSystemTimeAdjustmentPrecise` as it appears to
* return meaningless values when `isTimeAdjustmentDisabled` is `TRUE`.
*/
DWORD timeAdjustment;
DWORD timeIncrement;
BOOL isTimeAdjustmentDisabled;
if (GetSystemTimeAdjustment (&timeAdjustment, &timeIncrement, &isTimeAdjustmentDisabled)) {
WinpthreadsTimeImpl.SystemClock.Resolution = (long) (timeIncrement * 100);
} else {
if (1) {
WinpthreadsTimeImpl.SystemClock.Resolution = 15L * POW10_6;
#if WINPTHREADS_WIN9X
} else {
WinpthreadsTimeImpl.SystemClock.Resolution = 55L * POW10_6;
#endif
}
}
/**
* Obtain resolution of the system timer.
*
* On Windows NT, resolution of the system timer is the same as resolution
* of the system clock.
*
* Win9x systems use Programmable Interval Timer (PIT), whose resolution can
* be changed by setting [386Ehn].MinTimeSlice option in system.ini.
*
* On Win9x, resolution of the system timer is equivalent to that of the PIT;
* note that this is _not_ the value of [386Ehn].MinTimeSlice option.
*
* TODO: add logic to handle Win9x.
*/
if (1) {
WinpthreadsTimeImpl.SystemTimer.Resolution = WinpthreadsTimeImpl.SystemClock.Resolution;
#if WINPTHREADS_WIN9X
} else {
#endif
}
/**
* Obtain frequency and resolution of the performance counter.
*
* If we succeed, then the performance counter is supported;
* set `HIGH_RESOLUTION_WINDOWS_TIME` bit in `WinpthreadsTimeImpl.Flags`.
*
* Otherwise, the performance counter is not supported.
*
* Starting with Windows XP, functions `QueryPerformanceFrequency` and
* `QueryPerformanceCounter` always succeed.
*/
LARGE_INTEGER performanceFrequency;
if (QueryPerformanceFrequency (&performanceFrequency)) {
WinpthreadsTimeImpl.PerformanceCounter.Frequency = performanceFrequency.QuadPart;
/**
* Check if the performance counter supports sub-nanosecond resolution.
*/
if (WinpthreadsTimeImpl.PerformanceCounter.Frequency / POW10_9 > 0) {
WinpthreadsTimeImpl.PerformanceCounter.Resolution = 1L;
} else {
WinpthreadsTimeImpl.PerformanceCounter.Resolution =
(long) (POW10_9 / WinpthreadsTimeImpl.PerformanceCounter.Frequency);
}
WinpthreadsTimeImpl.Flags |= HIGH_RESOLUTION_WINDOWS_TIME;
WinpthreadsTimeImpl.TimeImplMonotonic = WinpthreadsTimeImplMonotonicFromPerformanceCounter;
/**
* Even though `GetSystemTimePreciseAsFileTime` is available since
* Windows 8, which should imply that the performance counter is supported,
* we want to be sure that `GetSystemTimePreciseAsFileTime` is used only
* when the performance counter is also supported.
*/
if (WINPTHREADS_TIME_HAVE (HIGH_RESOLUTION_SYSTEM_TIME)) {
WinpthreadsTimeImpl.TimeImplRealtime = WinpthreadsTimeImplRealtimePrecise;
}
}
}
/**
* Store resolution of the system clock in `ts`.
*/
static void WinpthreadsGetSystemClockResolution (struct _timespec64 *ts) {
ts->tv_sec = WinpthreadsTimeImpl.SystemClock.Resolution / POW10_9;
ts->tv_nsec = WinpthreadsTimeImpl.SystemClock.Resolution % POW10_9;
}
/**
* Store resolution of the system timer in `ts`.
*/
static void WinpthreadsGetSystemTimerResolution (struct _timespec64 *ts) {
ts->tv_sec = WinpthreadsTimeImpl.SystemTimer.Resolution / POW10_9;
ts->tv_nsec = WinpthreadsTimeImpl.SystemTimer.Resolution % POW10_9;
}
/**
* Store resolution of the performance counter in `ts`.
*/
static void WinpthreadsGetPerformanceCounterResolution (struct _timespec64 *ts) {
ts->tv_sec = WinpthreadsTimeImpl.PerformanceCounter.Resolution / POW10_9;
ts->tv_nsec = WinpthreadsTimeImpl.PerformanceCounter.Resolution % POW10_9;
}
/**
* Call `getSystemTimeAsFileTime` to obtain current system time as a `FILETIME`
* value and then store it in `struct _timespec64` structure pointed by `ts`.
*/
static void WinpthreadsGetSystemTime (struct _timespec64 *ts, FuncGetSystemTimeAsFileTime getSystemTimeAsFileTime) {
FILETIME fileTime;
getSystemTimeAsFileTime (&fileTime);
ULARGE_INTEGER value = {
.HighPart = fileTime.dwHighDateTime,
.LowPart = fileTime.dwLowDateTime
};
value.QuadPart -= DELTA_EPOCH_IN_100NS;
ts->tv_sec = (__time64_t) (value.QuadPart / POW10_7);
ts->tv_nsec = (long) ((value.QuadPart % POW10_7) * 100);
}
/**
* Call `getTimes` on `handle`, then convert and store obtained time values
* in `struct _timespec64` structure pointed by `ts`.
*/
static int WinpthreadsGetCpuTime (struct _timespec64 *ts, FuncGetTimes getTimes, void *handle) {
FILETIME creationTime;
FILETIME exitTime;
FILETIME kernelTime;
FILETIME userTime;
/**
* Functions `GetProcessTimes` and `GetThreadTimes` are available on
* Win9x systems, but they always fail with `ERROR_CALL_NOT_IMPLEMENTED`.
*
* `ENOTSUP` is the most fitting error code, although this error
* condition is not specified by POSIX.
*/
if (!getTimes (handle, &creationTime, &exitTime, &kernelTime, &userTime)) {
return ENOTSUP;
}
ULARGE_INTEGER kernelValue = {
.HighPart = kernelTime.dwHighDateTime,
.LowPart = kernelTime.dwLowDateTime
};
ULARGE_INTEGER userValue = {
.HighPart = userTime.dwHighDateTime,
.LowPart = userTime.dwLowDateTime
};
ULONGLONG value = kernelValue.QuadPart + userValue.QuadPart;
ts->tv_sec = (__time64_t) (value / POW10_7);
ts->tv_nsec = (long) ((value % POW10_7) * 100);
return 0;
}
static int WinpthreadsTimeImplRealtime (struct _timespec64 *time, struct _timespec64 *res) {
if (time != NULL) {
WinpthreadsGetSystemTime (time, GetSystemTimeAsFileTime);
}
if (res != NULL) {
WinpthreadsGetSystemClockResolution (res);
}
return 0;
}
static int WinpthreadsTimeImplRealtimePrecise (struct _timespec64 *time, struct _timespec64 *res) {
if (time != NULL) {
WinpthreadsGetSystemTime (time, GetSystemTimePreciseAsFileTime);
}
if (res != NULL) {
WinpthreadsGetPerformanceCounterResolution (res);
}
return 0;
}
static int WinpthreadsTimeImplMonotonicFromTickCount (struct _timespec64 *time, struct _timespec64 *res) {
if (time != NULL) {
/**
* Functions `GetTickCount*` return time in milliseconds.
*
* In order to return more precise time, round up returned time value
* to the resolution of the system timer.
*/
unsigned __int64 tickCountAsFileTime = GetTickCount64 () * POW10_4;
unsigned __int64 systemTimerResolution = WinpthreadsTimeImpl.SystemTimer.Resolution / 100;
if ((tickCountAsFileTime % systemTimerResolution) != 0) {
tickCountAsFileTime -= (tickCountAsFileTime % systemTimerResolution);
tickCountAsFileTime += systemTimerResolution;
}
time->tv_sec = (__time64_t) (tickCountAsFileTime / POW10_7);
time->tv_nsec = (long) ((tickCountAsFileTime % POW10_7) * 100);
}
if (res != NULL) {
WinpthreadsGetSystemTimerResolution (res);
}
return 0;
}
static int WinpthreadsTimeImplMonotonicFromPerformanceCounter (struct _timespec64 *time, struct _timespec64 *res) {
LARGE_INTEGER performanceCounter;
/**
* If call to `QueryPerformanceCounter` fails,
* forward to `WinpthreadsTimeImplMonotonicFromTickCount`.
*/
if (unlikely (!QueryPerformanceCounter (&performanceCounter))) {
return WinpthreadsTimeImplMonotonicFromTickCount (time, res);
}
const __int64 performanceFrequency = WinpthreadsTimeImpl.PerformanceCounter.Frequency;
if (time != NULL) {
time->tv_sec = (__time64_t) (performanceCounter.QuadPart / performanceFrequency);
time->tv_nsec = (long) (((performanceCounter.QuadPart % performanceFrequency) * POW10_9) / performanceFrequency);
}
if (res != NULL) {
WinpthreadsGetPerformanceCounterResolution (res);
}
return 0;
}
static int WinpthreadsTimeImplProcessCpuTime (struct _timespec64 *time, struct _timespec64 *res) {
struct _timespec64 ts;
/**
* Win9x: we want both `clock_getres` and `clock_gettime` to fail
* if CPU clocks are not supported.
*/
int error_code = WinpthreadsGetCpuTime (&ts, GetProcessTimes, GetCurrentProcess ());
if (error_code != 0) {
return error_code;
}
if (time != NULL) {
*time = ts;
}
if (res != NULL) {
WinpthreadsGetSystemClockResolution (res);
}
return 0;
}
static int WinpthreadsTimeImplThreadCpuTime (struct _timespec64 *time, struct _timespec64 *res) {
struct _timespec64 ts;
/**
* Win9x: we want both `clock_getres` and `clock_gettime` to fail
* if CPU clocks are not supported.
*/
int error_code = WinpthreadsGetCpuTime (&ts, GetThreadTimes, GetCurrentThread ());
if (error_code != 0) {
return error_code;
}
if (time != NULL) {
*time = ts;
}
if (res != NULL) {
WinpthreadsGetSystemClockResolution (res);
}
return 0;
}
/*******************************************************************************
* Private Functions.
*/
/**
* `MAX_SLEEP_IN_MS` as a `struct timespec` value.
*/
static const struct _timespec64 MaxWaitTimeAsTimeSpec = {
.tv_sec = (__time64_t) (MAX_SLEEP_IN_MS / POW10_3),
.tv_nsec = (long) ((MAX_SLEEP_IN_MS % POW10_3) * POW10_6)
};
/**
* The maximum `struct timespec` value that would fit into unsigned 64-bit
* integer when converted to nanoseconds.
*/
static const struct _timespec64 NsMaxAsTimeSpec = {
.tv_sec = (__time64_t) (_UI64_MAX / POW10_9),
.tv_nsec = (long) (_UI64_MAX % POW10_9)
};
int winpthreads_time (clockid_t clock, struct _timespec64 *time, struct _timespec64 *res) {
FuncWinpthreadsTimeImpl timeImpl;
switch (clock) {
case CLOCK_REALTIME:
timeImpl = WinpthreadsTimeImpl.TimeImplRealtime;
break;
case CLOCK_MONOTONIC:
timeImpl = WinpthreadsTimeImpl.TimeImplMonotonic;
break;
case CLOCK_PROCESS_CPUTIME_ID:
timeImpl = WinpthreadsTimeImplProcessCpuTime;
break;
case CLOCK_THREAD_CPUTIME_ID:
timeImpl = WinpthreadsTimeImplThreadCpuTime;
break;
case CLOCK_REALTIME_COARSE:
timeImpl = WinpthreadsTimeImplRealtime;
break;
default:
UNREACHABLE ();
}
return timeImpl (time, res);
}
int winpthreads_timespec_diff (const struct _timespec64 *ts1, const struct _timespec64 *ts2) {
if (ts1->tv_sec > ts2->tv_sec) {
return 1;
}
if (ts1->tv_sec < ts2->tv_sec) {
return -1;
}
return ts1->tv_nsec - ts2->tv_nsec;
}
void winpthreads_timespec_add (const struct _timespec64 *ts1, const struct _timespec64 *ts2, struct _timespec64 *out) {
/**
* Check for overflow.
*/
if (unlikely (ts1->tv_sec > _I64_MAX - ts2->tv_sec)) {
out->tv_sec = _I64_MAX;
out->tv_nsec = POW10_9 - 1;
return;
}
out->tv_sec = ts1->tv_sec + ts2->tv_sec;
out->tv_nsec = ts1->tv_nsec + ts2->tv_nsec;
if (out->tv_nsec >= POW10_9) {
/**
* Prevent overflow in `out->tv_sec`.
*/
if (out->tv_sec == _I64_MAX) {
out->tv_nsec = POW10_9 - 1;
} else {
out->tv_sec += 1;
out->tv_nsec -= POW10_9;
}
}
}
void winpthreads_timespec_sub (const struct _timespec64 *ts1, const struct _timespec64 *ts2, struct _timespec64 *out) {
/**
* Check for underflow.
*/
if (ts2->tv_sec > ts1->tv_sec) {
out->tv_sec = 0;
out->tv_nsec = 0;
return;
}
out->tv_sec = ts1->tv_sec - ts2->tv_sec;
out->tv_nsec = ts1->tv_nsec - ts2->tv_nsec;
if (out->tv_nsec < 0) {
/**
* Prevent underflow in `out->tv_sec`.
*/
if (out->tv_sec == 0) {
out->tv_nsec = 0;
} else {
out->tv_sec -= 1;
out->tv_nsec += POW10_9;
}
}
}
void winpthreads_timespec_round (const struct _timespec64 *time, const struct _timespec64 *res, struct _timespec64 *out) {
/**
* If `time` is zero simply return it in `out`.
*/
if (time->tv_sec == 0 && time->tv_nsec == 0) {
*out = *time;
return;
}
/**
* If `time` is less than or equal to `res`, store value of `res` in `out`.
*/
if (winpthreads_timespec_diff (time, res) <= 0) {
*out = *res;
return;
}
/**
* Check if `time` can fit into unsigned 64-bit integer when converted to
* nanoseconds.
*/
if (unlikely (winpthreads_timespec_diff (time, &NsMaxAsTimeSpec) > 0)) {
*out = *time;
return;
}
/**
* Convert `time` and `res` to nanoseconds.
*/
unsigned __int64 timeNs = ((unsigned __int64) time->tv_sec) * POW10_9 + time->tv_nsec;
unsigned __int64 resNs = ((unsigned __int64) res->tv_sec) * POW10_9 + res->tv_nsec;
/**
* Check if `time` is already a multiple of `res`.
*/
if ((timeNs % resNs) == 0) {
*out = *time;
return;
}
/**
* First, round down `time` to multiple of `res`.
*/
timeNs -= (timeNs % resNs);
/**
* Second, round up `time` to multiple of `res`.
*
* In order to avoid possible unsigned overflow, do addition using
* `winpthreads_timespec_add`.
*/
struct _timespec64 newTime = {
.tv_sec = (__time64_t) (timeNs / POW10_9),
.tv_nsec = (long) (timeNs % POW10_9),
};
winpthreads_timespec_add (&newTime, res, out);
}
unsigned winpthreads_wait_time_from_timespec (const struct _timespec64 *time, const struct _timespec64 *res) {
/**
* Return zero if `time` is zero.
*/
if (time->tv_sec == 0 && time->tv_nsec == 0) {
return 0;
}
/**
* If `time` is less than or equal to `res`, simply return 1ms.
*/
if (winpthreads_timespec_diff (time, res) <= 0) {
return 1;
}
/**
* Check if `time` is larger than `MaxWaitTimeAsTimeSpec`.
*/
if (unlikely (winpthreads_timespec_diff (time, &MaxWaitTimeAsTimeSpec) > 0)) {
return MAX_SLEEP_IN_MS;
}
/**
* Convert `time` and `res` to nanoseconds.
*
* Note that check above ensures that `time`, when converted to nanoseconds,
* fits into 64-bit unsigned integer.
*/
unsigned __int64 nsTime = ((unsigned __int64) time->tv_sec) * POW10_9 + time->tv_nsec;
unsigned __int64 nsRes = ((unsigned __int64) res->tv_sec) * POW10_9 + res->tv_nsec;
if ((nsTime % nsRes) == 0) {
nsTime -= nsRes;
} else {
nsTime -= (nsTime % nsRes);
}
/**
* Ensure that conversion to milliseconds does not yield zero.
*/
if (nsTime < POW10_6) {
return 1;
}
return (unsigned) (nsTime / POW10_6);
}
/*******************************************************************************
* Public Functions.
*/
/**
* Common implementation for `nanosleep` and `clock_nanosleep`.
*
* Returns zero on success and an error-code on failure.
*/
static int WinpthreadsSleep (clockid_t clock_id, int flags, const struct _timespec64 *request, struct _timespec64 *remain) {
/**
* Both `nanosleep` and `clock_nanosleep` are cancellation points.
*/
int waitFlags = WINPTHREADS_WAIT_CANCELLATION_NOTIFICATION;
if (flags & TIMER_ABSTIME) {
waitFlags |= WINPTHREADS_WAIT_TIMEOUT_ABSTIME;
}
/**
* Remaining sleep time.
*/
struct _timespec64 ts;
winpthreads_wait_status wait_status = winpthreads_wait (NULL, waitFlags, clock_id, request, &ts);
if (wait_status == wait_interrupted) {
pthread_testcancel ();
/**
* Store remaining sleep time in `remain`.
*/
if ((flags & TIMER_ABSTIME) == 0 && remain != NULL) {
*remain = ts;
}
return EINTR;
}
return 0;
}
int nanosleep64 (const struct _timespec64 *request, struct _timespec64 *remain)
{
/**
* Function `nanosleep` is a cancellation point.
*/
pthread_testcancel ();
/**
* The nanosleep() function shall fail if:
*
* [EINVAL]
* The request argument specified a nanosecond value less than zero or
* greater than or equal to 1000 million.
*/
if (request->tv_sec < 0 || request->tv_nsec < 0 || request->tv_nsec >= POW10_9) {
_set_errno (EINVAL);
return -1;
}
int error_code = WinpthreadsSleep (CLOCK_REALTIME, 0, request, remain);
if (error_code != 0) {
_set_errno (error_code);
return -1;
}
return error_code;
}
int nanosleep32 (const struct _timespec32 *request, struct _timespec32 *remain)
{
struct _timespec64 request64 = {
.tv_sec = request->tv_sec,
.tv_nsec = request->tv_nsec
};
struct _timespec64 remain64 = {0};
int error_code = nanosleep64 (&request64, &remain64);
if (error_code == -1) {
if (errno == EINTR && remain != NULL) {
assert (remain64.tv_sec >= 0 && remain64.tv_sec <= INT_MAX);
remain->tv_sec = (__time32_t) remain64.tv_sec;
assert (remain64.tv_nsec >= 0 && remain64.tv_nsec < POW10_9);
remain->tv_nsec = remain64.tv_nsec;
}
}
return error_code;
}
int clock_getres64 (clockid_t clock_id, struct _timespec64 *res)
{
int error_code = 0;
switch (clock_id) {
case CLOCK_REALTIME: {
WinpthreadsTimeImpl.TimeImplRealtime (NULL, res);
break;
}
case CLOCK_REALTIME_COARSE: {
WinpthreadsTimeImplRealtime (NULL, res);
break;
}
case CLOCK_MONOTONIC: {
WinpthreadsTimeImpl.TimeImplMonotonic (NULL, res);
break;
}
case CLOCK_PROCESS_CPUTIME_ID: {
error_code = WinpthreadsTimeImplProcessCpuTime (NULL, res);
break;
}
case CLOCK_THREAD_CPUTIME_ID: {
error_code = WinpthreadsTimeImplThreadCpuTime (NULL, res);
break;
}
default: {
error_code = EINVAL;
break;
}
}
if (error_code != 0) {
_set_errno (error_code);
return -1;
}
return 0;
}
int clock_getres32 (clockid_t clock_id, struct _timespec32 *res)
{
struct _timespec64 res64;
int error_code = clock_getres64 (clock_id, &res64);
if (error_code == 0) {
res->tv_sec = (__time32_t) res64.tv_sec;
res->tv_nsec = res64.tv_nsec;
}
return error_code;
}
int clock_gettime64 (clockid_t clock_id, struct _timespec64 *tp)
{
int error_code = 0;
switch (clock_id) {
case CLOCK_REALTIME: {
WinpthreadsTimeImpl.TimeImplRealtime (tp, NULL);
break;
}
case CLOCK_REALTIME_COARSE: {
WinpthreadsTimeImplRealtime (tp, NULL);
break;
}
case CLOCK_MONOTONIC: {
WinpthreadsTimeImpl.TimeImplMonotonic (tp, NULL);
break;
}
case CLOCK_PROCESS_CPUTIME_ID: {
error_code = WinpthreadsTimeImplProcessCpuTime (tp, NULL);
break;
}
case CLOCK_THREAD_CPUTIME_ID: {
error_code = WinpthreadsTimeImplThreadCpuTime (tp, NULL);
break;
}
default: {
error_code = EINVAL;
break;
}
}
if (error_code != 0) {
_set_errno (error_code);
return -1;
}
return 0;
}
int clock_gettime32 (clockid_t clock_id, struct _timespec32 *tp)
{
struct _timespec64 tp64;
int error_code = clock_gettime64 (clock_id, &tp64);
if (error_code == 0) {
if (tp64.tv_sec > INT_MAX) {
_set_errno (EOVERFLOW);
return -1;
}
tp->tv_sec = (__time32_t) tp64.tv_sec;
tp->tv_nsec = tp64.tv_nsec;
}
return error_code;
}
int clock_settime64 (clockid_t clock_id, const struct _timespec64 *tp)
{
/**
* The clock_settime() function shall fail if:
*
* [EINVAL]
* The tp argument specified a nanosecond value less than zero or
* greater than or equal to 1000 million.
*/
if (tp->tv_sec < 0 || tp->tv_nsec < 0 || tp->tv_nsec >= POW10_9) {
_set_errno (EINVAL);
return -1;
}
FuncWinpthreadsTimeImpl timeImpl;
switch (clock_id) {
case CLOCK_REALTIME:
timeImpl = WinpthreadsTimeImpl.TimeImplRealtime;
break;
case CLOCK_REALTIME_COARSE:
timeImpl = WinpthreadsTimeImplRealtime;
break;
/**
* Setting CPU clocks is not supported.
*
* Fail with `ENOTSUP`; while this error condition is not specified
* by POSIX, it is better than overly generic `EINVAL`.
*/
case CLOCK_PROCESS_CPUTIME_ID:
case CLOCK_THREAD_CPUTIME_ID:
_set_errno (ENOTSUP);
return -1;
/**
* The clock_settime() function shall fail if:
*
* [EINVAL]
* The value of the clock_id argument is CLOCK_MONOTONIC.
*/
case CLOCK_MONOTONIC:
/**
* The clock_settime() function shall fail if:
*
* [EINVAL]
* The clock_id argument does not specify a known clock.
*/
default:
_set_errno(EINVAL);
return -1;
}
/**
* Obtain resolution of `clock_id` as a `FILETIME` value.
*/
struct _timespec64 resAsTimeSpec;
unsigned __int64 resAsFileTime;
timeImpl (NULL, &resAsTimeSpec);
resAsFileTime = resAsTimeSpec.tv_sec * POW10_7 + resAsTimeSpec.tv_nsec / 100;
/**
* The maximum `FILETIME` value that can be passed to `FileTimeToSystemTime`
* is defined as `FILETIME_TO_SYSTEMTIME_MAX`. However, since we will round
* it down to `resAsFileTime`, we may allow values slighty larger than that.
*/
unsigned __int64 fileTimeMax = FILETIME_TO_SYSTEMTIME_MAX;
if (likely (resAsFileTime != 0) && (fileTimeMax % resAsFileTime) != 0) {
fileTimeMax -= (fileTimeMax % resAsFileTime);
fileTimeMax += resAsFileTime - 1;
}
/**
* Convert `tp` to `FILEITME` value.
* The converted value shall not exceed `fileTimeMax`.
*
* The clock_settime() function shall fail if:
*
* [EINVAL]
* The tp argument to clock_settime() is outside the range for
* the given clock ID.
*/
ULARGE_INTEGER value = {
.QuadPart = DELTA_EPOCH_IN_100NS
};
unsigned __int64 fileTimeFromSec = (unsigned __int64) tp->tv_sec;
unsigned __int64 fileTimeFromNsec = (unsigned __int64) (tp->tv_nsec / 100);
if (unlikely (fileTimeFromSec > ((fileTimeMax - value.QuadPart) / POW10_7))) {
_set_errno (EINVAL);
return -1;
}
value.QuadPart += (fileTimeFromSec * POW10_7);
if (unlikely (fileTimeFromNsec > (fileTimeMax - value.QuadPart))) {
_set_errno (EINVAL);
return -1;
}
value.QuadPart += fileTimeFromNsec;
/**
* Round `value` down to `resAsFileTime`.
*/
if (likely (resAsFileTime != 0)) {
value.QuadPart -= (value.QuadPart % resAsFileTime);
}
/**
* Convert `value` to `FILETIME`, and then to `SYSTEMTIME`.
*/
FILETIME fileTime = {
.dwHighDateTime = value.HighPart,
.dwLowDateTime = value.LowPart
};
SYSTEMTIME systemTime;
if (!FileTimeToSystemTime (&fileTime, &systemTime)) {
_set_errno (EINVAL);
return -1;
}
/**
* The clock_settime() function shall fail if:
*
* [EPERM]
* The requesting process does not have appropriate privileges
* to set the specified clock.
*/
if (!SetSystemTime (&systemTime)) {
_set_errno (EPERM);
return -1;
}
return 0;
}
int clock_settime32 (clockid_t clock_id, const struct _timespec32 *tp)
{
struct _timespec64 tp64 = {.tv_sec = tp->tv_sec, .tv_nsec = tp->tv_nsec};
return clock_settime64 (clock_id, &tp64);
}
int clock_nanosleep64 (clockid_t clock_id, int flags, const struct _timespec64 *request, struct _timespec64 *remain)
{
/**
* Function `clock_nanosleep` is a cancellation point.
*/
pthread_testcancel ();
/**
* The clock_nanosleep() function shall fail if:
*
* [EINVAL]
* The request argument specified a nanosecond value less than zero or
* greater than or equal to 1000 million.
*/
if (request->tv_sec < 0 || request->tv_nsec < 0 || request->tv_nsec >= POW10_9) {
return EINVAL;
}
switch (clock_id) {
case CLOCK_REALTIME:
break;
case CLOCK_REALTIME_COARSE:
break;
case CLOCK_MONOTONIC:
break;
/**
* The clock_nanosleep() function shall fail if:
*
* [EINVAL]
* the clock_id argument does not specify a known clock,
* or specifies the CPU-time clock of the calling thread.
*/
case CLOCK_PROCESS_CPUTIME_ID:
case CLOCK_THREAD_CPUTIME_ID:
default:
return EINVAL;
}
return WinpthreadsSleep (clock_id, flags, request, remain);
}
int clock_nanosleep32 (clockid_t clock_id, int flags, const struct _timespec32 *request, struct _timespec32 *remain)
{
struct _timespec64 request64 = {
.tv_sec = request->tv_sec,
.tv_nsec = request->tv_nsec
};
struct _timespec64 remain64;
int error_code = clock_nanosleep64 (clock_id, flags, &request64, &remain64);
if (!(flags & TIMER_ABSTIME) && error_code == EINTR && remain != NULL) {
assert (remain64.tv_sec >= 0 && remain64.tv_sec <= INT_MAX);
remain->tv_sec = (__time32_t) remain64.tv_sec;
assert (remain64.tv_nsec >= 0 && remain64.tv_nsec < POW10_9);
remain->tv_nsec = remain64.tv_nsec;
}
return error_code;
}