1/*
2 * Copyright (C) 2008, 2016 Apple Inc. All rights reserved.
3 * Copyright (C) 2009 Jian Li <jianli@chromium.org>
4 * Copyright (C) 2012 Patrick Gansterer <paroga@paroga.com>
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of Apple Inc. ("Apple") nor the names of
16 * its contributors may be used to endorse or promote products derived
17 * from this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31/* Thread local storage is implemented by using either pthread API or Windows
32 * native API. There is subtle semantic discrepancy for the cleanup function
33 * implementation as noted below:
34 * @ In pthread implementation, the destructor function will be called
35 * repeatedly if there is still non-NULL value associated with the function.
36 * @ In Windows native implementation, the destructor function will be called
37 * only once.
38 * This semantic discrepancy does not impose any problem because nowhere in
39 * WebKit the repeated call bahavior is utilized.
40 */
41
42#pragma once
43
44#include <wtf/MainThread.h>
45#include <wtf/Noncopyable.h>
46#include <wtf/StdLibExtras.h>
47
48#if USE(PTHREADS)
49#include <pthread.h>
50
51#if OS(HURD)
52// PTHREAD_KEYS_MAX is not defined in bionic nor in Hurd, so explicitly define it here.
53#define PTHREAD_KEYS_MAX 1024
54#else
55#include <limits.h>
56#endif
57
58#elif OS(WINDOWS)
59#include <windows.h>
60#endif
61
62namespace WTF {
63
64#if OS(WINDOWS) && CPU(X86)
65#define THREAD_SPECIFIC_CALL __stdcall
66#else
67#define THREAD_SPECIFIC_CALL
68#endif
69
70enum class CanBeGCThread {
71 False,
72 True
73};
74
75template<typename T, CanBeGCThread canBeGCThread = CanBeGCThread::False> class ThreadSpecific {
76 WTF_MAKE_NONCOPYABLE(ThreadSpecific);
77public:
78 ThreadSpecific();
79 bool isSet(); // Useful as a fast check to see if this thread has set this value.
80 T* operator->();
81 operator T*();
82 T& operator*();
83
84private:
85 // Not implemented. It's technically possible to destroy a thread specific key, but one would need
86 // to make sure that all values have been destroyed already (usually, that all threads that used it
87 // have exited). It's unlikely that any user of this call will be in that situation - and having
88 // a destructor defined can be confusing, given that it has such strong pre-requisites to work correctly.
89 ~ThreadSpecific();
90
91 struct Data {
92 WTF_MAKE_NONCOPYABLE(Data);
93 WTF_MAKE_FAST_ALLOCATED;
94 public:
95 using PointerType = typename std::remove_const<T>::type*;
96
97 Data(ThreadSpecific<T, canBeGCThread>* owner)
98 : owner(owner)
99 {
100 // Set up thread-specific value's memory pointer before invoking constructor, in case any function it calls
101 // needs to access the value, to avoid recursion.
102 owner->setInTLS(this);
103 new (NotNull, storagePointer()) T();
104 }
105
106 ~Data()
107 {
108 storagePointer()->~T();
109 owner->setInTLS(nullptr);
110 }
111
112 PointerType storagePointer() const { return const_cast<PointerType>(reinterpret_cast<const T*>(&m_storage)); }
113
114 typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type m_storage;
115 ThreadSpecific<T, canBeGCThread>* owner;
116 };
117
118 T* get();
119 T* set();
120 void setInTLS(Data*);
121 void static THREAD_SPECIFIC_CALL destroy(void* ptr);
122
123#if USE(PTHREADS)
124 pthread_key_t m_key { };
125#elif OS(WINDOWS)
126 int m_index;
127#endif
128};
129
130#if USE(PTHREADS)
131
132typedef pthread_key_t ThreadSpecificKey;
133
134static const constexpr ThreadSpecificKey InvalidThreadSpecificKey = PTHREAD_KEYS_MAX;
135
136inline void threadSpecificKeyCreate(ThreadSpecificKey* key, void (*destructor)(void *))
137{
138 int error = pthread_key_create(key, destructor);
139 if (error)
140 CRASH();
141}
142
143inline void threadSpecificKeyDelete(ThreadSpecificKey key)
144{
145 int error = pthread_key_delete(key);
146 if (error)
147 CRASH();
148}
149
150inline void threadSpecificSet(ThreadSpecificKey key, void* value)
151{
152 pthread_setspecific(key, value);
153}
154
155inline void* threadSpecificGet(ThreadSpecificKey key)
156{
157 return pthread_getspecific(key);
158}
159
160template<typename T, CanBeGCThread canBeGCThread>
161inline ThreadSpecific<T, canBeGCThread>::ThreadSpecific()
162{
163 int error = pthread_key_create(&m_key, destroy);
164 if (error)
165 CRASH();
166}
167
168template<typename T, CanBeGCThread canBeGCThread>
169inline T* ThreadSpecific<T, canBeGCThread>::get()
170{
171 Data* data = static_cast<Data*>(pthread_getspecific(m_key));
172 if (data)
173 return data->storagePointer();
174 return nullptr;
175}
176
177template<typename T, CanBeGCThread canBeGCThread>
178inline void ThreadSpecific<T, canBeGCThread>::setInTLS(Data* data)
179{
180 pthread_setspecific(m_key, data);
181}
182
183#elif OS(WINDOWS)
184
185// The maximum number of FLS keys that can be created. For simplification, we assume that:
186// 1) Once the instance of ThreadSpecific<> is created, it will not be destructed until the program dies.
187// 2) We do not need to hold many instances of ThreadSpecific<> data. This fixed number should be far enough.
188const int kMaxFlsKeySize = 128;
189
190WTF_EXPORT_PRIVATE long& flsKeyCount();
191WTF_EXPORT_PRIVATE DWORD* flsKeys();
192
193typedef DWORD ThreadSpecificKey;
194
195static const constexpr ThreadSpecificKey InvalidThreadSpecificKey = FLS_OUT_OF_INDEXES;
196
197inline void threadSpecificKeyCreate(ThreadSpecificKey* key, void (THREAD_SPECIFIC_CALL *destructor)(void *))
198{
199 DWORD flsKey = FlsAlloc(destructor);
200 if (flsKey == FLS_OUT_OF_INDEXES)
201 CRASH();
202
203 *key = flsKey;
204}
205
206inline void threadSpecificKeyDelete(ThreadSpecificKey key)
207{
208 FlsFree(key);
209}
210
211inline void threadSpecificSet(ThreadSpecificKey key, void* data)
212{
213 FlsSetValue(key, data);
214}
215
216inline void* threadSpecificGet(ThreadSpecificKey key)
217{
218 return FlsGetValue(key);
219}
220
221template<typename T, CanBeGCThread canBeGCThread>
222inline ThreadSpecific<T, canBeGCThread>::ThreadSpecific()
223 : m_index(-1)
224{
225 DWORD flsKey = FlsAlloc(destroy);
226 if (flsKey == FLS_OUT_OF_INDEXES)
227 CRASH();
228
229 m_index = InterlockedIncrement(&flsKeyCount()) - 1;
230 if (m_index >= kMaxFlsKeySize)
231 CRASH();
232 flsKeys()[m_index] = flsKey;
233}
234
235template<typename T, CanBeGCThread canBeGCThread>
236inline ThreadSpecific<T, canBeGCThread>::~ThreadSpecific()
237{
238 FlsFree(flsKeys()[m_index]);
239}
240
241template<typename T, CanBeGCThread canBeGCThread>
242inline T* ThreadSpecific<T, canBeGCThread>::get()
243{
244 Data* data = static_cast<Data*>(FlsGetValue(flsKeys()[m_index]));
245 if (data)
246 return data->storagePointer();
247 return nullptr;
248}
249
250template<typename T, CanBeGCThread canBeGCThread>
251inline void ThreadSpecific<T, canBeGCThread>::setInTLS(Data* data)
252{
253 FlsSetValue(flsKeys()[m_index], data);
254}
255
256#else
257#error ThreadSpecific is not implemented for this platform.
258#endif
259
260template<typename T, CanBeGCThread canBeGCThread>
261inline void THREAD_SPECIFIC_CALL ThreadSpecific<T, canBeGCThread>::destroy(void* ptr)
262{
263 Data* data = static_cast<Data*>(ptr);
264
265#if USE(PTHREADS)
266 // We want get() to keep working while data destructor works, because it can be called indirectly by the destructor.
267 // Some pthreads implementations zero out the pointer before calling destroy(), so we temporarily reset it.
268 pthread_setspecific(data->owner->m_key, ptr);
269#endif
270
271 delete data;
272}
273
274template<typename T, CanBeGCThread canBeGCThread>
275inline T* ThreadSpecific<T, canBeGCThread>::set()
276{
277 RELEASE_ASSERT(canBeGCThread == CanBeGCThread::True || !mayBeGCThread());
278 ASSERT(!get());
279 Data* data = new Data(this); // Data will set itself into TLS.
280 ASSERT(get() == data->storagePointer());
281 return data->storagePointer();
282}
283
284template<typename T, CanBeGCThread canBeGCThread>
285inline bool ThreadSpecific<T, canBeGCThread>::isSet()
286{
287 return !!get();
288}
289
290template<typename T, CanBeGCThread canBeGCThread>
291inline ThreadSpecific<T, canBeGCThread>::operator T*()
292{
293 if (T* ptr = get())
294 return ptr;
295 return set();
296}
297
298template<typename T, CanBeGCThread canBeGCThread>
299inline T* ThreadSpecific<T, canBeGCThread>::operator->()
300{
301 return operator T*();
302}
303
304template<typename T, CanBeGCThread canBeGCThread>
305inline T& ThreadSpecific<T, canBeGCThread>::operator*()
306{
307 return *operator T*();
308}
309
310} // namespace WTF
311
312using WTF::ThreadSpecific;
313