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
10 #include <openssl/crypto.h>
12 #if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG) && defined(OPENSSL_SYS_WINDOWS)
14 CRYPTO_RWLOCK *CRYPTO_THREAD_lock_new(void)
16 CRYPTO_RWLOCK *lock = OPENSSL_zalloc(sizeof(CRITICAL_SECTION));
20 /* 0x400 is the spin count value suggested in the documentation */
21 if (!InitializeCriticalSectionAndSpinCount(lock, 0x400)) {
29 int CRYPTO_THREAD_read_lock(CRYPTO_RWLOCK *lock)
31 EnterCriticalSection(lock);
35 int CRYPTO_THREAD_write_lock(CRYPTO_RWLOCK *lock)
37 EnterCriticalSection(lock);
41 int CRYPTO_THREAD_unlock(CRYPTO_RWLOCK *lock)
43 LeaveCriticalSection(lock);
47 void CRYPTO_THREAD_lock_free(CRYPTO_RWLOCK *lock)
52 DeleteCriticalSection(lock);
58 # define ONCE_UNINITED 0
59 # define ONCE_ININIT 1
63 * We don't use InitOnceExecuteOnce because that isn't available in WinXP which
64 * we still have to support.
66 int CRYPTO_THREAD_run_once(CRYPTO_ONCE *once, void (*init)(void))
68 LONG volatile *lock = (LONG *)once;
71 if (*lock == ONCE_DONE)
75 result = InterlockedCompareExchange(lock, ONCE_ININIT, ONCE_UNINITED);
76 if (result == ONCE_UNINITED) {
81 } while (result == ONCE_ININIT);
83 return (*lock == ONCE_DONE);
86 int CRYPTO_THREAD_init_local(CRYPTO_THREAD_LOCAL *key, void (*cleanup)(void *))
89 if (*key == TLS_OUT_OF_INDEXES)
95 void *CRYPTO_THREAD_get_local(CRYPTO_THREAD_LOCAL *key)
97 return TlsGetValue(*key);
100 int CRYPTO_THREAD_set_local(CRYPTO_THREAD_LOCAL *key, void *val)
102 if (TlsSetValue(*key, val) == 0)
108 int CRYPTO_THREAD_cleanup_local(CRYPTO_THREAD_LOCAL *key)
110 if (TlsFree(*key) == 0)
116 CRYPTO_THREAD_ID CRYPTO_THREAD_get_current_id(void)
118 return GetCurrentThreadId();
121 int CRYPTO_THREAD_compare_id(CRYPTO_THREAD_ID a, CRYPTO_THREAD_ID b)
126 int CRYPTO_atomic_add(int *val, int amount, int *ret, CRYPTO_RWLOCK *lock)
128 *ret = InterlockedExchangeAdd(val, amount) + amount;