thread_win.c 8.7 KB

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