Chromium Code Reviews| OLD | NEW |
|---|---|
| 1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. | 1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
| 4 | 4 |
| 5 #include "base/threading/thread_local_storage.h" | 5 #include "base/threading/thread_local_storage.h" |
| 6 | 6 |
| 7 #include <windows.h> | 7 #include <windows.h> |
| 8 | 8 |
| 9 #include "base/logging.h" | 9 #include "base/logging.h" |
| 10 | 10 |
| 11 | 11 |
| 12 namespace base { | 12 namespace base { |
| 13 | 13 |
| 14 namespace { | 14 namespace { |
| 15 // In order to make TLS destructors work, we need to keep function | |
| 16 // pointers to the destructor for each TLS that we allocate. | |
| 17 // We make this work by allocating a single OS-level TLS, which | |
| 18 // contains an array of slots for the application to use. In | |
| 19 // parallel, we also allocate an array of destructors, which we | |
| 20 // keep track of and call when threads terminate. | |
| 21 | |
| 22 // windows_native_tls_key is the one native TLS that we use. It stores our | |
| 23 // table. | |
| 24 long windows_native_tls_key = TLS_OUT_OF_INDEXES; | |
|
rvargas (doing something else)
2011/11/30 04:00:23
Shouldn't we move to g_windows_native... ?
jar (doing other things)
2011/11/30 07:31:30
Done.
| |
| 25 | |
| 26 // last_used_tls_key is the high-water-mark of allocated thread local storage. | |
| 27 // We intentionally skip 0 (claiming it was used) so that it is not confused | |
|
rvargas (doing something else)
2011/11/30 04:00:23
Remove the comment about skipping 0
jar (doing other things)
2011/11/30 07:31:30
This is a somewhat significant comment, even thoug
rvargas (doing something else)
2011/11/30 18:48:41
Right... I got confused by the change to 0 here (e
| |
| 28 // with an unallocated TLS slot. | |
| 29 long last_used_tls_key = 0; | |
| 30 | |
| 15 // The maximum number of 'slots' in our thread local storage stack. | 31 // The maximum number of 'slots' in our thread local storage stack. |
| 16 const int kThreadLocalStorageSize = 64; | 32 const int kThreadLocalStorageSize = 64; |
| 17 | 33 |
| 18 // The maximum number of times to try to clear slots by calling destructors. | 34 // The maximum number of times to try to clear slots by calling destructors. |
| 19 // Use pthread naming convention for clarity. | 35 // Use pthread naming convention for clarity. |
| 20 const int kMaxDestructorIterations = kThreadLocalStorageSize; | 36 const int kMaxDestructorIterations = kThreadLocalStorageSize; |
| 21 | 37 |
| 22 // An array of destructor function pointers for the slots. If a slot has a | 38 // An array of destructor function pointers for the slots. If a slot has a |
| 23 // destructor, it will be stored in its corresponding entry in this array. | 39 // destructor, it will be stored in its corresponding entry in this array. |
| 24 // The elements are volatile to ensure that when the compiler reads the value | 40 // The elements are volatile to ensure that when the compiler reads the value |
| 25 // to potentially call the destructor, it does so once, and that value is tested | 41 // to potentially call the destructor, it does so once, and that value is tested |
| 26 // for null-ness and then used. Yes, that would be a weird de-optimization, | 42 // for null-ness and then used. Yes, that would be a weird de-optimization, |
| 27 // but I can imagine some register machines where it was just as easy to | 43 // but I can imagine some register machines where it was just as easy to |
| 28 // re-fetch an array element, and I want to be sure a call to free the key | 44 // re-fetch an array element, and I want to be sure a call to free the key |
| 29 // (i.e., null out the destructor entry) that happens on a separate thread can't | 45 // (i.e., null out the destructor entry) that happens on a separate thread can't |
| 30 // hurt the racy calls to the destructors on another thread. | 46 // hurt the racy calls to the destructors on another thread. |
| 31 volatile ThreadLocalStorage::TLSDestructorFunc | 47 volatile ThreadLocalStorage::TLSDestructorFunc |
| 32 g_tls_destructors[kThreadLocalStorageSize]; | 48 g_tls_destructors[kThreadLocalStorageSize]; |
| 33 | 49 |
| 34 } // namespace anonymous | 50 } // namespace anonymous |
| 35 | 51 |
| 36 // In order to make TLS destructors work, we need to keep function | |
| 37 // pointers to the destructor for each TLS that we allocate. | |
| 38 // We make this work by allocating a single OS-level TLS, which | |
| 39 // contains an array of slots for the application to use. In | |
| 40 // parallel, we also allocate an array of destructors, which we | |
| 41 // keep track of and call when threads terminate. | |
| 42 | |
| 43 // tls_key_ is the one native TLS that we use. It stores our | |
| 44 // table. | |
| 45 long ThreadLocalStorage::tls_key_ = TLS_OUT_OF_INDEXES; | |
| 46 | |
| 47 // tls_max_ is the high-water-mark of allocated thread local storage. | |
| 48 // We intentionally skip 0 so that it is not confused with an | |
| 49 // unallocated TLS slot. | |
| 50 long ThreadLocalStorage::tls_max_ = 1; | |
| 51 | |
| 52 void** ThreadLocalStorage::Initialize() { | 52 void** ThreadLocalStorage::Initialize() { |
| 53 if (tls_key_ == TLS_OUT_OF_INDEXES) { | 53 if (windows_native_tls_key == TLS_OUT_OF_INDEXES) { |
| 54 long value = TlsAlloc(); | 54 long value = TlsAlloc(); |
| 55 DCHECK(value != TLS_OUT_OF_INDEXES); | 55 DCHECK(value != TLS_OUT_OF_INDEXES); |
| 56 | 56 |
| 57 // Atomically test-and-set the tls_key. If the key is TLS_OUT_OF_INDEXES, | 57 // Atomically test-and-set the tls_key. If the key is TLS_OUT_OF_INDEXES, |
| 58 // go ahead and set it. Otherwise, do nothing, as another | 58 // go ahead and set it. Otherwise, do nothing, as another |
| 59 // thread already did our dirty work. | 59 // thread already did our dirty work. |
| 60 if (InterlockedCompareExchange(&tls_key_, value, TLS_OUT_OF_INDEXES) != | 60 if (TLS_OUT_OF_INDEXES != InterlockedCompareExchange( |
| 61 TLS_OUT_OF_INDEXES) { | 61 &windows_native_tls_key, value, TLS_OUT_OF_INDEXES)) { |
|
rvargas (doing something else)
2011/11/30 04:00:23
nit: needs two extra spaces here
jar (doing other things)
2011/11/30 07:31:30
Done.
| |
| 62 // We've been shortcut. Another thread replaced tls_key_ first so we need | 62 // We've been shortcut. Another thread replaced windows_native_tls_key |
| 63 // to destroy our index and use the one the other thread got first. | 63 // first so we need to destroy our index and use the one the other thread |
| 64 // got first. | |
| 64 TlsFree(value); | 65 TlsFree(value); |
| 65 } | 66 } |
| 66 } | 67 } |
| 67 DCHECK(!TlsGetValue(tls_key_)); | 68 DCHECK(!TlsGetValue(windows_native_tls_key)); |
| 68 | 69 |
| 69 // Some allocators, such as TCMalloc, make use of thread local storage. | 70 // Some allocators, such as TCMalloc, make use of thread local storage. |
| 70 // As a result, any attempt to call new (or malloc) will lazily cause such a | 71 // As a result, any attempt to call new (or malloc) will lazily cause such a |
| 71 // system to initialize, which will include registering for a TLS key. If we | 72 // system to initialize, which will include registering for a TLS key. If we |
| 72 // are not careful here, then that request to create a key will call new back, | 73 // are not careful here, then that request to create a key will call new back, |
| 73 // and we'll have an infinite loop. We avoid that as follows: | 74 // and we'll have an infinite loop. We avoid that as follows: |
| 74 // Use a stack allocated vector, so that we don't have dependence on our | 75 // Use a stack allocated vector, so that we don't have dependence on our |
| 75 // allocator until our service is in place. (i.e., don't even call new until | 76 // allocator until our service is in place. (i.e., don't even call new until |
| 76 // after we're setup) | 77 // after we're setup) |
| 77 void* stack_allocated_tls_data[kThreadLocalStorageSize]; | 78 void* stack_allocated_tls_data[kThreadLocalStorageSize]; |
| 78 memset(stack_allocated_tls_data, 0, sizeof(stack_allocated_tls_data)); | 79 memset(stack_allocated_tls_data, 0, sizeof(stack_allocated_tls_data)); |
| 79 // Ensure that any rentrant calls change the temp version. | 80 // Ensure that any rentrant calls change the temp version. |
| 80 TlsSetValue(tls_key_, stack_allocated_tls_data); | 81 TlsSetValue(windows_native_tls_key, stack_allocated_tls_data); |
| 81 | 82 |
| 82 // Allocate an array to store our data. | 83 // Allocate an array to store our data. |
| 83 void** tls_data = new void*[kThreadLocalStorageSize]; | 84 void** tls_data = new void*[kThreadLocalStorageSize]; |
| 84 memcpy(tls_data, stack_allocated_tls_data, sizeof(stack_allocated_tls_data)); | 85 memcpy(tls_data, stack_allocated_tls_data, sizeof(stack_allocated_tls_data)); |
| 85 TlsSetValue(tls_key_, tls_data); | 86 TlsSetValue(windows_native_tls_key, tls_data); |
| 86 return tls_data; | 87 return tls_data; |
| 87 } | 88 } |
| 88 | 89 |
| 89 ThreadLocalStorage::Slot::Slot(TLSDestructorFunc destructor) | 90 ThreadLocalStorage::Slot::Slot(TLSDestructorFunc destructor) |
| 90 : initialized_(false), | 91 : initialized_(false), |
| 91 slot_(0) { | 92 slot_(0) { |
| 92 Initialize(destructor); | 93 Initialize(destructor); |
| 93 } | 94 } |
| 94 | 95 |
| 95 bool ThreadLocalStorage::Slot::Initialize(TLSDestructorFunc destructor) { | 96 bool ThreadLocalStorage::Slot::Initialize(TLSDestructorFunc destructor) { |
| 96 if (tls_key_ == TLS_OUT_OF_INDEXES || !TlsGetValue(tls_key_)) | 97 if (windows_native_tls_key == TLS_OUT_OF_INDEXES || |
| 98 !TlsGetValue(windows_native_tls_key)) | |
| 97 ThreadLocalStorage::Initialize(); | 99 ThreadLocalStorage::Initialize(); |
| 98 | 100 |
| 99 // Grab a new slot. | 101 // Grab a new slot. |
| 100 slot_ = InterlockedIncrement(&tls_max_) - 1; | 102 slot_ = InterlockedIncrement(&last_used_tls_key); |
| 101 DCHECK_GT(slot_, 0); | 103 DCHECK_GT(slot_, 0); |
| 102 if (slot_ >= kThreadLocalStorageSize) { | 104 if (slot_ >= kThreadLocalStorageSize) { |
| 103 NOTREACHED(); | 105 NOTREACHED(); |
| 104 return false; | 106 return false; |
| 105 } | 107 } |
| 106 | 108 |
| 107 // Setup our destructor. | 109 // Setup our destructor. |
| 108 g_tls_destructors[slot_] = destructor; | 110 g_tls_destructors[slot_] = destructor; |
| 109 initialized_ = true; | 111 initialized_ = true; |
| 110 return true; | 112 return true; |
| 111 } | 113 } |
| 112 | 114 |
| 113 void ThreadLocalStorage::Slot::Free() { | 115 void ThreadLocalStorage::Slot::Free() { |
| 114 // At this time, we don't reclaim old indices for TLS slots. | 116 // At this time, we don't reclaim old indices for TLS slots. |
| 115 // So all we need to do is wipe the destructor. | 117 // So all we need to do is wipe the destructor. |
| 116 DCHECK_GT(slot_, 0); | 118 DCHECK_GT(slot_, 0); |
| 117 DCHECK_LT(slot_, kThreadLocalStorageSize); | 119 DCHECK_LT(slot_, kThreadLocalStorageSize); |
| 118 g_tls_destructors[slot_] = NULL; | 120 g_tls_destructors[slot_] = NULL; |
| 119 slot_ = 0; | 121 slot_ = 0; |
| 120 initialized_ = false; | 122 initialized_ = false; |
| 121 } | 123 } |
| 122 | 124 |
| 123 void* ThreadLocalStorage::Slot::Get() const { | 125 void* ThreadLocalStorage::Slot::Get() const { |
| 124 void** tls_data = static_cast<void**>(TlsGetValue(tls_key_)); | 126 void** tls_data = static_cast<void**>(TlsGetValue(windows_native_tls_key)); |
| 125 if (!tls_data) | 127 if (!tls_data) |
| 126 tls_data = ThreadLocalStorage::Initialize(); | 128 tls_data = ThreadLocalStorage::Initialize(); |
| 127 DCHECK_GT(slot_, 0); | 129 DCHECK_GT(slot_, 0); |
| 128 DCHECK_LT(slot_, kThreadLocalStorageSize); | 130 DCHECK_LT(slot_, kThreadLocalStorageSize); |
| 129 return tls_data[slot_]; | 131 return tls_data[slot_]; |
| 130 } | 132 } |
| 131 | 133 |
| 132 void ThreadLocalStorage::Slot::Set(void* value) { | 134 void ThreadLocalStorage::Slot::Set(void* value) { |
| 133 void** tls_data = static_cast<void**>(TlsGetValue(tls_key_)); | 135 void** tls_data = static_cast<void**>(TlsGetValue(windows_native_tls_key)); |
| 134 if (!tls_data) | 136 if (!tls_data) |
| 135 tls_data = ThreadLocalStorage::Initialize(); | 137 tls_data = ThreadLocalStorage::Initialize(); |
| 136 DCHECK_GT(slot_, 0); | 138 DCHECK_GT(slot_, 0); |
| 137 DCHECK_LT(slot_, kThreadLocalStorageSize); | 139 DCHECK_LT(slot_, kThreadLocalStorageSize); |
| 138 tls_data[slot_] = value; | 140 tls_data[slot_] = value; |
| 139 } | 141 } |
| 140 | 142 |
| 141 void ThreadLocalStorage::ThreadExit() { | 143 void ThreadLocalStorage::ThreadExit() { |
| 142 if (tls_key_ == TLS_OUT_OF_INDEXES) | 144 if (windows_native_tls_key == TLS_OUT_OF_INDEXES) |
| 143 return; | 145 return; |
| 144 | 146 |
| 145 void** tls_data = static_cast<void**>(TlsGetValue(tls_key_)); | 147 void** tls_data = static_cast<void**>(TlsGetValue(windows_native_tls_key)); |
| 146 // Maybe we have never initialized TLS for this thread. | 148 // Maybe we have never initialized TLS for this thread. |
| 147 if (!tls_data) | 149 if (!tls_data) |
| 148 return; | 150 return; |
| 149 | 151 |
| 150 // Some allocators, such as TCMalloc, use TLS. As a result, when a thread | 152 // Some allocators, such as TCMalloc, use TLS. As a result, when a thread |
| 151 // terminates, one of the destructor calls we make may be to shut down an | 153 // terminates, one of the destructor calls we make may be to shut down an |
| 152 // allocator. We have to be careful that after we've shutdown all of the | 154 // allocator. We have to be careful that after we've shutdown all of the |
| 153 // known destructors (perchance including an allocator), that we don't call | 155 // known destructors (perchance including an allocator), that we don't call |
| 154 // the allocator and cause it to resurrect itself (with no possibly destructor | 156 // the allocator and cause it to resurrect itself (with no possibly destructor |
| 155 // call to follow). We handle this problem as follows: | 157 // call to follow). We handle this problem as follows: |
| 156 // Switch to using a stack allocated vector, so that we don't have dependence | 158 // Switch to using a stack allocated vector, so that we don't have dependence |
| 157 // on our allocator after we have called all g_tls_destructors. (i.e., don't | 159 // on our allocator after we have called all g_tls_destructors. (i.e., don't |
| 158 // even call delete[] after we're done with destructors.) | 160 // even call delete[] after we're done with destructors.) |
| 159 void* stack_allocated_tls_data[kThreadLocalStorageSize]; | 161 void* stack_allocated_tls_data[kThreadLocalStorageSize]; |
| 160 memcpy(stack_allocated_tls_data, tls_data, sizeof(stack_allocated_tls_data)); | 162 memcpy(stack_allocated_tls_data, tls_data, sizeof(stack_allocated_tls_data)); |
| 161 // Ensure that any re-entrant calls change the temp version. | 163 // Ensure that any re-entrant calls change the temp version. |
| 162 TlsSetValue(tls_key_, stack_allocated_tls_data); | 164 TlsSetValue(windows_native_tls_key, stack_allocated_tls_data); |
| 163 delete[] tls_data; // Our last dependence on an allocator. | 165 delete[] tls_data; // Our last dependence on an allocator. |
| 164 | 166 |
| 165 int remaining_attempts = kMaxDestructorIterations; | 167 int remaining_attempts = kMaxDestructorIterations; |
| 166 bool need_to_scan_destructors = true; | 168 bool need_to_scan_destructors = true; |
| 167 while (need_to_scan_destructors) { | 169 while (need_to_scan_destructors) { |
| 168 need_to_scan_destructors = false; | 170 need_to_scan_destructors = false; |
| 169 // Try to destroy the first-created-slot (which is slot 1) in our last | 171 // Try to destroy the first-created-slot (which is slot 1) in our last |
| 170 // destructor call. That user was able to function, and define a slot with | 172 // destructor call. That user was able to function, and define a slot with |
| 171 // no other services running, so perhaps it is a basic service (like an | 173 // no other services running, so perhaps it is a basic service (like an |
| 172 // allocator) and should also be destroyed last. If we get the order wrong, | 174 // allocator) and should also be destroyed last. If we get the order wrong, |
| 173 // then we'll itterate several more times, so it is really not that | 175 // then we'll itterate several more times, so it is really not that |
| 174 // critical (but it might help). | 176 // critical (but it might help). |
| 175 for (int slot = tls_max_ - 1; slot > 0; --slot) { | 177 for (int slot = last_used_tls_key; slot > 0; --slot) { |
| 176 void* value = stack_allocated_tls_data[slot]; | 178 void* value = stack_allocated_tls_data[slot]; |
| 177 if (value == NULL) | 179 if (value == NULL) |
| 178 continue; | 180 continue; |
| 179 TLSDestructorFunc destructor = g_tls_destructors[slot]; | 181 TLSDestructorFunc destructor = g_tls_destructors[slot]; |
| 180 if (destructor == NULL) | 182 if (destructor == NULL) |
| 181 continue; | 183 continue; |
| 182 stack_allocated_tls_data[slot] = NULL; // pre-clear the slot. | 184 stack_allocated_tls_data[slot] = NULL; // pre-clear the slot. |
| 183 destructor(value); | 185 destructor(value); |
| 184 // Any destructor might have called a different service, which then set | 186 // Any destructor might have called a different service, which then set |
| 185 // a different slot to a non-NULL value. Hence we need to check | 187 // a different slot to a non-NULL value. Hence we need to check |
| 186 // the whole vector again. This is a pthread standard. | 188 // the whole vector again. This is a pthread standard. |
| 187 need_to_scan_destructors = true; | 189 need_to_scan_destructors = true; |
| 188 } | 190 } |
| 189 if (--remaining_attempts <= 0) { | 191 if (--remaining_attempts <= 0) { |
| 190 NOTREACHED(); // Destructors might not have been called. | 192 NOTREACHED(); // Destructors might not have been called. |
| 191 break; | 193 break; |
| 192 } | 194 } |
| 193 } | 195 } |
| 194 | 196 |
| 195 // Remove our stack allocated vector. | 197 // Remove our stack allocated vector. |
| 196 TlsSetValue(tls_key_, NULL); | 198 TlsSetValue(windows_native_tls_key, NULL); |
| 197 } | 199 } |
| 198 | 200 |
| 199 } // namespace base | 201 } // namespace base |
| 200 | |
| 201 // Thread Termination Callbacks. | |
| 202 // Windows doesn't support a per-thread destructor with its | |
| 203 // TLS primitives. So, we build it manually by inserting a | |
| 204 // function to be called on each thread's exit. | |
| 205 // This magic is from http://www.codeproject.com/threads/tls.asp | |
| 206 // and it works for VC++ 7.0 and later. | |
| 207 | |
| 208 // Force a reference to _tls_used to make the linker create the TLS directory | |
| 209 // if it's not already there. (e.g. if __declspec(thread) is not used). | |
| 210 // Force a reference to p_thread_callback_base to prevent whole program | |
| 211 // optimization from discarding the variable. | |
| 212 #ifdef _WIN64 | |
| 213 | |
| 214 #pragma comment(linker, "/INCLUDE:_tls_used") | |
| 215 #pragma comment(linker, "/INCLUDE:p_thread_callback_base") | |
| 216 | |
| 217 #else // _WIN64 | |
| 218 | |
| 219 #pragma comment(linker, "/INCLUDE:__tls_used") | |
| 220 #pragma comment(linker, "/INCLUDE:_p_thread_callback_base") | |
| 221 | |
| 222 #endif // _WIN64 | |
| 223 | |
| 224 // Static callback function to call with each thread termination. | |
| 225 void NTAPI OnThreadExit(PVOID module, DWORD reason, PVOID reserved) { | |
| 226 // On XP SP0 & SP1, the DLL_PROCESS_ATTACH is never seen. It is sent on SP2+ | |
| 227 // and on W2K and W2K3. So don't assume it is sent. | |
| 228 if (DLL_THREAD_DETACH == reason || DLL_PROCESS_DETACH == reason) | |
| 229 base::ThreadLocalStorage::ThreadExit(); | |
| 230 } | |
| 231 | |
| 232 // .CRT$XLA to .CRT$XLZ is an array of PIMAGE_TLS_CALLBACK pointers that are | |
| 233 // called automatically by the OS loader code (not the CRT) when the module is | |
| 234 // loaded and on thread creation. They are NOT called if the module has been | |
| 235 // loaded by a LoadLibrary() call. It must have implicitly been loaded at | |
| 236 // process startup. | |
| 237 // By implicitly loaded, I mean that it is directly referenced by the main EXE | |
| 238 // or by one of its dependent DLLs. Delay-loaded DLL doesn't count as being | |
| 239 // implicitly loaded. | |
| 240 // | |
| 241 // See VC\crt\src\tlssup.c for reference. | |
| 242 | |
| 243 // extern "C" suppresses C++ name mangling so we know the symbol name for the | |
| 244 // linker /INCLUDE:symbol pragma above. | |
| 245 extern "C" { | |
| 246 // The linker must not discard p_thread_callback_base. (We force a reference | |
| 247 // to this variable with a linker /INCLUDE:symbol pragma to ensure that.) If | |
| 248 // this variable is discarded, the OnThreadExit function will never be called. | |
| 249 #ifdef _WIN64 | |
| 250 | |
| 251 // .CRT section is merged with .rdata on x64 so it must be constant data. | |
| 252 #pragma const_seg(".CRT$XLB") | |
| 253 // When defining a const variable, it must have external linkage to be sure the | |
| 254 // linker doesn't discard it. | |
| 255 extern const PIMAGE_TLS_CALLBACK p_thread_callback_base; | |
| 256 const PIMAGE_TLS_CALLBACK p_thread_callback_base = OnThreadExit; | |
| 257 | |
| 258 // Reset the default section. | |
| 259 #pragma const_seg() | |
| 260 | |
| 261 #else // _WIN64 | |
| 262 | |
| 263 #pragma data_seg(".CRT$XLB") | |
| 264 PIMAGE_TLS_CALLBACK p_thread_callback_base = OnThreadExit; | |
| 265 | |
| 266 // Reset the default section. | |
| 267 #pragma data_seg() | |
| 268 | |
| 269 #endif // _WIN64 | |
| 270 } // extern "C" | |
| OLD | NEW |