blob: 8e231eb40140ad20803743616e2dc4829b5e8681 [file] [log] [blame]
Adam Langleyd7c5dfb2015-03-16 12:48:56 -07001/* 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
Adam Langley65a7e942015-05-07 18:28:27 -070017#if defined(OPENSSL_WINDOWS) && !defined(OPENSSL_NO_THREADS)
Adam Langleyd7c5dfb2015-03-16 12:48:56 -070018
19#pragma warning(push, 3)
20#include <windows.h>
21#pragma warning(pop)
22
23#include <assert.h>
Adam Langleydf1f5e72015-04-13 11:04:08 -070024#include <stdlib.h>
Adam Langleyd7c5dfb2015-03-16 12:48:56 -070025#include <string.h>
26
27#include <openssl/mem.h>
Adam Langleydf1f5e72015-04-13 11:04:08 -070028#include <openssl/type_check.h>
Adam Langleyd7c5dfb2015-03-16 12:48:56 -070029
30
Adam Langleydf1f5e72015-04-13 11:04:08 -070031OPENSSL_COMPILE_ASSERT(sizeof(CRYPTO_MUTEX) >= sizeof(CRITICAL_SECTION),
32 CRYPTO_MUTEX_too_small);
33
Brian Smith9333d6d2016-01-26 14:32:46 -100034union run_once_arg_t {
35 void (*func)(void);
36 void *data;
37};
38
39static void run_once(CRYPTO_once_t *once, void (*init)(union run_once_arg_t),
40 union run_once_arg_t arg) {
Adam Langleyd7c5dfb2015-03-16 12:48:56 -070041 /* Values must be aligned. */
42 assert((((uintptr_t) once) & 3) == 0);
43
44 /* This assumes that reading *once has acquire semantics. This should be true
45 * on x86 and x86-64, where we expect Windows to run. */
46#if !defined(OPENSSL_X86) && !defined(OPENSSL_X86_64)
47#error "Windows once code may not work on other platforms." \
48 "You can use InitOnceBeginInitialize on >=Vista"
49#endif
50 if (*once == 1) {
51 return;
52 }
53
54 for (;;) {
55 switch (InterlockedCompareExchange(once, 2, 0)) {
56 case 0:
57 /* The value was zero so we are the first thread to call |CRYPTO_once|
58 * on it. */
Adam Langleydf1f5e72015-04-13 11:04:08 -070059 init(arg);
Adam Langleyd7c5dfb2015-03-16 12:48:56 -070060 /* Write one to indicate that initialisation is complete. */
61 InterlockedExchange(once, 1);
62 return;
63
64 case 1:
65 /* Another thread completed initialisation between our fast-path check
66 * and |InterlockedCompareExchange|. */
67 return;
68
69 case 2:
70 /* Another thread is running the initialisation. Switch to it then try
71 * again. */
72 SwitchToThread();
73 break;
74
75 default:
76 abort();
77 }
78 }
79}
80
Brian Smith9333d6d2016-01-26 14:32:46 -100081static void call_once_init(union run_once_arg_t arg) {
82 arg.func();
Adam Langleydf1f5e72015-04-13 11:04:08 -070083}
84
85void CRYPTO_once(CRYPTO_once_t *in_once, void (*init)(void)) {
Brian Smith9333d6d2016-01-26 14:32:46 -100086 union run_once_arg_t arg;
87 arg.func = init;
Adam Langleydf1f5e72015-04-13 11:04:08 -070088 run_once(in_once, call_once_init, arg);
89}
90
91void CRYPTO_MUTEX_init(CRYPTO_MUTEX *lock) {
92 if (!InitializeCriticalSectionAndSpinCount((CRITICAL_SECTION *) lock, 0x400)) {
93 abort();
94 }
95}
96
97void CRYPTO_MUTEX_lock_read(CRYPTO_MUTEX *lock) {
98 /* Since we have to support Windows XP, read locks are actually exclusive. */
99 EnterCriticalSection((CRITICAL_SECTION *) lock);
100}
101
102void CRYPTO_MUTEX_lock_write(CRYPTO_MUTEX *lock) {
103 EnterCriticalSection((CRITICAL_SECTION *) lock);
104}
105
106void CRYPTO_MUTEX_unlock(CRYPTO_MUTEX *lock) {
107 LeaveCriticalSection((CRITICAL_SECTION *) lock);
108}
109
110void CRYPTO_MUTEX_cleanup(CRYPTO_MUTEX *lock) {
111 DeleteCriticalSection((CRITICAL_SECTION *) lock);
112}
113
Brian Smith9333d6d2016-01-26 14:32:46 -1000114static void static_lock_init(union run_once_arg_t arg) {
115 struct CRYPTO_STATIC_MUTEX *lock = arg.data;
Adam Langleydf1f5e72015-04-13 11:04:08 -0700116 if (!InitializeCriticalSectionAndSpinCount(&lock->lock, 0x400)) {
117 abort();
118 }
119}
120
121void CRYPTO_STATIC_MUTEX_lock_read(struct CRYPTO_STATIC_MUTEX *lock) {
Brian Smith9333d6d2016-01-26 14:32:46 -1000122 union run_once_arg_t arg;
123 arg.data = lock;
Adam Langleydf1f5e72015-04-13 11:04:08 -0700124 /* Since we have to support Windows XP, read locks are actually exclusive. */
Brian Smith9333d6d2016-01-26 14:32:46 -1000125 run_once(&lock->once, static_lock_init, arg);
Adam Langleydf1f5e72015-04-13 11:04:08 -0700126 EnterCriticalSection(&lock->lock);
127}
128
129void CRYPTO_STATIC_MUTEX_lock_write(struct CRYPTO_STATIC_MUTEX *lock) {
130 CRYPTO_STATIC_MUTEX_lock_read(lock);
131}
132
133void CRYPTO_STATIC_MUTEX_unlock(struct CRYPTO_STATIC_MUTEX *lock) {
134 LeaveCriticalSection(&lock->lock);
135}
136
Adam Langleyd7c5dfb2015-03-16 12:48:56 -0700137static CRITICAL_SECTION g_destructors_lock;
138static thread_local_destructor_t g_destructors[NUM_OPENSSL_THREAD_LOCALS];
139
140static CRYPTO_once_t g_thread_local_init_once = CRYPTO_ONCE_INIT;
141static DWORD g_thread_local_key;
142static int g_thread_local_failed;
143
144static void thread_local_init(void) {
145 if (!InitializeCriticalSectionAndSpinCount(&g_destructors_lock, 0x400)) {
146 g_thread_local_failed = 1;
147 return;
148 }
149 g_thread_local_key = TlsAlloc();
150 g_thread_local_failed = (g_thread_local_key == TLS_OUT_OF_INDEXES);
151}
152
David Benjaminfeaa57d2016-03-29 14:17:27 -0400153static void NTAPI thread_local_destructor(PVOID module, DWORD reason,
154 PVOID reserved) {
155 /* Only free memory on |DLL_THREAD_DETACH|, not |DLL_PROCESS_DETACH|. In
156 * VS2015's debug runtime, the C runtime has been unloaded by the time
157 * |DLL_PROCESS_DETACH| runs. See https://crbug.com/575795. This is consistent
158 * with |pthread_key_create| which does not call destructors on process exit,
159 * only thread exit. */
160 if (reason != DLL_THREAD_DETACH) {
Adam Langleyd7c5dfb2015-03-16 12:48:56 -0700161 return;
162 }
163
164 CRYPTO_once(&g_thread_local_init_once, thread_local_init);
165 if (g_thread_local_failed) {
166 return;
167 }
168
169 void **pointers = (void**) TlsGetValue(g_thread_local_key);
170 if (pointers == NULL) {
171 return;
172 }
173
174 thread_local_destructor_t destructors[NUM_OPENSSL_THREAD_LOCALS];
175
176 EnterCriticalSection(&g_destructors_lock);
177 memcpy(destructors, g_destructors, sizeof(destructors));
178 LeaveCriticalSection(&g_destructors_lock);
179
180 unsigned i;
181 for (i = 0; i < NUM_OPENSSL_THREAD_LOCALS; i++) {
182 if (destructors[i] != NULL) {
183 destructors[i](pointers[i]);
184 }
185 }
186
187 OPENSSL_free(pointers);
188}
189
190/* Thread Termination Callbacks.
191 *
192 * Windows doesn't support a per-thread destructor with its TLS primitives.
193 * So, we build it manually by inserting a function to be called on each
194 * thread's exit. This magic is from http://www.codeproject.com/threads/tls.asp
195 * and it works for VC++ 7.0 and later.
196 *
197 * Force a reference to _tls_used to make the linker create the TLS directory
198 * if it's not already there. (E.g. if __declspec(thread) is not used). Force
David Benjamin40acdae2015-04-03 11:41:56 -0400199 * a reference to p_thread_callback_boringssl to prevent whole program
200 * optimization from discarding the variable. */
Adam Langleyd7c5dfb2015-03-16 12:48:56 -0700201#ifdef _WIN64
202#pragma comment(linker, "/INCLUDE:_tls_used")
David Benjamin40acdae2015-04-03 11:41:56 -0400203#pragma comment(linker, "/INCLUDE:p_thread_callback_boringssl")
Adam Langleyd7c5dfb2015-03-16 12:48:56 -0700204#else
205#pragma comment(linker, "/INCLUDE:__tls_used")
David Benjamin40acdae2015-04-03 11:41:56 -0400206#pragma comment(linker, "/INCLUDE:_p_thread_callback_boringssl")
Adam Langleyd7c5dfb2015-03-16 12:48:56 -0700207#endif
208
209/* .CRT$XLA to .CRT$XLZ is an array of PIMAGE_TLS_CALLBACK pointers that are
210 * called automatically by the OS loader code (not the CRT) when the module is
211 * loaded and on thread creation. They are NOT called if the module has been
212 * loaded by a LoadLibrary() call. It must have implicitly been loaded at
213 * process startup.
214 *
215 * By implicitly loaded, I mean that it is directly referenced by the main EXE
216 * or by one of its dependent DLLs. Delay-loaded DLL doesn't count as being
217 * implicitly loaded.
218 *
219 * See VC\crt\src\tlssup.c for reference. */
220
David Benjamin40acdae2015-04-03 11:41:56 -0400221/* The linker must not discard p_thread_callback_boringssl. (We force a reference
Adam Langleyd7c5dfb2015-03-16 12:48:56 -0700222 * to this variable with a linker /INCLUDE:symbol pragma to ensure that.) If
223 * this variable is discarded, the OnThreadExit function will never be
224 * called. */
225#ifdef _WIN64
226
227/* .CRT section is merged with .rdata on x64 so it must be constant data. */
228#pragma const_seg(".CRT$XLC")
229/* When defining a const variable, it must have external linkage to be sure the
230 * linker doesn't discard it. */
David Benjamin40acdae2015-04-03 11:41:56 -0400231extern const PIMAGE_TLS_CALLBACK p_thread_callback_boringssl;
232const PIMAGE_TLS_CALLBACK p_thread_callback_boringssl = thread_local_destructor;
Adam Langleyd7c5dfb2015-03-16 12:48:56 -0700233/* Reset the default section. */
234#pragma const_seg()
235
236#else
237
238#pragma data_seg(".CRT$XLC")
David Benjamin40acdae2015-04-03 11:41:56 -0400239PIMAGE_TLS_CALLBACK p_thread_callback_boringssl = thread_local_destructor;
Adam Langleyd7c5dfb2015-03-16 12:48:56 -0700240/* Reset the default section. */
241#pragma data_seg()
242
243#endif /* _WIN64 */
244
245void *CRYPTO_get_thread_local(thread_local_data_t index) {
246 CRYPTO_once(&g_thread_local_init_once, thread_local_init);
247 if (g_thread_local_failed) {
248 return NULL;
249 }
250
251 void **pointers = TlsGetValue(g_thread_local_key);
252 if (pointers == NULL) {
253 return NULL;
254 }
255 return pointers[index];
256}
257
258int CRYPTO_set_thread_local(thread_local_data_t index, void *value,
259 thread_local_destructor_t destructor) {
260 CRYPTO_once(&g_thread_local_init_once, thread_local_init);
261 if (g_thread_local_failed) {
262 destructor(value);
263 return 0;
264 }
265
266 void **pointers = TlsGetValue(g_thread_local_key);
267 if (pointers == NULL) {
268 pointers = OPENSSL_malloc(sizeof(void *) * NUM_OPENSSL_THREAD_LOCALS);
269 if (pointers == NULL) {
270 destructor(value);
271 return 0;
272 }
273 memset(pointers, 0, sizeof(void *) * NUM_OPENSSL_THREAD_LOCALS);
274 if (TlsSetValue(g_thread_local_key, pointers) == 0) {
275 OPENSSL_free(pointers);
276 destructor(value);
277 return 0;
278 }
279 }
280
281 EnterCriticalSection(&g_destructors_lock);
282 g_destructors[index] = destructor;
283 LeaveCriticalSection(&g_destructors_lock);
284
285 pointers[index] = value;
286 return 1;
287}
288
Adam Langley65a7e942015-05-07 18:28:27 -0700289#endif /* OPENSSL_WINDOWS && !OPENSSL_NO_THREADS */