Coverage Report

Created: 2026-11-10 06:43

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/FreeRDP/winpr/libwinpr/thread/thread.c
Line
Count
Source
1
/**
2
 * WinPR: Windows Portable Runtime
3
 * Process Thread Functions
4
 *
5
 * Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
6
 * Copyright 2015 Hewlett-Packard Development Company, L.P.
7
 * Copyright 2021 David Fort <contact@hardening-consulting.com>
8
 *
9
 *
10
 * Licensed under the Apache License, Version 2.0 (the "License");
11
 * you may not use this file except in compliance with the License.
12
 * You may obtain a copy of the License at
13
 *
14
 *     http://www.apache.org/licenses/LICENSE-2.0
15
 *
16
 * Unless required by applicable law or agreed to in writing, software
17
 * distributed under the License is distributed on an "AS IS" BASIS,
18
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
 * See the License for the specific language governing permissions and
20
 * limitations under the License.
21
 */
22
23
#include <winpr/config.h>
24
25
#include <winpr/winpr.h>
26
#include <winpr/assert.h>
27
28
#include <winpr/handle.h>
29
30
#include <winpr/thread.h>
31
32
#if defined(__FreeBSD__)
33
#include <pthread_np.h>
34
#elif defined(__linux__)
35
#include <sys/syscall.h>
36
#endif
37
38
#ifndef MIN
39
0
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
40
#endif
41
42
#ifndef MAX
43
0
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
44
#endif
45
46
/**
47
 * api-ms-win-core-processthreads-l1-1-1.dll
48
 *
49
 * CreateRemoteThread
50
 * CreateRemoteThreadEx
51
 * CreateThread
52
 * DeleteProcThreadAttributeList
53
 * ExitThread
54
 * FlushInstructionCache
55
 * FlushProcessWriteBuffers
56
 * GetCurrentThread
57
 * GetCurrentThreadId
58
 * GetCurrentThreadStackLimits
59
 * GetExitCodeThread
60
 * GetPriorityClass
61
 * GetStartupInfoW
62
 * GetThreadContext
63
 * GetThreadId
64
 * GetThreadIdealProcessorEx
65
 * GetThreadPriority
66
 * GetThreadPriorityBoost
67
 * GetThreadTimes
68
 * InitializeProcThreadAttributeList
69
 * OpenThread
70
 * OpenThreadToken
71
 * QueryProcessAffinityUpdateMode
72
 * QueueUserAPC
73
 * ResumeThread
74
 * SetPriorityClass
75
 * SetThreadContext
76
 * SetThreadPriority
77
 * SetThreadPriorityBoost
78
 * SetThreadStackGuarantee
79
 * SetThreadToken
80
 * SuspendThread
81
 * SwitchToThread
82
 * TerminateThread
83
 * UpdateProcThreadAttribute
84
 */
85
86
#ifndef _WIN32
87
88
#include <pthread.h>
89
#include <winpr/crt.h>
90
#include <winpr/platform.h>
91
92
#include <string.h>
93
#ifdef WINPR_HAVE_UNISTD_H
94
#include <unistd.h>
95
#endif
96
97
#ifdef WINPR_HAVE_SYS_EVENTFD_H
98
#include <sys/eventfd.h>
99
#endif
100
101
#include <winpr/debug.h>
102
103
#include <errno.h>
104
#include <fcntl.h>
105
106
#include <winpr/collections.h>
107
108
#include "thread.h"
109
#include "apc.h"
110
111
#include "../handle/handle.h"
112
#include "../log.h"
113
#define TAG WINPR_TAG("thread")
114
115
static WINPR_THREAD mainThread;
116
117
#if defined(WITH_THREAD_LIST)
118
static wListDictionary* thread_list = nullptr;
119
#endif
120
121
static BOOL ThreadCloseHandle(HANDLE handle);
122
static void cleanup_handle(void* obj);
123
124
static BOOL ThreadIsHandled(HANDLE handle)
125
0
{
126
0
  return WINPR_HANDLE_IS_HANDLED(handle, HANDLE_TYPE_THREAD, FALSE);
127
0
}
128
129
static int ThreadGetFd(HANDLE handle)
130
0
{
131
0
  WINPR_THREAD* pThread = (WINPR_THREAD*)handle;
132
133
0
  if (!ThreadIsHandled(handle))
134
0
    return -1;
135
136
0
  return pThread->event.fds[0];
137
0
}
138
139
0
#define run_mutex_init(fkt, mux, arg) run_mutex_init_(fkt, #fkt, mux, arg)
140
static BOOL run_mutex_init_(int (*fkt)(pthread_mutex_t*, const pthread_mutexattr_t*),
141
                            const char* name, pthread_mutex_t* mutex,
142
                            const pthread_mutexattr_t* mutexattr)
143
0
{
144
0
  int rc = 0;
145
146
0
  WINPR_ASSERT(fkt);
147
0
  WINPR_ASSERT(mutex);
148
149
0
  rc = fkt(mutex, mutexattr);
150
0
  if (rc != 0)
151
0
  {
152
0
    char ebuffer[256] = WINPR_C_ARRAY_INIT;
153
0
    WLog_WARN(TAG, "[%s] failed with [%s]", name, winpr_strerror(rc, ebuffer, sizeof(ebuffer)));
154
0
  }
155
0
  return rc == 0;
156
0
}
157
158
0
#define run_mutex_fkt(fkt, mux) run_mutex_fkt_(fkt, #fkt, mux)
159
static BOOL run_mutex_fkt_(int (*fkt)(pthread_mutex_t* mux), const char* name,
160
                           pthread_mutex_t* mutex)
161
0
{
162
0
  int rc = 0;
163
164
0
  WINPR_ASSERT(fkt);
165
0
  WINPR_ASSERT(mutex);
166
167
0
  rc = fkt(mutex);
168
0
  if (rc != 0)
169
0
  {
170
0
    char ebuffer[256] = WINPR_C_ARRAY_INIT;
171
0
    WLog_WARN(TAG, "[%s] failed with [%s]", name, winpr_strerror(rc, ebuffer, sizeof(ebuffer)));
172
0
  }
173
0
  return rc == 0;
174
0
}
175
176
0
#define run_cond_init(fkt, cond, arg) run_cond_init_(fkt, #fkt, cond, arg)
177
static BOOL run_cond_init_(int (*fkt)(pthread_cond_t*, const pthread_condattr_t*), const char* name,
178
                           pthread_cond_t* condition, const pthread_condattr_t* conditionattr)
179
0
{
180
0
  int rc = 0;
181
182
0
  WINPR_ASSERT(fkt);
183
0
  WINPR_ASSERT(condition);
184
185
0
  rc = fkt(condition, conditionattr);
186
0
  if (rc != 0)
187
0
  {
188
0
    char ebuffer[256] = WINPR_C_ARRAY_INIT;
189
0
    WLog_WARN(TAG, "[%s] failed with [%s]", name, winpr_strerror(rc, ebuffer, sizeof(ebuffer)));
190
0
  }
191
0
  return rc == 0;
192
0
}
193
194
0
#define run_cond_fkt(fkt, cond) run_cond_fkt_(fkt, #fkt, cond)
195
static BOOL run_cond_fkt_(int (*fkt)(pthread_cond_t* mux), const char* name,
196
                          pthread_cond_t* condition)
197
0
{
198
0
  int rc = 0;
199
200
0
  WINPR_ASSERT(fkt);
201
0
  WINPR_ASSERT(condition);
202
203
0
  rc = fkt(condition);
204
0
  if (rc != 0)
205
0
  {
206
0
    char ebuffer[256] = WINPR_C_ARRAY_INIT;
207
0
    WLog_WARN(TAG, "[%s] failed with [%s]", name, winpr_strerror(rc, ebuffer, sizeof(ebuffer)));
208
0
  }
209
0
  return rc == 0;
210
0
}
211
212
static int pthread_mutex_checked_unlock(pthread_mutex_t* mutex)
213
0
{
214
0
  WINPR_ASSERT(mutex);
215
0
  WINPR_ASSERT(pthread_mutex_trylock(mutex) == EBUSY);
216
0
  return pthread_mutex_unlock(mutex);
217
0
}
218
219
static BOOL mux_condition_bundle_init(mux_condition_bundle* bundle)
220
0
{
221
0
  WINPR_ASSERT(bundle);
222
223
0
  bundle->val = FALSE;
224
0
  if (!run_mutex_init(pthread_mutex_init, &bundle->mux, nullptr))
225
0
    return FALSE;
226
227
0
  if (!run_cond_init(pthread_cond_init, &bundle->cond, nullptr))
228
0
    return FALSE;
229
0
  return TRUE;
230
0
}
231
232
static void mux_condition_bundle_uninit(mux_condition_bundle* bundle)
233
0
{
234
0
  mux_condition_bundle empty = WINPR_C_ARRAY_INIT;
235
236
0
  WINPR_ASSERT(bundle);
237
238
0
  run_cond_fkt(pthread_cond_destroy, &bundle->cond);
239
0
  run_mutex_fkt(pthread_mutex_destroy, &bundle->mux);
240
0
  *bundle = empty;
241
0
}
242
243
static BOOL mux_condition_bundle_signal(mux_condition_bundle* bundle)
244
0
{
245
0
  BOOL rc = TRUE;
246
0
  WINPR_ASSERT(bundle);
247
248
0
  if (!run_mutex_fkt(pthread_mutex_lock, &bundle->mux))
249
0
    return FALSE;
250
0
  bundle->val = TRUE;
251
0
  if (!run_cond_fkt(pthread_cond_signal, &bundle->cond))
252
0
    rc = FALSE;
253
0
  if (!run_mutex_fkt(pthread_mutex_checked_unlock, &bundle->mux))
254
0
    rc = FALSE;
255
0
  return rc;
256
0
}
257
258
static BOOL mux_condition_bundle_lock(mux_condition_bundle* bundle)
259
0
{
260
0
  WINPR_ASSERT(bundle);
261
0
  return run_mutex_fkt(pthread_mutex_lock, &bundle->mux);
262
0
}
263
264
static BOOL mux_condition_bundle_unlock(mux_condition_bundle* bundle)
265
0
{
266
0
  WINPR_ASSERT(bundle);
267
0
  return run_mutex_fkt(pthread_mutex_checked_unlock, &bundle->mux);
268
0
}
269
270
static BOOL mux_condition_bundle_wait(mux_condition_bundle* bundle, const char* name)
271
0
{
272
0
  BOOL rc = FALSE;
273
274
0
  WINPR_ASSERT(bundle);
275
0
  WINPR_ASSERT(name);
276
0
  WINPR_ASSERT(pthread_mutex_trylock(&bundle->mux) == EBUSY);
277
278
0
  while (!bundle->val)
279
0
  {
280
0
    int r = pthread_cond_wait(&bundle->cond, &bundle->mux);
281
0
    if (r != 0)
282
0
    {
283
0
      char ebuffer[256] = WINPR_C_ARRAY_INIT;
284
0
      WLog_ERR(TAG, "failed to wait for %s [%s]", name,
285
0
               winpr_strerror(r, ebuffer, sizeof(ebuffer)));
286
0
      switch (r)
287
0
      {
288
0
        case ENOTRECOVERABLE:
289
0
        case EPERM:
290
0
        case ETIMEDOUT:
291
0
        case EINVAL:
292
0
          goto fail;
293
294
0
        default:
295
0
          break;
296
0
      }
297
0
    }
298
0
  }
299
300
0
  rc = bundle->val;
301
302
0
fail:
303
0
  return rc;
304
0
}
305
306
static BOOL signal_thread_ready(WINPR_THREAD* thread)
307
0
{
308
0
  WINPR_ASSERT(thread);
309
310
0
  return mux_condition_bundle_signal(&thread->isCreated);
311
0
}
312
313
static BOOL signal_thread_is_running(WINPR_THREAD* thread)
314
0
{
315
0
  WINPR_ASSERT(thread);
316
317
0
  return mux_condition_bundle_signal(&thread->isRunning);
318
0
}
319
320
static DWORD ThreadCleanupHandle(HANDLE handle)
321
0
{
322
0
  DWORD status = WAIT_FAILED;
323
0
  WINPR_THREAD* thread = (WINPR_THREAD*)handle;
324
325
0
  if (!ThreadIsHandled(handle))
326
0
    return WAIT_FAILED;
327
328
0
  if (!run_mutex_fkt(pthread_mutex_lock, &thread->mutex))
329
0
    return WAIT_FAILED;
330
331
0
  if (!thread->joined)
332
0
  {
333
0
    int rc = pthread_join(thread->thread, nullptr);
334
335
0
    if (rc != 0)
336
0
    {
337
0
      char ebuffer[256] = WINPR_C_ARRAY_INIT;
338
0
      WLog_ERR(TAG, "pthread_join failure: [%d] %s", rc,
339
0
               winpr_strerror(rc, ebuffer, sizeof(ebuffer)));
340
0
      goto fail;
341
0
    }
342
0
    else
343
0
      thread->joined = TRUE;
344
0
  }
345
346
0
  status = WAIT_OBJECT_0;
347
348
0
fail:
349
0
  if (!run_mutex_fkt(pthread_mutex_checked_unlock, &thread->mutex))
350
0
    return WAIT_FAILED;
351
352
0
  return status;
353
0
}
354
355
static HANDLE_OPS ops = { ThreadIsHandled, ThreadCloseHandle, ThreadGetFd, ThreadCleanupHandle,
356
                        nullptr,         nullptr,           nullptr,     nullptr,
357
                        nullptr,         nullptr,           nullptr,     nullptr,
358
                        nullptr,         nullptr,           nullptr,     nullptr,
359
                        nullptr,         nullptr,           nullptr,     nullptr,
360
                        nullptr };
361
362
static void dump_thread(WINPR_THREAD* thread)
363
0
{
364
#if defined(WITH_DEBUG_THREADS)
365
  void* stack = winpr_backtrace(20);
366
  char** msg = nullptr;
367
  size_t used = 0;
368
  WLog_DBG(TAG, "Called from:");
369
  msg = winpr_backtrace_symbols(stack, &used);
370
371
  for (size_t i = 0; i < used; i++)
372
    WLog_DBG(TAG, "[%" PRIuz "]: %s", i, msg[i]);
373
374
  free((void*)msg);
375
  winpr_backtrace_free(stack);
376
  WLog_DBG(TAG, "Thread handle created still not closed!");
377
  msg = winpr_backtrace_symbols(thread->create_stack, &used);
378
379
  for (size_t i = 0; i < used; i++)
380
    WLog_DBG(TAG, "[%" PRIuz "]: %s", i, msg[i]);
381
382
  free((void*)msg);
383
384
  if (thread->started)
385
  {
386
    WLog_DBG(TAG, "Thread still running!");
387
  }
388
  else if (!thread->exit_stack)
389
  {
390
    WLog_DBG(TAG, "Thread suspended.");
391
  }
392
  else
393
  {
394
    WLog_DBG(TAG, "Thread exited at:");
395
    msg = winpr_backtrace_symbols(thread->exit_stack, &used);
396
397
    for (size_t i = 0; i < used; i++)
398
      WLog_DBG(TAG, "[%" PRIuz "]: %s", i, msg[i]);
399
400
    free((void*)msg);
401
  }
402
#else
403
0
  WINPR_UNUSED(thread);
404
0
#endif
405
0
}
406
407
/**
408
 * TODO: implement thread suspend/resume using pthreads
409
 * http://stackoverflow.com/questions/3140867/suspend-pthreads-without-using-condition
410
 */
411
static BOOL set_event(WINPR_THREAD* thread)
412
0
{
413
0
  return winpr_event_set(&thread->event);
414
0
}
415
416
static BOOL reset_event(WINPR_THREAD* thread)
417
0
{
418
0
  return winpr_event_reset(&thread->event);
419
0
}
420
421
#if defined(WITH_THREAD_LIST)
422
static BOOL thread_compare(const void* a, const void* b)
423
{
424
  const pthread_t* p1 = a;
425
  const pthread_t* p2 = b;
426
  BOOL rc = pthread_equal(*p1, *p2);
427
  return rc;
428
}
429
#endif
430
431
static INIT_ONCE threads_InitOnce = INIT_ONCE_STATIC_INIT;
432
static pthread_t mainThreadId;
433
static pthread_key_t currentThreadTlsIndex = 0;
434
435
static BOOL initializeThreads(WINPR_ATTR_UNUSED PINIT_ONCE InitOnce,
436
                              WINPR_ATTR_UNUSED PVOID Parameter, WINPR_ATTR_UNUSED PVOID* Context)
437
0
{
438
0
  if (!apc_init(&mainThread.apc))
439
0
  {
440
0
    WLog_ERR(TAG, "failed to initialize APC");
441
0
    goto out;
442
0
  }
443
444
0
  mainThread.common.Type = HANDLE_TYPE_THREAD;
445
0
  mainThreadId = pthread_self();
446
447
0
  const int res = pthread_key_create(&currentThreadTlsIndex, nullptr);
448
0
  if (res != 0)
449
0
  {
450
0
    WLog_ERR(TAG, "Major bug, unable to allocate a TLS value for currentThread");
451
0
    return FALSE;
452
0
  }
453
454
#if defined(WITH_THREAD_LIST)
455
  thread_list = ListDictionary_New(TRUE);
456
457
  if (!thread_list)
458
  {
459
    WLog_ERR(TAG, "Couldn't create global thread list");
460
    goto error_thread_list;
461
  }
462
463
  thread_list->objectKey.fnObjectEquals = thread_compare;
464
#endif
465
466
0
out:
467
0
  return TRUE;
468
0
}
469
470
static BOOL signal_and_wait_for_ready(WINPR_THREAD* thread)
471
0
{
472
0
  BOOL res = FALSE;
473
474
0
  WINPR_ASSERT(thread);
475
476
0
  if (!mux_condition_bundle_lock(&thread->isRunning))
477
0
    return FALSE;
478
479
0
  if (!signal_thread_ready(thread))
480
0
    goto fail;
481
482
0
  if (!mux_condition_bundle_wait(&thread->isRunning, "threadIsRunning"))
483
0
    goto fail;
484
485
#if defined(WITH_THREAD_LIST)
486
  if (!ListDictionary_Contains(thread_list, &thread->thread))
487
  {
488
    WLog_ERR(TAG, "Thread not in thread_list, startup failed!");
489
    goto fail;
490
  }
491
#endif
492
493
0
  res = TRUE;
494
495
0
fail:
496
0
  if (!mux_condition_bundle_unlock(&thread->isRunning))
497
0
    return FALSE;
498
499
0
  return res;
500
0
}
501
502
/* Thread launcher function responsible for registering
503
 * cleanup handlers and calling pthread_exit, if not done
504
 * in thread function. */
505
static void* thread_launcher(void* arg)
506
0
{
507
0
  DWORD rc = 0;
508
0
  WINPR_THREAD* thread = (WINPR_THREAD*)arg;
509
0
  LPTHREAD_START_ROUTINE fkt = nullptr;
510
511
0
  if (!thread)
512
0
  {
513
0
    WLog_ERR(TAG, "Called with invalid argument %p", arg);
514
0
    goto exit;
515
0
  }
516
517
0
  const int res = pthread_setspecific(currentThreadTlsIndex, thread);
518
0
  if (res != 0)
519
0
  {
520
0
    WLog_ERR(TAG, "thread %" PRIu64 ", unable to set current thread value",
521
0
             WINPR_CXX_COMPAT_CAST(uint64_t, pthread_self()));
522
0
    goto exit;
523
0
  }
524
525
0
  if (!(fkt = thread->lpStartAddress))
526
0
  {
527
0
    union
528
0
    {
529
0
      LPTHREAD_START_ROUTINE fkt;
530
0
      void* pv;
531
0
    } cnv;
532
0
    cnv.fkt = fkt;
533
0
    WLog_ERR(TAG, "Thread function argument is %p", cnv.pv);
534
0
    goto exit;
535
0
  }
536
537
0
  if (!signal_and_wait_for_ready(thread))
538
0
    goto exit;
539
540
0
  rc = fkt(thread->lpParameter);
541
0
exit:
542
543
0
  if (thread)
544
0
  {
545
0
    apc_cleanupThread(thread);
546
547
0
    if (!thread->exited)
548
0
      thread->dwExitCode = rc;
549
550
0
    set_event(thread);
551
552
0
    (void)signal_thread_ready(thread);
553
554
0
    if (thread->detached || !thread->started)
555
0
      cleanup_handle(thread);
556
0
  }
557
558
0
  return nullptr;
559
0
}
560
561
static BOOL winpr_StartThread(WINPR_THREAD* thread)
562
0
{
563
0
  BOOL rc = FALSE;
564
0
  BOOL locked = FALSE;
565
0
  pthread_attr_t attr = WINPR_C_ARRAY_INIT;
566
567
0
  if (!mux_condition_bundle_lock(&thread->isCreated))
568
0
    return FALSE;
569
0
  locked = TRUE;
570
571
0
  pthread_attr_init(&attr);
572
0
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
573
574
0
  size_t stackSize = thread->dwStackSize;
575
0
  if (stackSize == 0)
576
0
  {
577
0
    size_t platformDefault = 0;
578
0
    if ((pthread_attr_getstacksize(&attr, &platformDefault) == 0) &&
579
0
        (platformDefault < WINPR_THREAD_DEFAULT_STACK_SIZE))
580
0
      stackSize = WINPR_THREAD_DEFAULT_STACK_SIZE;
581
0
  }
582
583
0
  if (stackSize > 0)
584
0
  {
585
0
    const int err = pthread_attr_setstacksize(&attr, stackSize);
586
0
    if (err != 0)
587
0
    {
588
0
      char ebuffer[256] = WINPR_C_ARRAY_INIT;
589
0
      WLog_WARN(TAG, "pthread_attr_setstacksize(%" PRIuz ") failed: %s", stackSize,
590
0
                winpr_strerror(err, ebuffer, sizeof(ebuffer)));
591
0
    }
592
0
  }
593
594
0
  thread->started = TRUE;
595
0
  reset_event(thread);
596
597
#if defined(WITH_THREAD_LIST)
598
  if (!ListDictionary_Add(thread_list, &thread->thread, thread))
599
  {
600
    WLog_ERR(TAG, "failed to add the thread to the thread list");
601
    goto error;
602
  }
603
#endif
604
605
0
  if (pthread_create(&thread->thread, &attr, thread_launcher, thread))
606
0
    goto error;
607
608
0
  if (!mux_condition_bundle_wait(&thread->isCreated, "threadIsCreated"))
609
0
    goto error;
610
611
0
  locked = FALSE;
612
0
  if (!mux_condition_bundle_unlock(&thread->isCreated))
613
0
    goto error;
614
615
0
  if (!signal_thread_is_running(thread))
616
0
  {
617
0
    WLog_ERR(TAG, "failed to signal the thread was ready");
618
0
    goto error;
619
0
  }
620
621
0
  rc = TRUE;
622
0
error:
623
0
  if (locked)
624
0
  {
625
0
    if (!mux_condition_bundle_unlock(&thread->isCreated))
626
0
      rc = FALSE;
627
0
  }
628
629
0
  pthread_attr_destroy(&attr);
630
631
0
  if (rc)
632
0
    dump_thread(thread);
633
634
0
  return rc;
635
0
}
636
637
BOOL SetThreadPriority(HANDLE hThread, int nPriority)
638
0
{
639
0
  ULONG Type = 0;
640
0
  WINPR_HANDLE* Object = nullptr;
641
642
0
  if (!winpr_Handle_GetInfo(hThread, &Type, &Object) || Object->Type != HANDLE_TYPE_THREAD)
643
0
    return FALSE;
644
645
0
  const int min = 19;
646
0
  const int max = 0;
647
0
  const int diff = (max - min);
648
0
  const int normal = min + diff / 2;
649
0
  const int off = MIN(1, diff / 4);
650
0
  int sched_priority = -1;
651
652
0
  switch (nPriority & ~(THREAD_MODE_BACKGROUND_BEGIN | THREAD_MODE_BACKGROUND_END))
653
0
  {
654
0
    case THREAD_PRIORITY_ABOVE_NORMAL:
655
0
      sched_priority = MIN(normal + off, max);
656
0
      break;
657
0
    case THREAD_PRIORITY_BELOW_NORMAL:
658
0
      sched_priority = MAX(normal - off, min);
659
0
      break;
660
0
    case THREAD_PRIORITY_HIGHEST:
661
0
      sched_priority = max;
662
0
      break;
663
0
    case THREAD_PRIORITY_IDLE:
664
0
      sched_priority = min;
665
0
      break;
666
0
    case THREAD_PRIORITY_LOWEST:
667
0
      sched_priority = min;
668
0
      break;
669
0
    case THREAD_PRIORITY_TIME_CRITICAL:
670
0
      sched_priority = max;
671
0
      break;
672
0
    default:
673
0
    case THREAD_PRIORITY_NORMAL:
674
0
      sched_priority = normal;
675
0
      break;
676
0
  }
677
0
#if defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 200809L) && defined(PTHREAD_SETSCHEDPRIO)
678
0
  WINPR_THREAD* thread = (WINPR_THREAD*)Object;
679
0
  const int rc = pthread_setschedprio(thread->thread, sched_priority);
680
0
  if (rc != 0)
681
0
  {
682
0
    char buffer[256] = WINPR_C_ARRAY_INIT;
683
0
    WLog_ERR(TAG, "pthread_setschedprio(%d) %s [%d]", sched_priority,
684
0
             winpr_strerror(rc, buffer, sizeof(buffer)), rc);
685
0
  }
686
0
  return rc == 0;
687
#else
688
  WLog_WARN(TAG, "pthread_setschedprio(%d) not implemented, requires POSIX 2008 or later",
689
            sched_priority);
690
  return TRUE;
691
#endif
692
0
}
693
694
HANDLE CreateThread(LPSECURITY_ATTRIBUTES lpThreadAttributes, size_t dwStackSize,
695
                    LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter,
696
                    DWORD dwCreationFlags, WINPR_ATTR_UNUSED LPDWORD lpThreadId)
697
0
{
698
0
  HANDLE handle = nullptr;
699
0
  WINPR_THREAD* thread = (WINPR_THREAD*)calloc(1, sizeof(WINPR_THREAD));
700
701
0
  if (!thread)
702
0
    return nullptr;
703
704
0
  thread->dwStackSize = dwStackSize;
705
0
  thread->lpParameter = lpParameter;
706
0
  thread->lpStartAddress = lpStartAddress;
707
0
  thread->lpThreadAttributes = lpThreadAttributes;
708
0
  thread->common.ops = &ops;
709
#if defined(WITH_DEBUG_THREADS)
710
  thread->create_stack = winpr_backtrace(20);
711
  dump_thread(thread);
712
#endif
713
714
0
  if (!winpr_event_init(&thread->event))
715
0
  {
716
0
    WLog_ERR(TAG, "failed to create event");
717
0
    goto fail;
718
0
  }
719
720
0
  if (!run_mutex_init(pthread_mutex_init, &thread->mutex, nullptr))
721
0
  {
722
0
    WLog_ERR(TAG, "failed to initialize thread mutex");
723
0
    goto fail;
724
0
  }
725
726
0
  if (!apc_init(&thread->apc))
727
0
  {
728
0
    WLog_ERR(TAG, "failed to initialize APC");
729
0
    goto fail;
730
0
  }
731
732
0
  if (!mux_condition_bundle_init(&thread->isCreated))
733
0
    goto fail;
734
0
  if (!mux_condition_bundle_init(&thread->isRunning))
735
0
    goto fail;
736
737
0
  WINPR_HANDLE_SET_TYPE_AND_MODE(thread, HANDLE_TYPE_THREAD, WINPR_FD_READ);
738
0
  handle = (HANDLE)thread;
739
740
0
  if (!InitOnceExecuteOnce(&threads_InitOnce, initializeThreads, nullptr, nullptr))
741
0
    goto fail;
742
743
0
  if (!(dwCreationFlags & CREATE_SUSPENDED))
744
0
  {
745
0
    if (!winpr_StartThread(thread))
746
0
      goto fail;
747
0
  }
748
0
  else
749
0
  {
750
0
    if (!set_event(thread))
751
0
      goto fail;
752
0
  }
753
754
0
  return handle;
755
0
fail:
756
0
  cleanup_handle(thread);
757
0
  return nullptr;
758
0
}
759
760
void cleanup_handle(void* obj)
761
0
{
762
0
  WINPR_THREAD* thread = (WINPR_THREAD*)obj;
763
0
  if (!thread)
764
0
    return;
765
766
0
  if (!apc_uninit(&thread->apc))
767
0
    WLog_ERR(TAG, "failed to destroy APC");
768
769
0
  mux_condition_bundle_uninit(&thread->isCreated);
770
0
  mux_condition_bundle_uninit(&thread->isRunning);
771
0
  run_mutex_fkt(pthread_mutex_destroy, &thread->mutex);
772
773
0
  winpr_event_uninit(&thread->event);
774
775
#if defined(WITH_THREAD_LIST)
776
  ListDictionary_Remove(thread_list, &thread->thread);
777
#endif
778
#if defined(WITH_DEBUG_THREADS)
779
780
  if (thread->create_stack)
781
    winpr_backtrace_free(thread->create_stack);
782
783
  if (thread->exit_stack)
784
    winpr_backtrace_free(thread->exit_stack);
785
786
#endif
787
0
  free(thread);
788
0
}
789
790
BOOL ThreadCloseHandle(HANDLE handle)
791
0
{
792
0
  WINPR_THREAD* thread = (WINPR_THREAD*)handle;
793
794
#if defined(WITH_THREAD_LIST)
795
  if (!thread_list)
796
  {
797
    WLog_ERR(TAG, "Thread list does not exist, check call!");
798
    dump_thread(thread);
799
  }
800
  else if (!ListDictionary_Contains(thread_list, &thread->thread))
801
  {
802
    WLog_ERR(TAG, "Thread list does not contain this thread! check call!");
803
    dump_thread(thread);
804
  }
805
  else
806
  {
807
    ListDictionary_Lock(thread_list);
808
#endif
809
0
    dump_thread(thread);
810
811
0
    if ((thread->started) && (WaitForSingleObject(thread, 0) != WAIT_OBJECT_0))
812
0
    {
813
0
      WLog_DBG(TAG, "Thread running, setting to detached state!");
814
0
      thread->detached = TRUE;
815
0
      pthread_detach(thread->thread);
816
0
    }
817
0
    else
818
0
    {
819
0
      cleanup_handle(thread);
820
0
    }
821
822
#if defined(WITH_THREAD_LIST)
823
    ListDictionary_Unlock(thread_list);
824
  }
825
#endif
826
827
0
  return TRUE;
828
0
}
829
830
HANDLE CreateRemoteThread(WINPR_ATTR_UNUSED HANDLE hProcess,
831
                          WINPR_ATTR_UNUSED LPSECURITY_ATTRIBUTES lpThreadAttributes,
832
                          WINPR_ATTR_UNUSED size_t dwStackSize,
833
                          WINPR_ATTR_UNUSED LPTHREAD_START_ROUTINE lpStartAddress,
834
                          WINPR_ATTR_UNUSED LPVOID lpParameter,
835
                          WINPR_ATTR_UNUSED DWORD dwCreationFlags,
836
                          WINPR_ATTR_UNUSED LPDWORD lpThreadId)
837
0
{
838
0
  WLog_ERR(TAG, "not implemented");
839
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
840
0
  return nullptr;
841
0
}
842
843
VOID ExitThread(DWORD dwExitCode)
844
0
{
845
#if defined(WITH_THREAD_LIST)
846
  DWORD rc;
847
  pthread_t tid = pthread_self();
848
849
  if (!thread_list)
850
  {
851
    WLog_ERR(TAG, "function called without existing thread list!");
852
#if defined(WITH_DEBUG_THREADS)
853
    DumpThreadHandles();
854
#endif
855
    pthread_exit(0);
856
  }
857
  else if (!ListDictionary_Contains(thread_list, &tid))
858
  {
859
    WLog_ERR(TAG, "function called, but no matching entry in thread list!");
860
#if defined(WITH_DEBUG_THREADS)
861
    DumpThreadHandles();
862
#endif
863
    pthread_exit(0);
864
  }
865
  else
866
  {
867
    WINPR_THREAD* thread;
868
    ListDictionary_Lock(thread_list);
869
    thread = ListDictionary_GetItemValue(thread_list, &tid);
870
    WINPR_ASSERT(thread);
871
    thread->exited = TRUE;
872
    thread->dwExitCode = dwExitCode;
873
#if defined(WITH_DEBUG_THREADS)
874
    thread->exit_stack = winpr_backtrace(20);
875
#endif
876
    ListDictionary_Unlock(thread_list);
877
    set_event(thread);
878
    rc = thread->dwExitCode;
879
880
    if (thread->detached || !thread->started)
881
      cleanup_handle(thread);
882
883
    pthread_exit((void*)(size_t)rc);
884
  }
885
#else
886
0
  WINPR_UNUSED(dwExitCode);
887
0
#endif
888
0
}
889
890
BOOL GetExitCodeThread(HANDLE hThread, LPDWORD lpExitCode)
891
0
{
892
0
  ULONG Type = 0;
893
0
  WINPR_HANDLE* Object = nullptr;
894
0
  WINPR_THREAD* thread = nullptr;
895
896
0
  if (!winpr_Handle_GetInfo(hThread, &Type, &Object) || Object->Type != HANDLE_TYPE_THREAD)
897
0
  {
898
0
    WLog_ERR(TAG, "hThread is not a thread");
899
0
    SetLastError(ERROR_INVALID_PARAMETER);
900
0
    return FALSE;
901
0
  }
902
903
0
  thread = (WINPR_THREAD*)Object;
904
0
  *lpExitCode = thread->dwExitCode;
905
0
  return TRUE;
906
0
}
907
908
WINPR_THREAD* winpr_GetCurrentThread(VOID)
909
0
{
910
0
  WINPR_THREAD* ret = nullptr;
911
912
0
  if (!InitOnceExecuteOnce(&threads_InitOnce, initializeThreads, nullptr, nullptr))
913
0
    return nullptr;
914
0
  if (mainThreadId == pthread_self())
915
0
    return (HANDLE)&mainThread;
916
917
0
  ret = pthread_getspecific(currentThreadTlsIndex);
918
0
  return ret;
919
0
}
920
921
HANDLE _GetCurrentThread(VOID)
922
0
{
923
0
  return (HANDLE)winpr_GetCurrentThread();
924
0
}
925
926
DWORD GetCurrentThreadId(VOID)
927
1.05M
{
928
#if defined(__FreeBSD__)
929
  return WINPR_CXX_COMPAT_CAST(DWORD, pthread_getthreadid_np());
930
#elif defined(__OpenBSD__)
931
  return WINPR_CXX_COMPAT_CAST(DWORD, getthrid());
932
#elif defined(__linux__)
933
1.05M
  return WINPR_CXX_COMPAT_CAST(DWORD, syscall(SYS_gettid));
934
#else
935
  pthread_t tid = pthread_self();
936
  /* Since pthread_t can be 64-bits on some systems, take just the    */
937
  /* lower 32-bits of it for the thread ID returned by this function. */
938
  uintptr_t ptid = WINPR_REINTERPRET_CAST(tid, pthread_t, uintptr_t);
939
#if UINTPTR_MAX > UINT32_MAX
940
  return (ptid & UINT32_MAX) ^ (ptid >> 32);
941
#else
942
  /* A 32-bit pthread_t already fits. Shifting it by 32 is undefined behaviour and
943
   * WebAssembly masks the shift count to 0, so the expression above returned
944
   * ptid ^ ptid == 0 for every thread, and critical sections took any thread for
945
   * the owner. */
946
  return WINPR_CXX_COMPAT_CAST(DWORD, ptid);
947
#endif
948
#endif
949
1.05M
}
950
951
typedef struct
952
{
953
  WINPR_APC_ITEM apc;
954
  PAPCFUNC completion;
955
  ULONG_PTR completionArg;
956
} UserApcItem;
957
958
static void userAPC(LPVOID arg)
959
0
{
960
0
  UserApcItem* userApc = (UserApcItem*)arg;
961
962
0
  userApc->completion(userApc->completionArg);
963
964
0
  userApc->apc.markedForRemove = TRUE;
965
0
}
966
967
DWORD QueueUserAPC(PAPCFUNC pfnAPC, HANDLE hThread, ULONG_PTR dwData)
968
0
{
969
0
  ULONG Type = 0;
970
0
  WINPR_HANDLE* Object = nullptr;
971
0
  WINPR_APC_ITEM* apc = nullptr;
972
0
  UserApcItem* apcItem = nullptr;
973
974
0
  if (!pfnAPC)
975
0
    return 1;
976
977
0
  if (!winpr_Handle_GetInfo(hThread, &Type, &Object) || Object->Type != HANDLE_TYPE_THREAD)
978
0
  {
979
0
    WLog_ERR(TAG, "hThread is not a thread");
980
0
    SetLastError(ERROR_INVALID_PARAMETER);
981
0
    return (DWORD)0;
982
0
  }
983
984
0
  apcItem = calloc(1, sizeof(*apcItem));
985
0
  if (!apcItem)
986
0
  {
987
0
    SetLastError(ERROR_INVALID_PARAMETER);
988
0
    return (DWORD)0;
989
0
  }
990
991
0
  apc = &apcItem->apc;
992
0
  apc->type = APC_TYPE_USER;
993
0
  apc->markedForFree = TRUE;
994
0
  apc->alwaysSignaled = TRUE;
995
0
  apc->completion = userAPC;
996
0
  apc->completionArgs = apc;
997
0
  apcItem->completion = pfnAPC;
998
0
  apcItem->completionArg = dwData;
999
0
  apc_register(hThread, apc);
1000
0
  return 1;
1001
0
}
1002
1003
DWORD ResumeThread(HANDLE hThread)
1004
0
{
1005
0
  ULONG Type = 0;
1006
0
  WINPR_HANDLE* Object = nullptr;
1007
0
  WINPR_THREAD* thread = nullptr;
1008
1009
0
  if (!winpr_Handle_GetInfo(hThread, &Type, &Object) || Object->Type != HANDLE_TYPE_THREAD)
1010
0
  {
1011
0
    WLog_ERR(TAG, "hThread is not a thread");
1012
0
    SetLastError(ERROR_INVALID_PARAMETER);
1013
0
    return (DWORD)-1;
1014
0
  }
1015
1016
0
  thread = (WINPR_THREAD*)Object;
1017
1018
0
  if (!run_mutex_fkt(pthread_mutex_lock, &thread->mutex))
1019
0
    return (DWORD)-1;
1020
1021
0
  if (!thread->started)
1022
0
  {
1023
0
    if (!winpr_StartThread(thread))
1024
0
    {
1025
0
      run_mutex_fkt(pthread_mutex_checked_unlock, &thread->mutex);
1026
0
      return (DWORD)-1;
1027
0
    }
1028
0
  }
1029
0
  else
1030
0
    WLog_WARN(TAG, "Thread already started!");
1031
1032
0
  if (!run_mutex_fkt(pthread_mutex_checked_unlock, &thread->mutex))
1033
0
    return (DWORD)-1;
1034
1035
0
  return 0;
1036
0
}
1037
1038
DWORD SuspendThread(WINPR_ATTR_UNUSED HANDLE hThread)
1039
0
{
1040
0
  WLog_ERR(TAG, "not implemented");
1041
0
  SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1042
0
  return (DWORD)-1;
1043
0
}
1044
1045
BOOL SwitchToThread(VOID)
1046
0
{
1047
  /**
1048
   * Note: on some operating systems sched_yield is a stub returning -1.
1049
   * usleep should at least trigger a context switch if any thread is waiting.
1050
   */
1051
0
  if (sched_yield() != 0)
1052
0
    usleep(1);
1053
1054
0
  return TRUE;
1055
0
}
1056
1057
BOOL TerminateThread(HANDLE hThread, DWORD dwExitCode)
1058
0
{
1059
0
  ULONG Type = 0;
1060
0
  WINPR_HANDLE* Object = nullptr;
1061
0
  WINPR_THREAD* thread = nullptr;
1062
1063
0
  if (!winpr_Handle_GetInfo(hThread, &Type, &Object) || Object->Type != HANDLE_TYPE_THREAD)
1064
0
    return FALSE;
1065
1066
0
  thread = (WINPR_THREAD*)Object;
1067
0
  thread->exited = TRUE;
1068
0
  thread->dwExitCode = dwExitCode;
1069
1070
0
  if (!run_mutex_fkt(pthread_mutex_lock, &thread->mutex))
1071
0
    return FALSE;
1072
1073
0
#ifndef ANDROID
1074
0
  pthread_cancel(thread->thread);
1075
#else
1076
  WLog_ERR(TAG, "Function not supported on this platform!");
1077
#endif
1078
1079
0
  if (!run_mutex_fkt(pthread_mutex_checked_unlock, &thread->mutex))
1080
0
    return FALSE;
1081
1082
0
  set_event(thread);
1083
0
  return TRUE;
1084
0
}
1085
1086
VOID DumpThreadHandles(void)
1087
0
{
1088
#if defined(WITH_DEBUG_THREADS)
1089
  char** msg = nullptr;
1090
  size_t used = 0;
1091
  void* stack = winpr_backtrace(20);
1092
  WLog_DBG(TAG, "---------------- Called from ----------------------------");
1093
  msg = winpr_backtrace_symbols(stack, &used);
1094
1095
  for (size_t i = 0; i < used; i++)
1096
  {
1097
    WLog_DBG(TAG, "[%" PRIuz "]: %s", i, msg[i]);
1098
  }
1099
1100
  free((void*)msg);
1101
  winpr_backtrace_free(stack);
1102
  WLog_DBG(TAG, "---------------- Start Dumping thread handles -----------");
1103
1104
#if defined(WITH_THREAD_LIST)
1105
  if (!thread_list)
1106
  {
1107
    WLog_DBG(TAG, "All threads properly shut down and disposed of.");
1108
  }
1109
  else
1110
  {
1111
    ULONG_PTR* keys = nullptr;
1112
    ListDictionary_Lock(thread_list);
1113
    int x, count = ListDictionary_GetKeys(thread_list, &keys);
1114
    WLog_DBG(TAG, "Dumping %d elements", count);
1115
1116
    for (size_t x = 0; x < count; x++)
1117
    {
1118
      WINPR_THREAD* thread = ListDictionary_GetItemValue(thread_list, (void*)keys[x]);
1119
      WLog_DBG(TAG, "Thread [%d] handle created still not closed!", x);
1120
      msg = winpr_backtrace_symbols(thread->create_stack, &used);
1121
1122
      for (size_t i = 0; i < used; i++)
1123
      {
1124
        WLog_DBG(TAG, "[%" PRIdz "]: %s", i, msg[i]);
1125
      }
1126
1127
      free(msg);
1128
1129
      if (thread->started)
1130
      {
1131
        WLog_DBG(TAG, "Thread [%d] still running!", x);
1132
      }
1133
      else
1134
      {
1135
        WLog_DBG(TAG, "Thread [%d] exited at:", x);
1136
        msg = winpr_backtrace_symbols(thread->exit_stack, &used);
1137
1138
        for (size_t i = 0; i < used; i++)
1139
          WLog_DBG(TAG, "[%" PRIdz "]: %s", i, msg[i]);
1140
1141
        free(msg);
1142
      }
1143
    }
1144
1145
    free(keys);
1146
    ListDictionary_Unlock(thread_list);
1147
  }
1148
#endif
1149
1150
  WLog_DBG(TAG, "---------------- End Dumping thread handles -------------");
1151
#endif
1152
0
}
1153
#endif