master
  1/*
  2   Copyright (c) 2011-2016  mingw-w64 project
  3
  4   Permission is hereby granted, free of charge, to any person obtaining a
  5   copy of this software and associated documentation files (the "Software"),
  6   to deal in the Software without restriction, including without limitation
  7   the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8   and/or sell copies of the Software, and to permit persons to whom the
  9   Software is furnished to do so, subject to the following conditions:
 10
 11   The above copyright notice and this permission notice shall be included in
 12   all copies or substantial portions of the Software.
 13
 14   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 15   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 16   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 17   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 18   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 19   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 20   DEALINGS IN THE SOFTWARE.
 21*/
 22
 23#ifdef HAVE_CONFIG_H
 24#include "config.h"
 25#endif
 26
 27#define WIN32_LEAN_AND_MEAN
 28#include <windows.h>
 29
 30/* public header files */
 31#include "pthread.h"
 32/* internal header files */
 33#include "misc.h"
 34
 35void (WINAPI *_pthread_get_system_time_best_as_file_time) (LPFILETIME) = NULL;
 36static ULONGLONG (WINAPI *_pthread_get_tick_count_64) (VOID);
 37HRESULT (WINAPI *_pthread_set_thread_description) (HANDLE, PCWSTR) = NULL;
 38
 39#if defined(__GNUC__) || defined(__clang__)
 40#pragma GCC diagnostic push
 41#pragma GCC diagnostic ignored "-Wprio-ctor-dtor"
 42__attribute__((constructor(0)))
 43#endif
 44static void winpthreads_init(void)
 45{
 46    HMODULE mod = GetModuleHandleA("kernel32.dll");
 47    if (mod)
 48    {
 49        _pthread_get_tick_count_64 =
 50            (ULONGLONG (WINAPI *)(VOID))(void*) GetProcAddress(mod, "GetTickCount64");
 51
 52        /* <1us precision on Windows 10 */
 53        _pthread_get_system_time_best_as_file_time =
 54            (void (WINAPI *)(LPFILETIME))(void*) GetProcAddress(mod, "GetSystemTimePreciseAsFileTime");
 55    }
 56
 57    if (!_pthread_get_system_time_best_as_file_time)
 58        /* >15ms precision on Windows 10 */
 59        _pthread_get_system_time_best_as_file_time = GetSystemTimeAsFileTime;
 60
 61    mod = GetModuleHandleA("kernelbase.dll");
 62    if (mod)
 63    {
 64        _pthread_set_thread_description =
 65            (HRESULT (WINAPI *)(HANDLE, PCWSTR))(void*) GetProcAddress(mod, "SetThreadDescription");
 66    }
 67}
 68#if defined(__GNUC__) || defined(__clang__)
 69#pragma GCC diagnostic pop
 70#endif
 71
 72#if defined(_MSC_VER) && !defined(__clang__)
 73/* Force a reference to __xc_t to prevent whole program optimization
 74 * from discarding the variable. */
 75
 76/* On x86, symbols are prefixed with an underscore. */
 77# if defined(_M_IX86)
 78#   pragma comment(linker, "/include:___xc_t")
 79# else
 80#   pragma comment(linker, "/include:__xc_t")
 81# endif
 82
 83#pragma section(".CRT$XCT", long, read)
 84__declspec(allocate(".CRT$XCT"))
 85extern const _PVFV __xc_t;
 86const _PVFV __xc_t = winpthreads_init;
 87#endif
 88
 89unsigned long long _pthread_time_in_ms(void)
 90{
 91    FILETIME ft;
 92
 93    GetSystemTimeAsFileTime(&ft);
 94    return (((unsigned long long)ft.dwHighDateTime << 32) + ft.dwLowDateTime
 95            - 0x19DB1DED53E8000ULL) / 10000ULL;
 96}
 97
 98unsigned long long _pthread_time_in_ms_from_timespec(const struct _timespec64 *ts)
 99{
100    unsigned long long t = (unsigned long long) ts->tv_sec * 1000LL;
101    /* The +999999 is here to ensure that the division always rounds up */
102    t += (unsigned long long) (ts->tv_nsec + 999999) / 1000000;
103
104    return t;
105}
106
107unsigned long long _pthread_rel_time_in_ms(const struct _timespec64 *ts)
108{
109    unsigned long long t1 = _pthread_time_in_ms_from_timespec(ts);
110    unsigned long long t2 = _pthread_time_in_ms();
111
112    /* Prevent underflow */
113    if (t1 < t2) return 0;
114    return t1 - t2;
115}
116
117static unsigned long long
118_pthread_get_tick_count (long long *frequency)
119{
120  if (_pthread_get_tick_count_64 != NULL)
121    return _pthread_get_tick_count_64 ();
122
123  LARGE_INTEGER freq, timestamp;
124
125  if (*frequency == 0)
126  {
127    if (QueryPerformanceFrequency (&freq))
128      *frequency = freq.QuadPart;
129    else
130      *frequency = -1;
131  }
132
133  if (*frequency > 0 && QueryPerformanceCounter (&timestamp))
134    return timestamp.QuadPart / (*frequency / 1000);
135
136  /* Fallback */
137  return GetTickCount ();
138}
139
140/* A wrapper around WaitForSingleObject() that ensures that
141 * the wait function does not time out before the time
142 * actually runs out. This is needed because WaitForSingleObject()
143 * might have poor accuracy, returning earlier than expected.
144 * On the other hand, returning a bit *later* than expected
145 * is acceptable in a preemptive multitasking environment.
146 */
147unsigned long
148_pthread_wait_for_single_object (void *handle, unsigned long timeout)
149{
150  DWORD result;
151  unsigned long long start_time, end_time;
152  unsigned long wait_time;
153  long long frequency = 0;
154
155  if (timeout == INFINITE || timeout == 0)
156    return WaitForSingleObject ((HANDLE) handle, (DWORD) timeout);
157
158  start_time = _pthread_get_tick_count (&frequency);
159  end_time = start_time + timeout;
160  wait_time = timeout;
161
162  do
163  {
164    unsigned long long current_time;
165
166    result = WaitForSingleObject ((HANDLE) handle, (DWORD) wait_time);
167    if (result != WAIT_TIMEOUT)
168      break;
169
170    current_time = _pthread_get_tick_count (&frequency);
171    if (current_time >= end_time)
172      break;
173
174    wait_time = (DWORD) (end_time - current_time);
175  } while (TRUE);
176
177  return result;
178}
179
180/* A wrapper around WaitForMultipleObjects() that ensures that
181 * the wait function does not time out before the time
182 * actually runs out. This is needed because WaitForMultipleObjects()
183 * might have poor accuracy, returning earlier than expected.
184 * On the other hand, returning a bit *later* than expected
185 * is acceptable in a preemptive multitasking environment.
186 */
187unsigned long
188_pthread_wait_for_multiple_objects (unsigned long count, void **handles, unsigned int all, unsigned long timeout)
189{
190  DWORD result;
191  unsigned long long start_time, end_time;
192  unsigned long wait_time;
193  long long frequency = 0;
194
195  if (timeout == INFINITE || timeout == 0)
196    return WaitForMultipleObjects ((DWORD) count, (HANDLE *) handles, all, (DWORD) timeout);
197
198  start_time = _pthread_get_tick_count (&frequency);
199  end_time = start_time + timeout;
200  wait_time = timeout;
201
202  do
203  {
204    unsigned long long current_time;
205
206    result = WaitForMultipleObjects ((DWORD) count, (HANDLE *) handles, all, (DWORD) wait_time);
207    if (result != WAIT_TIMEOUT)
208      break;
209
210    current_time = _pthread_get_tick_count (&frequency);
211    if (current_time >= end_time)
212      break;
213
214    wait_time = (DWORD) (end_time - current_time);
215  } while (TRUE);
216
217  return result;
218}