blob: ee48f34a7f9ac4a358193cc86fea745641393e7a [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
17#if defined(OPENSSL_WINDOWS)
18
19#pragma warning(push, 3)
20#include <windows.h>
21#pragma warning(pop)
22
23#include <assert.h>
24#include <string.h>
25
26#include <openssl/mem.h>
27
28
29void CRYPTO_once(CRYPTO_once_t *in_once, void (*init)(void)) {
30 volatile LONG *once = (LONG*) in_once;
31
32 assert(sizeof(LONG) == sizeof(CRYPTO_once_t));
33 /* Values must be aligned. */
34 assert((((uintptr_t) once) & 3) == 0);
35
36 /* This assumes that reading *once has acquire semantics. This should be true
37 * on x86 and x86-64, where we expect Windows to run. */
38#if !defined(OPENSSL_X86) && !defined(OPENSSL_X86_64)
39#error "Windows once code may not work on other platforms." \
40 "You can use InitOnceBeginInitialize on >=Vista"
41#endif
42 if (*once == 1) {
43 return;
44 }
45
46 for (;;) {
47 switch (InterlockedCompareExchange(once, 2, 0)) {
48 case 0:
49 /* The value was zero so we are the first thread to call |CRYPTO_once|
50 * on it. */
51 init();
52 /* Write one to indicate that initialisation is complete. */
53 InterlockedExchange(once, 1);
54 return;
55
56 case 1:
57 /* Another thread completed initialisation between our fast-path check
58 * and |InterlockedCompareExchange|. */
59 return;
60
61 case 2:
62 /* Another thread is running the initialisation. Switch to it then try
63 * again. */
64 SwitchToThread();
65 break;
66
67 default:
68 abort();
69 }
70 }
71}
72
73static CRITICAL_SECTION g_destructors_lock;
74static thread_local_destructor_t g_destructors[NUM_OPENSSL_THREAD_LOCALS];
75
76static CRYPTO_once_t g_thread_local_init_once = CRYPTO_ONCE_INIT;
77static DWORD g_thread_local_key;
78static int g_thread_local_failed;
79
80static void thread_local_init(void) {
81 if (!InitializeCriticalSectionAndSpinCount(&g_destructors_lock, 0x400)) {
82 g_thread_local_failed = 1;
83 return;
84 }
85 g_thread_local_key = TlsAlloc();
86 g_thread_local_failed = (g_thread_local_key == TLS_OUT_OF_INDEXES);
87}
88
89static void NTAPI thread_local_destructor(PVOID module,
90 DWORD reason, PVOID reserved) {
91 if (DLL_THREAD_DETACH != reason && DLL_PROCESS_DETACH != reason) {
92 return;
93 }
94
95 CRYPTO_once(&g_thread_local_init_once, thread_local_init);
96 if (g_thread_local_failed) {
97 return;
98 }
99
100 void **pointers = (void**) TlsGetValue(g_thread_local_key);
101 if (pointers == NULL) {
102 return;
103 }
104
105 thread_local_destructor_t destructors[NUM_OPENSSL_THREAD_LOCALS];
106
107 EnterCriticalSection(&g_destructors_lock);
108 memcpy(destructors, g_destructors, sizeof(destructors));
109 LeaveCriticalSection(&g_destructors_lock);
110
111 unsigned i;
112 for (i = 0; i < NUM_OPENSSL_THREAD_LOCALS; i++) {
113 if (destructors[i] != NULL) {
114 destructors[i](pointers[i]);
115 }
116 }
117
118 OPENSSL_free(pointers);
119}
120
121/* Thread Termination Callbacks.
122 *
123 * Windows doesn't support a per-thread destructor with its TLS primitives.
124 * So, we build it manually by inserting a function to be called on each
125 * thread's exit. This magic is from http://www.codeproject.com/threads/tls.asp
126 * and it works for VC++ 7.0 and later.
127 *
128 * Force a reference to _tls_used to make the linker create the TLS directory
129 * if it's not already there. (E.g. if __declspec(thread) is not used). Force
130 * a reference to p_thread_callback_base to prevent whole program optimization
131 * from discarding the variable. */
132#ifdef _WIN64
133#pragma comment(linker, "/INCLUDE:_tls_used")
134#pragma comment(linker, "/INCLUDE:p_thread_callback_base")
135#else
136#pragma comment(linker, "/INCLUDE:__tls_used")
137#pragma comment(linker, "/INCLUDE:_p_thread_callback_base")
138#endif
139
140/* .CRT$XLA to .CRT$XLZ is an array of PIMAGE_TLS_CALLBACK pointers that are
141 * called automatically by the OS loader code (not the CRT) when the module is
142 * loaded and on thread creation. They are NOT called if the module has been
143 * loaded by a LoadLibrary() call. It must have implicitly been loaded at
144 * process startup.
145 *
146 * By implicitly loaded, I mean that it is directly referenced by the main EXE
147 * or by one of its dependent DLLs. Delay-loaded DLL doesn't count as being
148 * implicitly loaded.
149 *
150 * See VC\crt\src\tlssup.c for reference. */
151
152/* The linker must not discard p_thread_callback_base. (We force a reference
153 * to this variable with a linker /INCLUDE:symbol pragma to ensure that.) If
154 * this variable is discarded, the OnThreadExit function will never be
155 * called. */
156#ifdef _WIN64
157
158/* .CRT section is merged with .rdata on x64 so it must be constant data. */
159#pragma const_seg(".CRT$XLC")
160/* When defining a const variable, it must have external linkage to be sure the
161 * linker doesn't discard it. */
162extern const PIMAGE_TLS_CALLBACK p_thread_callback_base;
163const PIMAGE_TLS_CALLBACK p_thread_callback_base = thread_local_destructor;
164/* Reset the default section. */
165#pragma const_seg()
166
167#else
168
169#pragma data_seg(".CRT$XLC")
170PIMAGE_TLS_CALLBACK p_thread_callback_base = thread_local_destructor;
171/* Reset the default section. */
172#pragma data_seg()
173
174#endif /* _WIN64 */
175
176void *CRYPTO_get_thread_local(thread_local_data_t index) {
177 CRYPTO_once(&g_thread_local_init_once, thread_local_init);
178 if (g_thread_local_failed) {
179 return NULL;
180 }
181
182 void **pointers = TlsGetValue(g_thread_local_key);
183 if (pointers == NULL) {
184 return NULL;
185 }
186 return pointers[index];
187}
188
189int CRYPTO_set_thread_local(thread_local_data_t index, void *value,
190 thread_local_destructor_t destructor) {
191 CRYPTO_once(&g_thread_local_init_once, thread_local_init);
192 if (g_thread_local_failed) {
193 destructor(value);
194 return 0;
195 }
196
197 void **pointers = TlsGetValue(g_thread_local_key);
198 if (pointers == NULL) {
199 pointers = OPENSSL_malloc(sizeof(void *) * NUM_OPENSSL_THREAD_LOCALS);
200 if (pointers == NULL) {
201 destructor(value);
202 return 0;
203 }
204 memset(pointers, 0, sizeof(void *) * NUM_OPENSSL_THREAD_LOCALS);
205 if (TlsSetValue(g_thread_local_key, pointers) == 0) {
206 OPENSSL_free(pointers);
207 destructor(value);
208 return 0;
209 }
210 }
211
212 EnterCriticalSection(&g_destructors_lock);
213 g_destructors[index] = destructor;
214 LeaveCriticalSection(&g_destructors_lock);
215
216 pointers[index] = value;
217 return 1;
218}
219
220#endif /* OPENSSL_WINDOWS */