1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
|
/*
* Copyright 2019-2025 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <internal/thread_arch.h>
#if defined(OPENSSL_THREADS_WINNT)
# include <process.h>
# include <windows.h>
static unsigned __stdcall thread_start_thunk(LPVOID vthread)
{
CRYPTO_THREAD *thread;
CRYPTO_THREAD_RETVAL ret;
thread = (CRYPTO_THREAD *)vthread;
thread->thread_id = GetCurrentThreadId();
ret = thread->routine(thread->data);
ossl_crypto_mutex_lock(thread->statelock);
CRYPTO_THREAD_SET_STATE(thread, CRYPTO_THREAD_FINISHED);
thread->retval = ret;
ossl_crypto_condvar_signal(thread->condvar);
ossl_crypto_mutex_unlock(thread->statelock);
return 0;
}
int ossl_crypto_thread_native_spawn(CRYPTO_THREAD *thread)
{
HANDLE *handle;
handle = OPENSSL_zalloc(sizeof(*handle));
if (handle == NULL)
goto fail;
*handle = (HANDLE)_beginthreadex(NULL, 0, &thread_start_thunk, thread, 0, NULL);
if (*handle == NULL)
goto fail;
thread->handle = handle;
return 1;
fail:
thread->handle = NULL;
OPENSSL_free(handle);
return 0;
}
int ossl_crypto_thread_native_perform_join(CRYPTO_THREAD *thread, CRYPTO_THREAD_RETVAL *retval)
{
DWORD thread_retval;
HANDLE *handle;
if (thread == NULL || thread->handle == NULL)
return 0;
handle = (HANDLE *) thread->handle;
if (WaitForSingleObject(*handle, INFINITE) != WAIT_OBJECT_0)
return 0;
if (GetExitCodeThread(*handle, &thread_retval) == 0)
return 0;
/*
* GetExitCodeThread call followed by this check is to make sure that
* the thread exited properly. In particular, thread_retval may be
* non-zero when exited via explicit ExitThread/TerminateThread or
* if the thread is still active (returns STILL_ACTIVE (259)).
*/
if (thread_retval != 0)
return 0;
if (CloseHandle(*handle) == 0)
return 0;
return 1;
}
int ossl_crypto_thread_native_exit(void)
{
_endthreadex(0);
return 1;
}
int ossl_crypto_thread_native_is_self(CRYPTO_THREAD *thread)
{
return thread->thread_id == GetCurrentThreadId();
}
CRYPTO_MUTEX *ossl_crypto_mutex_new(void)
{
CRITICAL_SECTION *mutex;
if ((mutex = OPENSSL_zalloc(sizeof(*mutex))) == NULL)
return NULL;
InitializeCriticalSection(mutex);
return (CRYPTO_MUTEX *)mutex;
}
void ossl_crypto_mutex_lock(CRYPTO_MUTEX *mutex)
{
CRITICAL_SECTION *mutex_p;
mutex_p = (CRITICAL_SECTION *)mutex;
EnterCriticalSection(mutex_p);
}
int ossl_crypto_mutex_try_lock(CRYPTO_MUTEX *mutex)
{
CRITICAL_SECTION *mutex_p;
mutex_p = (CRITICAL_SECTION *)mutex;
if (TryEnterCriticalSection(mutex_p))
return 1;
return 0;
}
void ossl_crypto_mutex_unlock(CRYPTO_MUTEX *mutex)
{
CRITICAL_SECTION *mutex_p;
mutex_p = (CRITICAL_SECTION *)mutex;
LeaveCriticalSection(mutex_p);
}
void ossl_crypto_mutex_free(CRYPTO_MUTEX **mutex)
{
CRITICAL_SECTION **mutex_p;
mutex_p = (CRITICAL_SECTION **)mutex;
if (*mutex_p != NULL)
DeleteCriticalSection(*mutex_p);
OPENSSL_free(*mutex_p);
*mutex = NULL;
}
static int determine_timeout(OSSL_TIME deadline, DWORD *w_timeout_p)
{
OSSL_TIME now, delta;
uint64_t ms;
if (ossl_time_is_infinite(deadline)) {
*w_timeout_p = INFINITE;
return 1;
}
now = ossl_time_now();
delta = ossl_time_subtract(deadline, now);
if (ossl_time_is_zero(delta))
return 0;
ms = ossl_time2ms(delta);
/*
* Amount of time we want to wait is too long for the 32-bit argument to
* the Win32 API, so just wait as long as possible.
*/
if (ms > (uint64_t)(INFINITE - 1))
*w_timeout_p = INFINITE - 1;
else
*w_timeout_p = (DWORD)ms;
return 1;
}
# if defined(OPENSSL_THREADS_WINNT_LEGACY)
# include <assert.h>
/*
* Win32, before Vista, did not have an OS-provided condition variable
* construct. This leads to the need to construct our own condition variable
* construct in order to support Windows XP.
*
* It is difficult to construct a condition variable construct using the
* OS-provided primitives in a way that is both correct (avoiding race
* conditions where broadcasts get lost) and fair.
*
* CORRECTNESS:
* A blocked thread is a thread which is calling wait(), between the
* precise instants at which the external mutex passed to wait() is
* unlocked and the instant at which it is relocked.
*
* a)
* - If broadcast() is called, ALL blocked threads MUST be unblocked.
* - If signal() is called, at least one blocked thread MUST be unblocked.
*
* (i.e.: a signal or broadcast must never get 'lost')
*
* b)
* - If broadcast() or signal() is called, this must not cause a thread
* which is not blocked to return immediately from a subsequent
* call to wait().
*
* FAIRNESS:
* If broadcast() is called at time T1, all blocked threads must be unblocked
* before any thread which subsequently calls wait() at time T2 > T1 is
* unblocked.
*
* An example of an implementation which lacks fairness is as follows:
*
* t1 enters wait()
* t2 enters wait()
*
* tZ calls broadcast()
*
* t1 exits wait()
* t1 enters wait()
*
* tZ calls broadcast()
*
* t1 exits wait()
*
* IMPLEMENTATION:
*
* The most suitable primitives available to us in Windows XP are semaphores,
* auto-reset events and manual-reset events. A solution based on semaphores
* is chosen.
*
* PROBLEM. Designing a solution based on semaphores is non-trivial because,
* while it is easy to track the number of waiters in an interlocked data
* structure and then add that number to the semaphore, this does not
* guarantee fairness or correctness. Consider the following situation:
*
* - t1 enters wait(), adding 1 to the wait counter & blocks on the semaphore
* - t2 enters wait(), adding 1 to the wait counter & blocks on the semaphore
* - tZ calls broadcast(), finds the wait counter is 2, adds 2 to the semaphore
*
* - t1 exits wait()
* - t1 immediately reenters wait() and blocks on the semaphore
* - The semaphore is still positive due to also having been signalled
* for t2, therefore it is decremented
* - t1 exits wait() immediately; t2 is never woken
*
* GENERATION COUNTERS. One naive solution to this is to use a generation
* counter. Each broadcast() invocation increments a generation counter. If
* the generation counter has not changed during a semaphore wait operation
* inside wait(), this indicates that no broadcast() call has been made in
* the meantime; therefore, the successful semaphore decrement must have
* 'stolen' a wakeup from another thread which was waiting to wakeup from the
* prior broadcast() call but which had not yet had a chance to do so. The
* semaphore can then be reincremented and the wait() operation repeated.
*
* However, this suffers from the obvious problem that without OS guarantees
* as to how semaphore readiness events are distributed amongst threads,
* there is no particular guarantee that the semaphore readiness event will
* not be immediately redistributed back to the same thread t1.
*
* SOLUTION. A solution is chosen as follows. In its initial state, a
* condition variable can accept waiters, who wait for the semaphore
* normally. However, once broadcast() is called, the condition
* variable becomes 'closed'. Any existing blocked threads are unblocked,
* but any new calls to wait() will instead enter a blocking pre-wait stage.
* Pre-wait threads are not considered to be waiting (and the external
* mutex remains held). A call to wait() in pre-wait cannot progress
* to waiting until all threads due to be unblocked by the prior broadcast()
* call have returned and had a chance to execute.
*
* This pre-wait does not affect a thread if it does not call wait()
* again until after all threads have had a chance to execute.
*
* RESOURCE USAGE. Aside from an allocation for the condition variable
* structure, this solution uses two Win32 semaphores.
*
* FUTURE OPTIMISATIONS:
*
* An optimised multi-generation implementation is possible at the cost of
* higher Win32 resource usage. Multiple 'buckets' could be defined, with
* usage rotating between buckets internally as buckets become closed.
* This would avoid the need for the prewait in more cases, depending
* on intensity of usage.
*
*/
typedef struct legacy_condvar_st {
CRYPTO_MUTEX *int_m; /* internal mutex */
HANDLE sema; /* main wait semaphore */
HANDLE prewait_sema; /* prewait semaphore */
/*
* All of the following fields are protected by int_m.
*
* num_wake only ever increases by virtue of a corresponding decrease in
* num_wait. num_wait can decrease for other reasons (for example due to a
* wait operation timing out).
*/
size_t num_wait; /* Num. threads currently blocked */
size_t num_wake; /* Num. threads due to wake up */
size_t num_prewait; /* Num. threads in prewait */
size_t gen; /* Prewait generation */
int closed; /* Is closed? */
} LEGACY_CONDVAR;
CRYPTO_CONDVAR *ossl_crypto_condvar_new(void)
{
LEGACY_CONDVAR *cv;
if ((cv = OPENSSL_malloc(sizeof(LEGACY_CONDVAR))) == NULL)
return NULL;
if ((cv->int_m = ossl_crypto_mutex_new()) == NULL) {
OPENSSL_free(cv);
return NULL;
}
if ((cv->sema = CreateSemaphoreA(NULL, 0, LONG_MAX, NULL)) == NULL) {
ossl_crypto_mutex_free(&cv->int_m);
OPENSSL_free(cv);
return NULL;
}
if ((cv->prewait_sema = CreateSemaphoreA(NULL, 0, LONG_MAX, NULL)) == NULL) {
CloseHandle(cv->sema);
ossl_crypto_mutex_free(&cv->int_m);
OPENSSL_free(cv);
return NULL;
}
cv->num_wait = 0;
cv->num_wake = 0;
cv->num_prewait = 0;
cv->closed = 0;
return (CRYPTO_CONDVAR *)cv;
}
void ossl_crypto_condvar_free(CRYPTO_CONDVAR **cv_p)
{
if (*cv_p != NULL) {
LEGACY_CONDVAR *cv = *(LEGACY_CONDVAR **)cv_p;
CloseHandle(cv->sema);
CloseHandle(cv->prewait_sema);
ossl_crypto_mutex_free(&cv->int_m);
OPENSSL_free(cv);
}
*cv_p = NULL;
}
static uint32_t obj_wait(HANDLE h, OSSL_TIME deadline)
{
DWORD timeout;
if (!determine_timeout(deadline, &timeout))
timeout = 1;
return WaitForSingleObject(h, timeout);
}
void ossl_crypto_condvar_wait_timeout(CRYPTO_CONDVAR *cv_, CRYPTO_MUTEX *ext_m,
OSSL_TIME deadline)
{
LEGACY_CONDVAR *cv = (LEGACY_CONDVAR *)cv_;
int closed, set_prewait = 0, have_orig_gen = 0;
uint32_t rc;
size_t orig_gen;
/* Admission control - prewait until we can enter our actual wait phase. */
do {
ossl_crypto_mutex_lock(cv->int_m);
closed = cv->closed;
/*
* Once prewait is over the prewait semaphore is signalled and
* num_prewait is set to 0. Use a generation counter to track if we need
* to remove a value we added to num_prewait when exiting (e.g. due to
* timeout or failure of WaitForSingleObject).
*/
if (!have_orig_gen) {
orig_gen = cv->gen;
have_orig_gen = 1;
} else if (cv->gen != orig_gen) {
set_prewait = 0;
orig_gen = cv->gen;
}
if (!closed) {
/* We can now be admitted. */
++cv->num_wait;
if (set_prewait) {
--cv->num_prewait;
set_prewait = 0;
}
} else if (!set_prewait) {
++cv->num_prewait;
set_prewait = 1;
}
ossl_crypto_mutex_unlock(cv->int_m);
if (closed)
if (obj_wait(cv->prewait_sema, deadline) != WAIT_OBJECT_0) {
/*
* If we got WAIT_OBJECT_0 we are safe - num_prewait has been
* set to 0 and the semaphore has been consumed. On the other
* hand if we timed out, there may be a residual posting that
* was made just after we timed out. However in the worst case
* this will just cause an internal spurious wakeup here in the
* future, so we do not care too much about this. We treat
* failure and timeout cases as the same, and simply exit in
* this case.
*/
ossl_crypto_mutex_lock(cv->int_m);
if (set_prewait && cv->gen == orig_gen)
--cv->num_prewait;
ossl_crypto_mutex_unlock(cv->int_m);
return;
}
} while (closed);
/*
* Unlock external mutex. Do not do this until we have been admitted, as we
* must guarantee we wake if broadcast is called at any time after ext_m is
* unlocked.
*/
ossl_crypto_mutex_unlock(ext_m);
for (;;) {
/* Wait. */
rc = obj_wait(cv->sema, deadline);
/* Reacquire internal mutex and probe state. */
ossl_crypto_mutex_lock(cv->int_m);
if (cv->num_wake > 0) {
/*
* A wake token is available, so we can wake up. Consume the token
* and get out of here. We don't care what WaitForSingleObject
* returned here (e.g. if it timed out coincidentally). In the
* latter case a signal might be left in the semaphore which causes
* a future WaitForSingleObject call to return immediately, but in
* this case we will just loop again.
*/
--cv->num_wake;
if (cv->num_wake == 0 && cv->closed) {
/*
* We consumed the last wake token, so we can now open the
* condition variable for new admissions.
*/
cv->closed = 0;
if (cv->num_prewait > 0) {
ReleaseSemaphore(cv->prewait_sema, (LONG)cv->num_prewait, NULL);
cv->num_prewait = 0;
++cv->gen;
}
}
} else if (rc == WAIT_OBJECT_0) {
/*
* We got a wakeup from the semaphore but we did not have any wake
* tokens. This ideally does not happen, but might if during a
* previous wait() call the semaphore is posted just after
* WaitForSingleObject returns due to a timeout (such that the
* num_wake > 0 case is taken above). Just spin again. (It is worth
* noting that repeated WaitForSingleObject calls is the only method
* documented for decrementing a Win32 semaphore, so this is
* basically the best possible strategy.)
*/
ossl_crypto_mutex_unlock(cv->int_m);
continue;
} else {
/*
* Assume we timed out. The WaitForSingleObject call may also have
* failed for some other reason, which we treat as a timeout.
*/
assert(cv->num_wait > 0);
--cv->num_wait;
}
break;
}
ossl_crypto_mutex_unlock(cv->int_m);
ossl_crypto_mutex_lock(ext_m);
}
void ossl_crypto_condvar_wait(CRYPTO_CONDVAR *cv, CRYPTO_MUTEX *ext_m)
{
ossl_crypto_condvar_wait_timeout(cv, ext_m, ossl_time_infinite());
}
void ossl_crypto_condvar_broadcast(CRYPTO_CONDVAR *cv_)
{
LEGACY_CONDVAR *cv = (LEGACY_CONDVAR *)cv_;
size_t num_wake;
ossl_crypto_mutex_lock(cv->int_m);
num_wake = cv->num_wait;
if (num_wake == 0) {
ossl_crypto_mutex_unlock(cv->int_m);
return;
}
cv->num_wake += num_wake;
cv->num_wait -= num_wake;
cv->closed = 1;
ossl_crypto_mutex_unlock(cv->int_m);
ReleaseSemaphore(cv->sema, (LONG)num_wake, NULL);
}
void ossl_crypto_condvar_signal(CRYPTO_CONDVAR *cv_)
{
LEGACY_CONDVAR *cv = (LEGACY_CONDVAR *)cv_;
ossl_crypto_mutex_lock(cv->int_m);
if (cv->num_wait == 0) {
ossl_crypto_mutex_unlock(cv->int_m);
return;
}
/*
* We do not close the condition variable when merely signalling, as there
* are no guaranteed fairness semantics here, unlike for a broadcast.
*/
--cv->num_wait;
++cv->num_wake;
ossl_crypto_mutex_unlock(cv->int_m);
ReleaseSemaphore(cv->sema, 1, NULL);
}
# else
CRYPTO_CONDVAR *ossl_crypto_condvar_new(void)
{
CONDITION_VARIABLE *cv_p;
if ((cv_p = OPENSSL_zalloc(sizeof(*cv_p))) == NULL)
return NULL;
InitializeConditionVariable(cv_p);
return (CRYPTO_CONDVAR *)cv_p;
}
void ossl_crypto_condvar_wait(CRYPTO_CONDVAR *cv, CRYPTO_MUTEX *mutex)
{
CONDITION_VARIABLE *cv_p;
CRITICAL_SECTION *mutex_p;
cv_p = (CONDITION_VARIABLE *)cv;
mutex_p = (CRITICAL_SECTION *)mutex;
SleepConditionVariableCS(cv_p, mutex_p, INFINITE);
}
void ossl_crypto_condvar_wait_timeout(CRYPTO_CONDVAR *cv, CRYPTO_MUTEX *mutex,
OSSL_TIME deadline)
{
DWORD timeout;
CONDITION_VARIABLE *cv_p = (CONDITION_VARIABLE *)cv;
CRITICAL_SECTION *mutex_p = (CRITICAL_SECTION *)mutex;
if (!determine_timeout(deadline, &timeout))
timeout = 1;
SleepConditionVariableCS(cv_p, mutex_p, timeout);
}
void ossl_crypto_condvar_broadcast(CRYPTO_CONDVAR *cv)
{
CONDITION_VARIABLE *cv_p;
cv_p = (CONDITION_VARIABLE *)cv;
WakeAllConditionVariable(cv_p);
}
void ossl_crypto_condvar_signal(CRYPTO_CONDVAR *cv)
{
CONDITION_VARIABLE *cv_p;
cv_p = (CONDITION_VARIABLE *)cv;
WakeConditionVariable(cv_p);
}
void ossl_crypto_condvar_free(CRYPTO_CONDVAR **cv)
{
CONDITION_VARIABLE **cv_p;
cv_p = (CONDITION_VARIABLE **)cv;
OPENSSL_free(*cv_p);
*cv_p = NULL;
}
# endif
void ossl_crypto_mem_barrier(void)
{
MemoryBarrier();
}
#endif
|