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#include <wtf/Threading.h>
48
49namespace WTF {
50
51enum class CanBeGCThread {
52 False,
53 True
54};
55
56template<typename T, CanBeGCThread canBeGCThread = CanBeGCThread::False> class ThreadSpecific {
57 WTF_MAKE_NONCOPYABLE(ThreadSpecific);
58public:
59 ThreadSpecific();
60 bool isSet(); // Useful as a fast check to see if this thread has set this value.
61 T* operator->();
62 operator T*();
63 T& operator*();
64
65private:
66 // Not implemented. It's technically possible to destroy a thread specific key, but one would need
67 // to make sure that all values have been destroyed already (usually, that all threads that used it
68 // have exited). It's unlikely that any user of this call will be in that situation - and having
69 // a destructor defined can be confusing, given that it has such strong pre-requisites to work correctly.
70 ~ThreadSpecific();
71
72 struct Data {
73 WTF_MAKE_NONCOPYABLE(Data);
74 WTF_MAKE_FAST_ALLOCATED;
75 public:
76 using PointerType = typename std::remove_const<T>::type*;
77
78 Data(ThreadSpecific<T, canBeGCThread>* owner)
79 : owner(owner)
80 {
81 // Set up thread-specific value's memory pointer before invoking constructor, in case any function it calls
82 // needs to access the value, to avoid recursion.
83 owner->setInTLS(this);
84 new (NotNull, storagePointer()) T();
85 }
86
87 ~Data()
88 {
89 storagePointer()->~T();
90 owner->setInTLS(nullptr);
91 }
92
93 PointerType storagePointer() const { return const_cast<PointerType>(reinterpret_cast<const T*>(&m_storage)); }
94
95 typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type m_storage;
96 ThreadSpecific<T, canBeGCThread>* owner;
97 };
98
99 T* get();
100 T* set();
101 void setInTLS(Data*);
102 void static THREAD_SPECIFIC_CALL destroy(void* ptr);
103
104#if USE(PTHREADS)
105 pthread_key_t m_key { };
106#elif OS(WINDOWS)
107 int m_index;
108#endif
109};
110
111#if USE(PTHREADS)
112
113template<typename T, CanBeGCThread canBeGCThread>
114inline ThreadSpecific<T, canBeGCThread>::ThreadSpecific()
115{
116 int error = pthread_key_create(&m_key, destroy);
117 if (error)
118 CRASH();
119}
120
121template<typename T, CanBeGCThread canBeGCThread>
122inline T* ThreadSpecific<T, canBeGCThread>::get()
123{
124 Data* data = static_cast<Data*>(pthread_getspecific(m_key));
125 if (data)
126 return data->storagePointer();
127 return nullptr;
128}
129
130template<typename T, CanBeGCThread canBeGCThread>
131inline void ThreadSpecific<T, canBeGCThread>::setInTLS(Data* data)
132{
133 pthread_setspecific(m_key, data);
134}
135
136#elif OS(WINDOWS)
137
138// The maximum number of FLS keys that can be created. For simplification, we assume that:
139// 1) Once the instance of ThreadSpecific<> is created, it will not be destructed until the program dies.
140// 2) We do not need to hold many instances of ThreadSpecific<> data. This fixed number should be far enough.
141static constexpr int maxFlsKeySize = 128;
142
143WTF_EXPORT_PRIVATE long& flsKeyCount();
144WTF_EXPORT_PRIVATE DWORD* flsKeys();
145
146template<typename T, CanBeGCThread canBeGCThread>
147inline ThreadSpecific<T, canBeGCThread>::ThreadSpecific()
148 : m_index(-1)
149{
150 DWORD flsKey = FlsAlloc(destroy);
151 if (flsKey == FLS_OUT_OF_INDEXES)
152 CRASH();
153
154 m_index = InterlockedIncrement(&flsKeyCount()) - 1;
155 if (m_index >= maxFlsKeySize)
156 CRASH();
157 flsKeys()[m_index] = flsKey;
158}
159
160template<typename T, CanBeGCThread canBeGCThread>
161inline ThreadSpecific<T, canBeGCThread>::~ThreadSpecific()
162{
163 FlsFree(flsKeys()[m_index]);
164}
165
166template<typename T, CanBeGCThread canBeGCThread>
167inline T* ThreadSpecific<T, canBeGCThread>::get()
168{
169 Data* data = static_cast<Data*>(FlsGetValue(flsKeys()[m_index]));
170 if (data)
171 return data->storagePointer();
172 return nullptr;
173}
174
175template<typename T, CanBeGCThread canBeGCThread>
176inline void ThreadSpecific<T, canBeGCThread>::setInTLS(Data* data)
177{
178 FlsSetValue(flsKeys()[m_index], data);
179}
180
181#else
182#error ThreadSpecific is not implemented for this platform.
183#endif
184
185template<typename T, CanBeGCThread canBeGCThread>
186inline void THREAD_SPECIFIC_CALL ThreadSpecific<T, canBeGCThread>::destroy(void* ptr)
187{
188 Data* data = static_cast<Data*>(ptr);
189
190#if USE(PTHREADS)
191 // We want get() to keep working while data destructor works, because it can be called indirectly by the destructor.
192 // Some pthreads implementations zero out the pointer before calling destroy(), so we temporarily reset it.
193 pthread_setspecific(data->owner->m_key, ptr);
194#endif
195
196 delete data;
197}
198
199template<typename T, CanBeGCThread canBeGCThread>
200inline T* ThreadSpecific<T, canBeGCThread>::set()
201{
202 RELEASE_ASSERT(canBeGCThread == CanBeGCThread::True || !Thread::mayBeGCThread());
203 ASSERT(!get());
204 Data* data = new Data(this); // Data will set itself into TLS.
205 ASSERT(get() == data->storagePointer());
206 return data->storagePointer();
207}
208
209template<typename T, CanBeGCThread canBeGCThread>
210inline bool ThreadSpecific<T, canBeGCThread>::isSet()
211{
212 return !!get();
213}
214
215template<typename T, CanBeGCThread canBeGCThread>
216inline ThreadSpecific<T, canBeGCThread>::operator T*()
217{
218 if (T* ptr = get())
219 return ptr;
220 return set();
221}
222
223template<typename T, CanBeGCThread canBeGCThread>
224inline T* ThreadSpecific<T, canBeGCThread>::operator->()
225{
226 return operator T*();
227}
228
229template<typename T, CanBeGCThread canBeGCThread>
230inline T& ThreadSpecific<T, canBeGCThread>::operator*()
231{
232 return *operator T*();
233}
234
235} // namespace WTF
236
237using WTF::ThreadSpecific;
238