Coverage Report

Created: 2025-07-01 06:46

/src/FreeRDP/winpr/libwinpr/synch/wait.c
Line
Count
Source (jump to first uncovered line)
1
/**
2
 * WinPR: Windows Portable Runtime
3
 * Synchronization Functions
4
 *
5
 * Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
6
 * Copyright 2014 Hardening <contact@hardening-consulting.com>
7
 *
8
 * Licensed under the Apache License, Version 2.0 (the "License");
9
 * you may not use this file except in compliance with the License.
10
 * You may obtain a copy of the License at
11
 *
12
 *     http://www.apache.org/licenses/LICENSE-2.0
13
 *
14
 * Unless required by applicable law or agreed to in writing, software
15
 * distributed under the License is distributed on an "AS IS" BASIS,
16
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
 * See the License for the specific language governing permissions and
18
 * limitations under the License.
19
 */
20
21
#include <winpr/config.h>
22
23
#ifdef WINPR_HAVE_UNISTD_H
24
#include <unistd.h>
25
#endif
26
27
#include <winpr/assert.h>
28
#include <errno.h>
29
30
#include <winpr/crt.h>
31
#include <winpr/synch.h>
32
#include <winpr/platform.h>
33
#include <winpr/sysinfo.h>
34
35
#include "synch.h"
36
#include "pollset.h"
37
#include "../thread/thread.h"
38
#include <winpr/thread.h>
39
#include <winpr/debug.h>
40
41
#include "../log.h"
42
0
#define TAG WINPR_TAG("sync.wait")
43
44
/**
45
 * WaitForSingleObject
46
 * WaitForSingleObjectEx
47
 * WaitForMultipleObjectsEx
48
 * SignalObjectAndWait
49
 */
50
51
#ifndef _WIN32
52
53
#include <stdlib.h>
54
#include <time.h>
55
#include <sys/time.h>
56
#include <sys/wait.h>
57
58
#include "../handle/handle.h"
59
60
#include "../pipe/pipe.h"
61
62
static struct timespec ts_from_ns(void)
63
0
{
64
0
  const UINT64 ns = winpr_GetUnixTimeNS();
65
0
  struct timespec timeout = { 0 };
66
0
  timeout.tv_sec = WINPR_TIME_NS_TO_S(ns);
67
0
  timeout.tv_nsec = WINPR_TIME_NS_REM_NS(ns);
68
0
  return timeout;
69
0
}
70
71
/**
72
 * Drop in replacement for pthread_mutex_timedlock
73
 * http://code.google.com/p/android/issues/detail?id=7807
74
 * http://aleksmaus.blogspot.ca/2011/12/missing-pthreadmutextimedlock-on.html
75
 */
76
#if !defined(WINPR_HAVE_PTHREAD_MUTEX_TIMEDLOCK)
77
#include <pthread.h>
78
79
static long long ts_difftime(const struct timespec* o, const struct timespec* n)
80
{
81
  long long oldValue = o->tv_sec * 1000000000LL + o->tv_nsec;
82
  long long newValue = n->tv_sec * 1000000000LL + n->tv_nsec;
83
  return newValue - oldValue;
84
}
85
86
#ifdef ANDROID
87
#if (__ANDROID_API__ >= 21)
88
#define CONST_NEEDED const
89
#else
90
#define CONST_NEEDED
91
#endif
92
#define STATIC_NEEDED
93
#else /* ANDROID */
94
#define CONST_NEEDED const
95
#define STATIC_NEEDED static
96
#endif
97
98
STATIC_NEEDED int pthread_mutex_timedlock(pthread_mutex_t* mutex,
99
                                          CONST_NEEDED struct timespec* timeout)
100
{
101
  struct timespec timenow = { 0 };
102
  struct timespec sleepytime = { 0 };
103
  unsigned long long diff = 0;
104
  int retcode = -1;
105
  /* This is just to avoid a completely busy wait */
106
  timenow = ts_from_ns();
107
  diff = ts_difftime(&timenow, timeout);
108
  sleepytime.tv_sec = diff / 1000000000LL;
109
  sleepytime.tv_nsec = diff % 1000000000LL;
110
111
  while ((retcode = pthread_mutex_trylock(mutex)) == EBUSY)
112
  {
113
    timenow = ts_from_ns();
114
115
    if (ts_difftime(timeout, &timenow) >= 0)
116
    {
117
      return ETIMEDOUT;
118
    }
119
120
    nanosleep(&sleepytime, NULL);
121
  }
122
123
  return retcode;
124
}
125
#endif
126
127
static void ts_add_ms(struct timespec* ts, DWORD dwMilliseconds)
128
0
{
129
0
  ts->tv_sec += dwMilliseconds / 1000L;
130
0
  ts->tv_nsec += (dwMilliseconds % 1000L) * 1000000L;
131
0
  ts->tv_sec += ts->tv_nsec / 1000000000L;
132
0
  ts->tv_nsec = ts->tv_nsec % 1000000000L;
133
0
}
134
135
DWORD WaitForSingleObjectEx(HANDLE hHandle, DWORD dwMilliseconds, BOOL bAlertable)
136
0
{
137
0
  ULONG Type = 0;
138
0
  WINPR_HANDLE* Object = NULL;
139
0
  WINPR_POLL_SET pollset = { 0 };
140
141
0
  if (!winpr_Handle_GetInfo(hHandle, &Type, &Object))
142
0
  {
143
0
    WLog_ERR(TAG, "invalid hHandle.");
144
0
    SetLastError(ERROR_INVALID_HANDLE);
145
0
    return WAIT_FAILED;
146
0
  }
147
148
0
  if (Type == HANDLE_TYPE_PROCESS && winpr_Handle_getFd(hHandle) == -1)
149
0
  {
150
    /* note: if we have pidfd support (under linux and we have managed to associate a
151
     *    pidfd with our process), we use the regular method with pollset below.
152
     *    If not (on other platforms) we do a waitpid */
153
0
    WINPR_PROCESS* process = (WINPR_PROCESS*)Object;
154
155
0
    do
156
0
    {
157
0
      DWORD status = 0;
158
0
      DWORD waitDelay = 0;
159
0
      int ret = waitpid(process->pid, &(process->status), WNOHANG);
160
0
      if (ret == process->pid)
161
0
      {
162
0
        process->dwExitCode = (DWORD)process->status;
163
0
        return WAIT_OBJECT_0;
164
0
      }
165
0
      else if (ret < 0)
166
0
      {
167
0
        char ebuffer[256] = { 0 };
168
0
        WLog_ERR(TAG, "waitpid failure [%d] %s", errno,
169
0
                 winpr_strerror(errno, ebuffer, sizeof(ebuffer)));
170
0
        SetLastError(ERROR_INTERNAL_ERROR);
171
0
        return WAIT_FAILED;
172
0
      }
173
174
      /* sleep by slices of 50ms */
175
0
      waitDelay = (dwMilliseconds < 50) ? dwMilliseconds : 50;
176
177
0
      status = SleepEx(waitDelay, bAlertable);
178
0
      if (status != 0)
179
0
        return status;
180
181
0
      dwMilliseconds -= waitDelay;
182
183
0
    } while (dwMilliseconds > 50);
184
185
0
    return WAIT_TIMEOUT;
186
0
  }
187
188
0
  if (Type == HANDLE_TYPE_MUTEX)
189
0
  {
190
0
    WINPR_MUTEX* mutex = (WINPR_MUTEX*)Object;
191
192
0
    if (dwMilliseconds != INFINITE)
193
0
    {
194
0
      int status = 0;
195
0
      struct timespec timeout = ts_from_ns();
196
197
0
      ts_add_ms(&timeout, dwMilliseconds);
198
0
      status = pthread_mutex_timedlock(&mutex->mutex, &timeout);
199
200
0
      if (ETIMEDOUT == status)
201
0
        return WAIT_TIMEOUT;
202
0
    }
203
0
    else
204
0
    {
205
0
      pthread_mutex_lock(&mutex->mutex);
206
0
    }
207
208
0
    return WAIT_OBJECT_0;
209
0
  }
210
0
  else
211
0
  {
212
0
    int status = -1;
213
0
    WINPR_THREAD* thread = NULL;
214
0
    BOOL isSet = FALSE;
215
0
    size_t extraFds = 0;
216
0
    DWORD ret = 0;
217
0
    BOOL autoSignaled = FALSE;
218
219
0
    if (bAlertable)
220
0
    {
221
0
      thread = (WINPR_THREAD*)_GetCurrentThread();
222
0
      if (thread)
223
0
      {
224
        /* treat reentrancy, we can't switch to alertable state when we're already
225
           treating completions */
226
0
        if (thread->apc.treatingCompletions)
227
0
          bAlertable = FALSE;
228
0
        else
229
0
          extraFds = thread->apc.length;
230
0
      }
231
0
      else
232
0
      {
233
        /* called from a non WinPR thread */
234
0
        bAlertable = FALSE;
235
0
      }
236
0
    }
237
238
0
    int fd = winpr_Handle_getFd(Object);
239
0
    if (fd < 0)
240
0
    {
241
0
      WLog_ERR(TAG, "winpr_Handle_getFd did not return a fd!");
242
0
      SetLastError(ERROR_INVALID_HANDLE);
243
0
      return WAIT_FAILED;
244
0
    }
245
246
0
    if (!pollset_init(&pollset, 1 + extraFds))
247
0
    {
248
0
      WLog_ERR(TAG, "unable to initialize pollset");
249
0
      SetLastError(ERROR_INTERNAL_ERROR);
250
0
      return WAIT_FAILED;
251
0
    }
252
253
0
    if (!pollset_add(&pollset, fd, Object->Mode))
254
0
    {
255
0
      WLog_ERR(TAG, "unable to add fd in pollset");
256
0
      goto out;
257
0
    }
258
259
0
    if (bAlertable && !apc_collectFds(thread, &pollset, &autoSignaled))
260
0
    {
261
0
      WLog_ERR(TAG, "unable to collect APC fds");
262
0
      goto out;
263
0
    }
264
265
0
    if (!autoSignaled)
266
0
    {
267
0
      status = pollset_poll(&pollset, dwMilliseconds);
268
0
      if (status < 0)
269
0
      {
270
0
        char ebuffer[256] = { 0 };
271
0
        WLog_ERR(TAG, "pollset_poll() failure [%d] %s", errno,
272
0
                 winpr_strerror(errno, ebuffer, sizeof(ebuffer)));
273
0
        goto out;
274
0
      }
275
0
    }
276
277
0
    ret = WAIT_TIMEOUT;
278
0
    if (bAlertable && apc_executeCompletions(thread, &pollset, 1))
279
0
      ret = WAIT_IO_COMPLETION;
280
281
0
    isSet = pollset_isSignaled(&pollset, 0);
282
0
    pollset_uninit(&pollset);
283
284
0
    if (!isSet)
285
0
      return ret;
286
287
0
    return winpr_Handle_cleanup(Object);
288
0
  }
289
290
0
out:
291
0
  pollset_uninit(&pollset);
292
0
  SetLastError(ERROR_INTERNAL_ERROR);
293
0
  return WAIT_FAILED;
294
0
}
295
296
DWORD WaitForSingleObject(HANDLE hHandle, DWORD dwMilliseconds)
297
0
{
298
0
  return WaitForSingleObjectEx(hHandle, dwMilliseconds, FALSE);
299
0
}
300
301
DWORD WaitForMultipleObjectsEx(DWORD nCount, const HANDLE* lpHandles, BOOL bWaitAll,
302
                               DWORD dwMilliseconds, BOOL bAlertable)
303
0
{
304
0
  DWORD signalled = 0;
305
0
  DWORD polled = 0;
306
0
  DWORD poll_map[MAXIMUM_WAIT_OBJECTS] = { 0 };
307
0
  BOOL signalled_handles[MAXIMUM_WAIT_OBJECTS] = { FALSE };
308
0
  int fd = -1;
309
0
  int status = -1;
310
0
  ULONG Type = 0;
311
0
  WINPR_HANDLE* Object = NULL;
312
0
  WINPR_THREAD* thread = NULL;
313
0
  WINPR_POLL_SET pollset = { 0 };
314
0
  DWORD ret = WAIT_FAILED;
315
0
  size_t extraFds = 0;
316
0
  UINT64 now = 0;
317
0
  UINT64 dueTime = 0;
318
319
0
  if (!nCount || (nCount > MAXIMUM_WAIT_OBJECTS))
320
0
  {
321
0
    WLog_ERR(TAG, "invalid handles count(%" PRIu32 ")", nCount);
322
0
    return WAIT_FAILED;
323
0
  }
324
325
0
  if (bAlertable)
326
0
  {
327
0
    thread = winpr_GetCurrentThread();
328
0
    if (thread)
329
0
    {
330
      /* treat reentrancy, we can't switch to alertable state when we're already
331
         treating completions */
332
0
      if (thread->apc.treatingCompletions)
333
0
        bAlertable = FALSE;
334
0
      else
335
0
        extraFds = thread->apc.length;
336
0
    }
337
0
    else
338
0
    {
339
      /* most probably we're not called from WinPR thread, so we can't have any APC */
340
0
      bAlertable = FALSE;
341
0
    }
342
0
  }
343
344
0
  if (!pollset_init(&pollset, nCount + extraFds))
345
0
  {
346
0
    WLog_ERR(TAG, "unable to initialize pollset for nCount=%" PRIu32 " extraCount=%" PRIu32 "",
347
0
             nCount, extraFds);
348
0
    return WAIT_FAILED;
349
0
  }
350
351
0
  signalled = 0;
352
353
0
  now = GetTickCount64();
354
0
  if (dwMilliseconds != INFINITE)
355
0
    dueTime = now + dwMilliseconds;
356
0
  else
357
0
    dueTime = 0xFFFFFFFFFFFFFFFF;
358
359
0
  do
360
0
  {
361
0
    BOOL autoSignaled = FALSE;
362
0
    polled = 0;
363
364
    /* first collect file descriptors to poll */
365
0
    DWORD idx = 0;
366
0
    for (; idx < nCount; idx++)
367
0
    {
368
0
      if (bWaitAll)
369
0
      {
370
0
        if (signalled_handles[idx])
371
0
          continue;
372
373
0
        poll_map[polled] = idx;
374
0
      }
375
376
0
      if (!winpr_Handle_GetInfo(lpHandles[idx], &Type, &Object))
377
0
      {
378
0
        WLog_ERR(TAG, "invalid event file descriptor at %" PRIu32, idx);
379
0
        winpr_log_backtrace(TAG, WLOG_ERROR, 20);
380
0
        SetLastError(ERROR_INVALID_HANDLE);
381
0
        goto out;
382
0
      }
383
384
0
      fd = winpr_Handle_getFd(Object);
385
0
      if (fd == -1)
386
0
      {
387
0
        WLog_ERR(TAG, "invalid file descriptor at %" PRIu32, idx);
388
0
        winpr_log_backtrace(TAG, WLOG_ERROR, 20);
389
0
        SetLastError(ERROR_INVALID_HANDLE);
390
0
        goto out;
391
0
      }
392
393
0
      if (!pollset_add(&pollset, fd, Object->Mode))
394
0
      {
395
0
        WLog_ERR(TAG, "unable to register fd in pollset at %" PRIu32, idx);
396
0
        winpr_log_backtrace(TAG, WLOG_ERROR, 20);
397
0
        SetLastError(ERROR_INVALID_HANDLE);
398
0
        goto out;
399
0
      }
400
401
0
      polled++;
402
0
    }
403
404
    /* treat file descriptors of the APC if needed */
405
0
    if (bAlertable && !apc_collectFds(thread, &pollset, &autoSignaled))
406
0
    {
407
0
      WLog_ERR(TAG, "unable to register APC fds");
408
0
      winpr_log_backtrace(TAG, WLOG_ERROR, 20);
409
0
      SetLastError(ERROR_INTERNAL_ERROR);
410
0
      goto out;
411
0
    }
412
413
    /* poll file descriptors */
414
0
    status = 0;
415
0
    if (!autoSignaled)
416
0
    {
417
0
      DWORD waitTime = 0;
418
419
0
      if (dwMilliseconds == INFINITE)
420
0
        waitTime = INFINITE;
421
0
      else
422
0
        waitTime = (DWORD)(dueTime - now);
423
424
0
      status = pollset_poll(&pollset, waitTime);
425
0
      if (status < 0)
426
0
      {
427
0
        char ebuffer[256] = { 0 };
428
0
#ifdef WINPR_HAVE_POLL_H
429
0
        WLog_ERR(TAG, "poll() handle %" PRIu32 " (%" PRIu32 ") failure [%d] %s", idx,
430
0
                 nCount, errno, winpr_strerror(errno, ebuffer, sizeof(ebuffer)));
431
#else
432
        WLog_ERR(TAG, "select() handle %" PRIu32 " (%" PRIu32 ") failure [%d] %s", idx,
433
                 nCount, errno, winpr_strerror(errno, ebuffer, sizeof(ebuffer)));
434
#endif
435
0
        winpr_log_backtrace(TAG, WLOG_ERROR, 20);
436
0
        SetLastError(ERROR_INTERNAL_ERROR);
437
0
        goto out;
438
0
      }
439
0
    }
440
441
    /* give priority to the APC queue, to return WAIT_IO_COMPLETION */
442
0
    if (bAlertable && apc_executeCompletions(thread, &pollset, polled))
443
0
    {
444
0
      ret = WAIT_IO_COMPLETION;
445
0
      goto out;
446
0
    }
447
448
    /* then treat pollset */
449
0
    if (status)
450
0
    {
451
0
      for (DWORD index = 0; index < polled; index++)
452
0
      {
453
0
        DWORD handlesIndex = 0;
454
0
        BOOL signal_set = FALSE;
455
456
0
        if (bWaitAll)
457
0
          handlesIndex = poll_map[index];
458
0
        else
459
0
          handlesIndex = index;
460
461
0
        signal_set = pollset_isSignaled(&pollset, index);
462
0
        if (signal_set)
463
0
        {
464
0
          DWORD rc = winpr_Handle_cleanup(lpHandles[handlesIndex]);
465
0
          if (rc != WAIT_OBJECT_0)
466
0
          {
467
0
            WLog_ERR(TAG, "error in cleanup function for handle at index=%" PRIu32,
468
0
                     handlesIndex);
469
0
            ret = rc;
470
0
            goto out;
471
0
          }
472
473
0
          if (bWaitAll)
474
0
          {
475
0
            signalled_handles[handlesIndex] = TRUE;
476
477
            /* Continue checks from last position. */
478
0
            for (; signalled < nCount; signalled++)
479
0
            {
480
0
              if (!signalled_handles[signalled])
481
0
                break;
482
0
            }
483
0
          }
484
0
          else
485
0
          {
486
0
            ret = (WAIT_OBJECT_0 + handlesIndex);
487
0
            goto out;
488
0
          }
489
490
0
          if (signalled >= nCount)
491
0
          {
492
0
            ret = WAIT_OBJECT_0;
493
0
            goto out;
494
0
          }
495
0
        }
496
0
      }
497
0
    }
498
499
0
    if (bAlertable && thread->apc.length > extraFds)
500
0
    {
501
0
      pollset_uninit(&pollset);
502
0
      extraFds = thread->apc.length;
503
0
      if (!pollset_init(&pollset, nCount + extraFds))
504
0
      {
505
0
        WLog_ERR(TAG, "unable reallocate pollset");
506
0
        SetLastError(ERROR_INTERNAL_ERROR);
507
0
        return WAIT_FAILED;
508
0
      }
509
0
    }
510
0
    else
511
0
      pollset_reset(&pollset);
512
513
0
    now = GetTickCount64();
514
0
  } while (now < dueTime);
515
516
0
  ret = WAIT_TIMEOUT;
517
518
0
out:
519
0
  pollset_uninit(&pollset);
520
0
  return ret;
521
0
}
522
523
DWORD WaitForMultipleObjects(DWORD nCount, const HANDLE* lpHandles, BOOL bWaitAll,
524
                             DWORD dwMilliseconds)
525
0
{
526
0
  return WaitForMultipleObjectsEx(nCount, lpHandles, bWaitAll, dwMilliseconds, FALSE);
527
0
}
528
529
DWORD SignalObjectAndWait(HANDLE hObjectToSignal, HANDLE hObjectToWaitOn, DWORD dwMilliseconds,
530
                          BOOL bAlertable)
531
0
{
532
0
  if (!SetEvent(hObjectToSignal))
533
0
    return WAIT_FAILED;
534
535
0
  return WaitForSingleObjectEx(hObjectToWaitOn, dwMilliseconds, bAlertable);
536
0
}
537
538
#endif