thread_win.c
Go to the documentation of this file.
1 /* Copyright (c) 2015, Google Inc.
2  *
3  * Permission to use, copy, modify, and/or distribute this software for any
4  * purpose with or without fee is hereby granted, provided that the above
5  * copyright notice and this permission notice appear in all copies.
6  *
7  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14 
15 #include "internal.h"
16 
17 #if defined(OPENSSL_WINDOWS_THREADS)
18 
20 #include <windows.h>
22 
23 #include <stdlib.h>
24 #include <string.h>
25 
26 #include <openssl/mem.h>
27 #include <openssl/type_check.h>
28 
29 
30 OPENSSL_STATIC_ASSERT(sizeof(CRYPTO_MUTEX) >= sizeof(SRWLOCK),
31  "CRYPTO_MUTEX is too small");
32 #if defined(__GNUC__) || defined(__clang__)
33 OPENSSL_STATIC_ASSERT(alignof(CRYPTO_MUTEX) >= alignof(SRWLOCK),
34  "CRYPTO_MUTEX has insufficient alignment");
35 #endif
36 
37 static BOOL CALLBACK call_once_init(INIT_ONCE *once, void *arg, void **out) {
38  void (**init)(void) = (void (**)(void))arg;
39  (**init)();
40  return TRUE;
41 }
42 
43 void CRYPTO_once(CRYPTO_once_t *once, void (*init)(void)) {
44  if (!InitOnceExecuteOnce(once, call_once_init, &init, NULL)) {
45  abort();
46  }
47 }
48 
49 void CRYPTO_MUTEX_init(CRYPTO_MUTEX *lock) {
50  InitializeSRWLock((SRWLOCK *) lock);
51 }
52 
54  AcquireSRWLockShared((SRWLOCK *) lock);
55 }
56 
58  AcquireSRWLockExclusive((SRWLOCK *) lock);
59 }
60 
62  ReleaseSRWLockShared((SRWLOCK *) lock);
63 }
64 
66  ReleaseSRWLockExclusive((SRWLOCK *) lock);
67 }
68 
70  // SRWLOCKs require no cleanup.
71 }
72 
74  AcquireSRWLockShared(&lock->lock);
75 }
76 
78  AcquireSRWLockExclusive(&lock->lock);
79 }
80 
82  ReleaseSRWLockShared(&lock->lock);
83 }
84 
86  ReleaseSRWLockExclusive(&lock->lock);
87 }
88 
89 static SRWLOCK g_destructors_lock = SRWLOCK_INIT;
91 
92 static CRYPTO_once_t g_thread_local_init_once = CRYPTO_ONCE_INIT;
93 static DWORD g_thread_local_key;
94 static int g_thread_local_failed;
95 
96 static void thread_local_init(void) {
97  g_thread_local_key = TlsAlloc();
98  g_thread_local_failed = (g_thread_local_key == TLS_OUT_OF_INDEXES);
99 }
100 
101 static void NTAPI thread_local_destructor(PVOID module, DWORD reason,
102  PVOID reserved) {
103  // Only free memory on |DLL_THREAD_DETACH|, not |DLL_PROCESS_DETACH|. In
104  // VS2015's debug runtime, the C runtime has been unloaded by the time
105  // |DLL_PROCESS_DETACH| runs. See https://crbug.com/575795. This is consistent
106  // with |pthread_key_create| which does not call destructors on process exit,
107  // only thread exit.
108  if (reason != DLL_THREAD_DETACH) {
109  return;
110  }
111 
112  CRYPTO_once(&g_thread_local_init_once, thread_local_init);
113  if (g_thread_local_failed) {
114  return;
115  }
116 
117  void **pointers = (void**) TlsGetValue(g_thread_local_key);
118  if (pointers == NULL) {
119  return;
120  }
121 
123 
124  AcquireSRWLockExclusive(&g_destructors_lock);
125  OPENSSL_memcpy(destructors, g_destructors, sizeof(destructors));
126  ReleaseSRWLockExclusive(&g_destructors_lock);
127 
128  for (unsigned i = 0; i < NUM_OPENSSL_THREAD_LOCALS; i++) {
129  if (destructors[i] != NULL) {
130  destructors[i](pointers[i]);
131  }
132  }
133 
134  OPENSSL_free(pointers);
135 }
136 
137 // Thread Termination Callbacks.
138 //
139 // Windows doesn't support a per-thread destructor with its TLS primitives.
140 // So, we build it manually by inserting a function to be called on each
141 // thread's exit. This magic is from http://www.codeproject.com/threads/tls.asp
142 // and it works for VC++ 7.0 and later.
143 //
144 // Force a reference to _tls_used to make the linker create the TLS directory
145 // if it's not already there. (E.g. if __declspec(thread) is not used). Force
146 // a reference to p_thread_callback_boringssl to prevent whole program
147 // optimization from discarding the variable.
148 //
149 // Note, in the prefixed build, |p_thread_callback_boringssl| may be a macro.
150 #define STRINGIFY(x) #x
151 #define EXPAND_AND_STRINGIFY(x) STRINGIFY(x)
152 #ifdef _WIN64
153 __pragma(comment(linker, "/INCLUDE:_tls_used"))
154 __pragma(comment(
155  linker, "/INCLUDE:" EXPAND_AND_STRINGIFY(p_thread_callback_boringssl)))
156 #else
157 __pragma(comment(linker, "/INCLUDE:__tls_used"))
158 __pragma(comment(
159  linker, "/INCLUDE:_" EXPAND_AND_STRINGIFY(p_thread_callback_boringssl)))
160 #endif
161 
162 // .CRT$XLA to .CRT$XLZ is an array of PIMAGE_TLS_CALLBACK pointers that are
163 // called automatically by the OS loader code (not the CRT) when the module is
164 // loaded and on thread creation. They are NOT called if the module has been
165 // loaded by a LoadLibrary() call. It must have implicitly been loaded at
166 // process startup.
167 //
168 // By implicitly loaded, I mean that it is directly referenced by the main EXE
169 // or by one of its dependent DLLs. Delay-loaded DLL doesn't count as being
170 // implicitly loaded.
171 //
172 // See VC\crt\src\tlssup.c for reference.
173 
174 // The linker must not discard p_thread_callback_boringssl. (We force a
175 // reference to this variable with a linker /INCLUDE:symbol pragma to ensure
176 // that.) If this variable is discarded, the OnThreadExit function will never
177 // be called.
178 #ifdef _WIN64
179 
180 // .CRT section is merged with .rdata on x64 so it must be constant data.
181 #pragma const_seg(".CRT$XLC")
182 // When defining a const variable, it must have external linkage to be sure the
183 // linker doesn't discard it.
184 extern const PIMAGE_TLS_CALLBACK p_thread_callback_boringssl;
185 const PIMAGE_TLS_CALLBACK p_thread_callback_boringssl = thread_local_destructor;
186 // Reset the default section.
187 #pragma const_seg()
188 
189 #else
190 
191 #pragma data_seg(".CRT$XLC")
192 PIMAGE_TLS_CALLBACK p_thread_callback_boringssl = thread_local_destructor;
193 // Reset the default section.
194 #pragma data_seg()
195 
196 #endif // _WIN64
197 
198 static void **get_thread_locals(void) {
199  // |TlsGetValue| clears the last error even on success, so that callers may
200  // distinguish it successfully returning NULL or failing. It is documented to
201  // never fail if the argument is a valid index from |TlsAlloc|, so we do not
202  // need to handle this.
203  //
204  // However, this error-mangling behavior interferes with the caller's use of
205  // |GetLastError|. In particular |SSL_get_error| queries the error queue to
206  // determine whether the caller should look at the OS's errors. To avoid
207  // destroying state, save and restore the Windows error.
208  //
209  // https://msdn.microsoft.com/en-us/library/windows/desktop/ms686812(v=vs.85).aspx
210  DWORD last_error = GetLastError();
211  void **ret = TlsGetValue(g_thread_local_key);
212  SetLastError(last_error);
213  return ret;
214 }
215 
217  CRYPTO_once(&g_thread_local_init_once, thread_local_init);
218  if (g_thread_local_failed) {
219  return NULL;
220  }
221 
222  void **pointers = get_thread_locals();
223  if (pointers == NULL) {
224  return NULL;
225  }
226  return pointers[index];
227 }
228 
230  thread_local_destructor_t destructor) {
231  CRYPTO_once(&g_thread_local_init_once, thread_local_init);
232  if (g_thread_local_failed) {
233  destructor(value);
234  return 0;
235  }
236 
237  void **pointers = get_thread_locals();
238  if (pointers == NULL) {
239  pointers = OPENSSL_malloc(sizeof(void *) * NUM_OPENSSL_THREAD_LOCALS);
240  if (pointers == NULL) {
241  destructor(value);
242  return 0;
243  }
244  OPENSSL_memset(pointers, 0, sizeof(void *) * NUM_OPENSSL_THREAD_LOCALS);
245  if (TlsSetValue(g_thread_local_key, pointers) == 0) {
246  OPENSSL_free(pointers);
247  destructor(value);
248  return 0;
249  }
250  }
251 
252  AcquireSRWLockExclusive(&g_destructors_lock);
253  g_destructors[index] = destructor;
254  ReleaseSRWLockExclusive(&g_destructors_lock);
255 
256  pointers[index] = value;
257  return 1;
258 }
259 
260 #endif // OPENSSL_WINDOWS_THREADS
TRUE
const BOOL TRUE
Definition: undname.c:48
gen_build_yaml.out
dictionary out
Definition: src/benchmark/gen_build_yaml.py:24
init
const char * init
Definition: upb/upb/bindings/lua/main.c:49
CRYPTO_STATIC_MUTEX_unlock_write
#define CRYPTO_STATIC_MUTEX_unlock_write
Definition: boringssl_prefix_symbols.h:1135
check_version.warning
string warning
Definition: check_version.py:46
internal.h
string.h
CRYPTO_MUTEX_unlock_read
#define CRYPTO_MUTEX_unlock_read
Definition: boringssl_prefix_symbols.h:1127
CRYPTO_once
#define CRYPTO_once
Definition: boringssl_prefix_symbols.h:1182
CRYPTO_MUTEX_init
#define CRYPTO_MUTEX_init
Definition: boringssl_prefix_symbols.h:1124
CRYPTO_get_thread_local
#define CRYPTO_get_thread_local
Definition: boringssl_prefix_symbols.h:1169
OPENSSL_memset
static void * OPENSSL_memset(void *dst, int c, size_t n)
Definition: third_party/boringssl-with-bazel/src/crypto/internal.h:835
BOOL
int BOOL
Definition: undname.c:46
OPENSSL_malloc
#define OPENSSL_malloc
Definition: boringssl_prefix_symbols.h:1885
CRYPTO_STATIC_MUTEX
Definition: third_party/boringssl-with-bazel/src/crypto/internal.h:533
CRYPTO_set_thread_local
#define CRYPTO_set_thread_local
Definition: boringssl_prefix_symbols.h:1199
CRYPTO_STATIC_MUTEX_unlock_read
#define CRYPTO_STATIC_MUTEX_unlock_read
Definition: boringssl_prefix_symbols.h:1134
gmock_output_test._
_
Definition: bloaty/third_party/googletest/googlemock/test/gmock_output_test.py:175
CRYPTO_STATIC_MUTEX_lock_write
#define CRYPTO_STATIC_MUTEX_lock_write
Definition: boringssl_prefix_symbols.h:1133
OPENSSL_memcpy
static void * OPENSSL_memcpy(void *dst, const void *src, size_t n)
Definition: third_party/boringssl-with-bazel/src/crypto/internal.h:819
CRYPTO_ONCE_INIT
#define CRYPTO_ONCE_INIT
Definition: third_party/boringssl-with-bazel/src/crypto/internal.h:471
arg
Definition: cmdline.cc:40
OPENSSL_MSVC_PRAGMA
OPENSSL_MSVC_PRAGMA(warning(disable:4702))
Definition: e_aes.c:69
push
int push(void *desc, unsigned char *buf, unsigned len)
Definition: bloaty/third_party/zlib/test/infcover.c:463
value
const char * value
Definition: hpack_parser_table.cc:165
CRYPTO_MUTEX_lock_read
#define CRYPTO_MUTEX_lock_read
Definition: boringssl_prefix_symbols.h:1125
CRYPTO_MUTEX_cleanup
#define CRYPTO_MUTEX_cleanup
Definition: boringssl_prefix_symbols.h:1123
once
absl::once_flag once
Definition: bm_opencensus_plugin.cc:38
thread_local_data_t
thread_local_data_t
Definition: third_party/boringssl-with-bazel/src/crypto/internal.h:635
index
int index
Definition: bloaty/third_party/protobuf/php/ext/google/protobuf/protobuf.h:1184
ret
UniquePtr< SSL_SESSION > ret
Definition: ssl_x509.cc:1029
descriptor_database_test_wrapper.module
module
Definition: descriptor_database_test_wrapper.py:30
CRYPTO_MUTEX_lock_write
#define CRYPTO_MUTEX_lock_write
Definition: boringssl_prefix_symbols.h:1126
arg
struct arg arg
thread_local_destructor_t
void(* thread_local_destructor_t)(void *)
Definition: third_party/boringssl-with-bazel/src/crypto/internal.h:645
SRWLOCK
RTL_SRWLOCK SRWLOCK
Definition: win.h:174
CRYPTO_once_t
uint32_t CRYPTO_once_t
Definition: third_party/boringssl-with-bazel/src/crypto/internal.h:470
CRYPTO_STATIC_MUTEX_lock_read
#define CRYPTO_STATIC_MUTEX_lock_read
Definition: boringssl_prefix_symbols.h:1132
mem.h
type_check.h
OPENSSL_free
#define OPENSSL_free
Definition: boringssl_prefix_symbols.h:1869
CRYPTO_MUTEX_unlock_write
#define CRYPTO_MUTEX_unlock_write
Definition: boringssl_prefix_symbols.h:1128
crypto_mutex_st
Definition: thread.h:70
OPENSSL_STATIC_ASSERT
#define OPENSSL_STATIC_ASSERT(cond, msg)
Definition: type_check.h:75
i
uint64_t i
Definition: abseil-cpp/absl/container/btree_benchmark.cc:230
NUM_OPENSSL_THREAD_LOCALS
@ NUM_OPENSSL_THREAD_LOCALS
Definition: third_party/boringssl-with-bazel/src/crypto/internal.h:640


grpc
Author(s):
autogenerated on Thu Mar 13 2025 03:01:37