• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 // Ensure we can't call OPENSSL_malloc circularly.
16 #define _BORINGSSL_PROHIBIT_OPENSSL_MALLOC
17 #include "internal.h"
18 
19 #if defined(OPENSSL_WINDOWS_THREADS)
20 
21 OPENSSL_MSVC_PRAGMA(warning(push, 3))
22 #include <windows.h>
23 OPENSSL_MSVC_PRAGMA(warning(pop))
24 
25 #include <assert.h>
26 #include <stdlib.h>
27 #include <string.h>
28 
29 static_assert(sizeof(CRYPTO_MUTEX) >= sizeof(SRWLOCK),
30               "CRYPTO_MUTEX is too small");
31 static_assert(alignof(CRYPTO_MUTEX) >= alignof(SRWLOCK),
32               "CRYPTO_MUTEX has insufficient alignment");
33 
call_once_init(INIT_ONCE * once,void * arg,void ** out)34 static BOOL CALLBACK call_once_init(INIT_ONCE *once, void *arg, void **out) {
35   void (**init)(void) = (void (**)(void))arg;
36   (**init)();
37   return TRUE;
38 }
39 
CRYPTO_once(CRYPTO_once_t * once,void (* init)(void))40 void CRYPTO_once(CRYPTO_once_t *once, void (*init)(void)) {
41   if (!InitOnceExecuteOnce(once, call_once_init, &init, NULL)) {
42     abort();
43   }
44 }
45 
CRYPTO_MUTEX_init(CRYPTO_MUTEX * lock)46 void CRYPTO_MUTEX_init(CRYPTO_MUTEX *lock) {
47   InitializeSRWLock((SRWLOCK *) lock);
48 }
49 
CRYPTO_MUTEX_lock_read(CRYPTO_MUTEX * lock)50 void CRYPTO_MUTEX_lock_read(CRYPTO_MUTEX *lock) {
51   AcquireSRWLockShared((SRWLOCK *) lock);
52 }
53 
CRYPTO_MUTEX_lock_write(CRYPTO_MUTEX * lock)54 void CRYPTO_MUTEX_lock_write(CRYPTO_MUTEX *lock) {
55   AcquireSRWLockExclusive((SRWLOCK *) lock);
56 }
57 
CRYPTO_MUTEX_unlock_read(CRYPTO_MUTEX * lock)58 void CRYPTO_MUTEX_unlock_read(CRYPTO_MUTEX *lock) {
59   ReleaseSRWLockShared((SRWLOCK *) lock);
60 }
61 
CRYPTO_MUTEX_unlock_write(CRYPTO_MUTEX * lock)62 void CRYPTO_MUTEX_unlock_write(CRYPTO_MUTEX *lock) {
63   ReleaseSRWLockExclusive((SRWLOCK *) lock);
64 }
65 
CRYPTO_MUTEX_cleanup(CRYPTO_MUTEX * lock)66 void CRYPTO_MUTEX_cleanup(CRYPTO_MUTEX *lock) {
67   // SRWLOCKs require no cleanup.
68 }
69 
CRYPTO_STATIC_MUTEX_lock_read(struct CRYPTO_STATIC_MUTEX * lock)70 void CRYPTO_STATIC_MUTEX_lock_read(struct CRYPTO_STATIC_MUTEX *lock) {
71   AcquireSRWLockShared(&lock->lock);
72 }
73 
CRYPTO_STATIC_MUTEX_lock_write(struct CRYPTO_STATIC_MUTEX * lock)74 void CRYPTO_STATIC_MUTEX_lock_write(struct CRYPTO_STATIC_MUTEX *lock) {
75   AcquireSRWLockExclusive(&lock->lock);
76 }
77 
CRYPTO_STATIC_MUTEX_unlock_read(struct CRYPTO_STATIC_MUTEX * lock)78 void CRYPTO_STATIC_MUTEX_unlock_read(struct CRYPTO_STATIC_MUTEX *lock) {
79   ReleaseSRWLockShared(&lock->lock);
80 }
81 
CRYPTO_STATIC_MUTEX_unlock_write(struct CRYPTO_STATIC_MUTEX * lock)82 void CRYPTO_STATIC_MUTEX_unlock_write(struct CRYPTO_STATIC_MUTEX *lock) {
83   ReleaseSRWLockExclusive(&lock->lock);
84 }
85 
86 static SRWLOCK g_destructors_lock = SRWLOCK_INIT;
87 static thread_local_destructor_t g_destructors[NUM_OPENSSL_THREAD_LOCALS];
88 
89 static CRYPTO_once_t g_thread_local_init_once = CRYPTO_ONCE_INIT;
90 static DWORD g_thread_local_key;
91 static int g_thread_local_failed;
92 
thread_local_init(void)93 static void thread_local_init(void) {
94   g_thread_local_key = TlsAlloc();
95   g_thread_local_failed = (g_thread_local_key == TLS_OUT_OF_INDEXES);
96 }
97 
thread_local_destructor(PVOID module,DWORD reason,PVOID reserved)98 static void NTAPI thread_local_destructor(PVOID module, DWORD reason,
99                                           PVOID reserved) {
100   // Only free memory on |DLL_THREAD_DETACH|, not |DLL_PROCESS_DETACH|. In
101   // VS2015's debug runtime, the C runtime has been unloaded by the time
102   // |DLL_PROCESS_DETACH| runs. See https://crbug.com/575795. This is consistent
103   // with |pthread_key_create| which does not call destructors on process exit,
104   // only thread exit.
105   if (reason != DLL_THREAD_DETACH) {
106     return;
107   }
108 
109   CRYPTO_once(&g_thread_local_init_once, thread_local_init);
110   if (g_thread_local_failed) {
111     return;
112   }
113 
114   void **pointers = (void**) TlsGetValue(g_thread_local_key);
115   if (pointers == NULL) {
116     return;
117   }
118 
119   thread_local_destructor_t destructors[NUM_OPENSSL_THREAD_LOCALS];
120 
121   AcquireSRWLockExclusive(&g_destructors_lock);
122   OPENSSL_memcpy(destructors, g_destructors, sizeof(destructors));
123   ReleaseSRWLockExclusive(&g_destructors_lock);
124 
125   for (unsigned i = 0; i < NUM_OPENSSL_THREAD_LOCALS; i++) {
126     if (destructors[i] != NULL) {
127       destructors[i](pointers[i]);
128     }
129   }
130 
131   free(pointers);
132 }
133 
134 // Thread Termination Callbacks.
135 //
136 // Windows doesn't support a per-thread destructor with its TLS primitives.
137 // So, we build it manually by inserting a function to be called on each
138 // thread's exit. This magic is from http://www.codeproject.com/threads/tls.asp
139 // and it works for VC++ 7.0 and later.
140 //
141 // Force a reference to _tls_used to make the linker create the TLS directory
142 // if it's not already there. (E.g. if __declspec(thread) is not used). Force
143 // a reference to p_thread_callback_boringssl to prevent whole program
144 // optimization from discarding the variable.
145 //
146 // Note, in the prefixed build, |p_thread_callback_boringssl| may be a macro.
147 #define STRINGIFY(x) #x
148 #define EXPAND_AND_STRINGIFY(x) STRINGIFY(x)
149 #ifdef _WIN64
150 __pragma(comment(linker, "/INCLUDE:_tls_used"))
151 __pragma(comment(
152     linker, "/INCLUDE:" EXPAND_AND_STRINGIFY(p_thread_callback_boringssl)))
153 #else
154 __pragma(comment(linker, "/INCLUDE:__tls_used"))
155 __pragma(comment(
156     linker, "/INCLUDE:_" EXPAND_AND_STRINGIFY(p_thread_callback_boringssl)))
157 #endif
158 
159 // .CRT$XLA to .CRT$XLZ is an array of PIMAGE_TLS_CALLBACK pointers that are
160 // called automatically by the OS loader code (not the CRT) when the module is
161 // loaded and on thread creation. They are NOT called if the module has been
162 // loaded by a LoadLibrary() call. It must have implicitly been loaded at
163 // process startup.
164 //
165 // By implicitly loaded, I mean that it is directly referenced by the main EXE
166 // or by one of its dependent DLLs. Delay-loaded DLL doesn't count as being
167 // implicitly loaded.
168 //
169 // See VC\crt\src\tlssup.c for reference.
170 
171 // The linker must not discard p_thread_callback_boringssl. (We force a
172 // reference to this variable with a linker /INCLUDE:symbol pragma to ensure
173 // that.) If this variable is discarded, the OnThreadExit function will never
174 // be called.
175 #ifdef _WIN64
176 
177 // .CRT section is merged with .rdata on x64 so it must be constant data.
178 #pragma const_seg(".CRT$XLC")
179 // When defining a const variable, it must have external linkage to be sure the
180 // linker doesn't discard it.
181 extern const PIMAGE_TLS_CALLBACK p_thread_callback_boringssl;
182 const PIMAGE_TLS_CALLBACK p_thread_callback_boringssl = thread_local_destructor;
183 // Reset the default section.
184 #pragma const_seg()
185 
186 #else
187 
188 #pragma data_seg(".CRT$XLC")
189 PIMAGE_TLS_CALLBACK p_thread_callback_boringssl = thread_local_destructor;
190 // Reset the default section.
191 #pragma data_seg()
192 
193 #endif  // _WIN64
194 
get_thread_locals(void)195 static void **get_thread_locals(void) {
196   // |TlsGetValue| clears the last error even on success, so that callers may
197   // distinguish it successfully returning NULL or failing. It is documented to
198   // never fail if the argument is a valid index from |TlsAlloc|, so we do not
199   // need to handle this.
200   //
201   // However, this error-mangling behavior interferes with the caller's use of
202   // |GetLastError|. In particular |SSL_get_error| queries the error queue to
203   // determine whether the caller should look at the OS's errors. To avoid
204   // destroying state, save and restore the Windows error.
205   //
206   // https://msdn.microsoft.com/en-us/library/windows/desktop/ms686812(v=vs.85).aspx
207   DWORD last_error = GetLastError();
208   void **ret = TlsGetValue(g_thread_local_key);
209   SetLastError(last_error);
210   return ret;
211 }
212 
CRYPTO_get_thread_local(thread_local_data_t index)213 void *CRYPTO_get_thread_local(thread_local_data_t index) {
214   CRYPTO_once(&g_thread_local_init_once, thread_local_init);
215   if (g_thread_local_failed) {
216     return NULL;
217   }
218 
219   void **pointers = get_thread_locals();
220   if (pointers == NULL) {
221     return NULL;
222   }
223   return pointers[index];
224 }
225 
CRYPTO_set_thread_local(thread_local_data_t index,void * value,thread_local_destructor_t destructor)226 int CRYPTO_set_thread_local(thread_local_data_t index, void *value,
227                             thread_local_destructor_t destructor) {
228   CRYPTO_once(&g_thread_local_init_once, thread_local_init);
229   if (g_thread_local_failed) {
230     destructor(value);
231     return 0;
232   }
233 
234   void **pointers = get_thread_locals();
235   if (pointers == NULL) {
236     pointers = malloc(sizeof(void *) * NUM_OPENSSL_THREAD_LOCALS);
237     if (pointers == NULL) {
238       destructor(value);
239       return 0;
240     }
241     OPENSSL_memset(pointers, 0, sizeof(void *) * NUM_OPENSSL_THREAD_LOCALS);
242     if (TlsSetValue(g_thread_local_key, pointers) == 0) {
243       free(pointers);
244       destructor(value);
245       return 0;
246     }
247   }
248 
249   AcquireSRWLockExclusive(&g_destructors_lock);
250   g_destructors[index] = destructor;
251   ReleaseSRWLockExclusive(&g_destructors_lock);
252 
253   pointers[index] = value;
254   return 1;
255 }
256 
257 #endif  // OPENSSL_WINDOWS_THREADS
258