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