2 * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
14 #include <openssl/crypto.h>
16 #if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG) && defined(OPENSSL_SYS_WINDOWS)
18 CRYPTO_RWLOCK *CRYPTO_THREAD_lock_new(void)
20 CRYPTO_RWLOCK *lock = OPENSSL_zalloc(sizeof(CRITICAL_SECTION));
24 /* 0x400 is the spin count value suggested in the documentation */
25 if (!InitializeCriticalSectionAndSpinCount(lock, 0x400)) {
33 int CRYPTO_THREAD_read_lock(CRYPTO_RWLOCK *lock)
35 EnterCriticalSection(lock);
39 int CRYPTO_THREAD_write_lock(CRYPTO_RWLOCK *lock)
41 EnterCriticalSection(lock);
45 int CRYPTO_THREAD_unlock(CRYPTO_RWLOCK *lock)
47 LeaveCriticalSection(lock);
51 void CRYPTO_THREAD_lock_free(CRYPTO_RWLOCK *lock)
56 DeleteCriticalSection(lock);
62 # define ONCE_UNINITED 0
63 # define ONCE_ININIT 1
67 * We don't use InitOnceExecuteOnce because that isn't available in WinXP which
68 * we still have to support.
70 int CRYPTO_THREAD_run_once(CRYPTO_ONCE *once, void (*init)(void))
72 LONG volatile *lock = (LONG *)once;
75 if (*lock == ONCE_DONE)
79 result = InterlockedCompareExchange(lock, ONCE_ININIT, ONCE_UNINITED);
80 if (result == ONCE_UNINITED) {
85 } while (result == ONCE_ININIT);
87 return (*lock == ONCE_DONE);
90 int CRYPTO_THREAD_init_local(CRYPTO_THREAD_LOCAL *key, void (*cleanup)(void *))
93 if (*key == TLS_OUT_OF_INDEXES)
99 void *CRYPTO_THREAD_get_local(CRYPTO_THREAD_LOCAL *key)
101 return TlsGetValue(*key);
104 int CRYPTO_THREAD_set_local(CRYPTO_THREAD_LOCAL *key, void *val)
106 if (TlsSetValue(*key, val) == 0)
112 int CRYPTO_THREAD_cleanup_local(CRYPTO_THREAD_LOCAL *key)
114 if (TlsFree(*key) == 0)
120 CRYPTO_THREAD_ID CRYPTO_THREAD_get_current_id(void)
122 return GetCurrentThreadId();
125 int CRYPTO_THREAD_compare_id(CRYPTO_THREAD_ID a, CRYPTO_THREAD_ID b)
130 int CRYPTO_atomic_add(int *val, int amount, int *ret, CRYPTO_RWLOCK *lock)
132 *ret = InterlockedExchangeAdd(val, amount) + amount;