| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
#include <aws/common/clock.h> |
| 7 |
#include <windows.h> |
| 8 |
|
| 9 |
static const uint64_t FILE_TIME_TO_NS = 100; |
| 10 |
static const uint64_t EC_TO_UNIX_EPOCH = 11644473600LL; |
| 11 |
static const uint64_t WINDOWS_TICK = 10000000; |
| 12 |
|
| 13 |
static INIT_ONCE s_timefunc_init_once = INIT_ONCE_STATIC_INIT; |
| 14 |
typedef VOID WINAPI timefunc_t(LPFILETIME); |
| 15 |
static VOID WINAPI s_get_system_time_func_lazy_init(LPFILETIME filetime_p); |
| 16 |
static timefunc_t *volatile s_p_time_func = s_get_system_time_func_lazy_init; |
| 17 |
|
| 18 |
|
| 19 |
#define WIDEN2(s) L## #s |
| 20 |
#define WIDEN(s) WIDEN2(s) |
| 21 |
|
| 22 |
static BOOL CALLBACK s_get_system_time_init_once(PINIT_ONCE init_once, PVOID param, PVOID *context) { |
| 23 |
(void)init_once; |
| 24 |
(void)param; |
| 25 |
(void)context; |
| 26 |
|
| 27 |
HMODULE kernel = GetModuleHandleW(WIDEN(WINDOWS_KERNEL_LIB) L".dll"); |
| 28 |
timefunc_t *time_func = (timefunc_t *)GetProcAddress(kernel, "GetSystemTimePreciseAsFileTime"); |
| 29 |
|
| 30 |
if (time_func == NULL) { |
| 31 |
time_func = GetSystemTimeAsFileTime; |
| 32 |
} |
| 33 |
|
| 34 |
s_p_time_func = time_func; |
| 35 |
|
| 36 |
return TRUE; |
| 37 |
} |
| 38 |
|
| 39 |
static VOID WINAPI s_get_system_time_func_lazy_init(LPFILETIME filetime_p) { |
| 40 |
BOOL status = InitOnceExecuteOnce(&s_timefunc_init_once, s_get_system_time_init_once, NULL, NULL); |
| 41 |
|
| 42 |
if (status) { |
| 43 |
(*s_p_time_func)(filetime_p); |
| 44 |
} else { |
| 45 |
|
| 46 |
GetSystemTimeAsFileTime(filetime_p); |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
int aws_high_res_clock_get_ticks(uint64_t *timestamp) { |
| 51 |
LARGE_INTEGER ticks, frequency; |
| 52 |
|
| 53 |
if (QueryPerformanceFrequency(&frequency) && QueryPerformanceCounter(&ticks)) { |
| 54 |
*timestamp = aws_timestamp_convert_u64( |
| 55 |
(uint64_t)ticks.QuadPart, (uint64_t)frequency.QuadPart, AWS_TIMESTAMP_NANOS, NULL); |
| 56 |
|
| 57 |
return AWS_OP_SUCCESS; |
| 58 |
} |
| 59 |
|
| 60 |
return aws_raise_error(AWS_ERROR_CLOCK_FAILURE); |
| 61 |
} |
| 62 |
|
| 63 |
int aws_sys_clock_get_ticks(uint64_t *timestamp) { |
| 64 |
FILETIME ticks; |
| 65 |
|
| 66 |
|
| 67 |
(*s_p_time_func)(&ticks); |
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
ULARGE_INTEGER int_conv; |
| 73 |
int_conv.LowPart = ticks.dwLowDateTime; |
| 74 |
int_conv.HighPart = ticks.dwHighDateTime; |
| 75 |
|
| 76 |
*timestamp = (int_conv.QuadPart - (WINDOWS_TICK * EC_TO_UNIX_EPOCH)) * FILE_TIME_TO_NS; |
| 77 |
return AWS_OP_SUCCESS; |
| 78 |
} |