fix potential memory leak in ThreadLocal
[folly.git] / folly / detail / ThreadLocalDetail.h
1 /*
2  * Copyright 2014 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #ifndef FOLLY_DETAIL_THREADLOCALDETAIL_H_
18 #define FOLLY_DETAIL_THREADLOCALDETAIL_H_
19
20 #include <limits.h>
21 #include <pthread.h>
22
23 #include <mutex>
24 #include <string>
25 #include <vector>
26
27 #include <glog/logging.h>
28
29 #include <folly/Foreach.h>
30 #include <folly/Exception.h>
31 #include <folly/Malloc.h>
32
33 namespace folly {
34 namespace threadlocal_detail {
35
36 /**
37  * Base class for deleters.
38  */
39 class DeleterBase {
40  public:
41   virtual ~DeleterBase() { }
42   virtual void dispose(void* ptr, TLPDestructionMode mode) const = 0;
43 };
44
45 /**
46  * Simple deleter class that calls delete on the passed-in pointer.
47  */
48 template <class Ptr>
49 class SimpleDeleter : public DeleterBase {
50  public:
51   virtual void dispose(void* ptr, TLPDestructionMode mode) const {
52     delete static_cast<Ptr>(ptr);
53   }
54 };
55
56 /**
57  * Custom deleter that calls a given callable.
58  */
59 template <class Ptr, class Deleter>
60 class CustomDeleter : public DeleterBase {
61  public:
62   explicit CustomDeleter(Deleter d) : deleter_(d) { }
63   virtual void dispose(void* ptr, TLPDestructionMode mode) const {
64     deleter_(static_cast<Ptr>(ptr), mode);
65   }
66  private:
67   Deleter deleter_;
68 };
69
70
71 /**
72  * POD wrapper around an element (a void*) and an associated deleter.
73  * This must be POD, as we memset() it to 0 and memcpy() it around.
74  */
75 struct ElementWrapper {
76   bool dispose(TLPDestructionMode mode) {
77     if (ptr == nullptr) {
78       return false;
79     }
80
81     DCHECK(deleter != nullptr);
82     deleter->dispose(ptr, mode);
83     cleanup();
84     return true;
85   }
86
87   void* release() {
88     auto retPtr = ptr;
89
90     if (ptr != nullptr) {
91       cleanup();
92     }
93
94     return retPtr;
95   }
96
97   template <class Ptr>
98   void set(Ptr p) {
99     DCHECK(ptr == nullptr);
100     DCHECK(deleter == nullptr);
101
102     if (p) {
103       // We leak a single object here but that is ok.  If we used an
104       // object directly, there is a chance that the destructor will be
105       // called on that static object before any of the ElementWrappers
106       // are disposed and that isn't so nice.
107       static auto d = new SimpleDeleter<Ptr>();
108       ptr = p;
109       deleter = d;
110       ownsDeleter = false;
111     }
112   }
113
114   template <class Ptr, class Deleter>
115   void set(Ptr p, Deleter d) {
116     DCHECK(ptr == nullptr);
117     DCHECK(deleter == nullptr);
118     if (p) {
119       ptr = p;
120       deleter = new CustomDeleter<Ptr,Deleter>(d);
121       ownsDeleter = true;
122     }
123   }
124
125   void cleanup() {
126     if (ownsDeleter) {
127       delete deleter;
128     }
129     ptr = nullptr;
130     deleter = nullptr;
131     ownsDeleter = false;
132   }
133
134   void* ptr;
135   DeleterBase* deleter;
136   bool ownsDeleter;
137 };
138
139 /**
140  * Per-thread entry.  Each thread using a StaticMeta object has one.
141  * This is written from the owning thread only (under the lock), read
142  * from the owning thread (no lock necessary), and read from other threads
143  * (under the lock).
144  */
145 struct ThreadEntry {
146   ElementWrapper* elements;
147   size_t elementsCapacity;
148   ThreadEntry* next;
149   ThreadEntry* prev;
150 };
151
152 // Held in a singleton to track our global instances.
153 // We have one of these per "Tag", by default one for the whole system
154 // (Tag=void).
155 //
156 // Creating and destroying ThreadLocalPtr objects, as well as thread exit
157 // for threads that use ThreadLocalPtr objects collide on a lock inside
158 // StaticMeta; you can specify multiple Tag types to break that lock.
159 template <class Tag>
160 struct StaticMeta {
161   static StaticMeta<Tag>& instance() {
162     // Leak it on exit, there's only one per process and we don't have to
163     // worry about synchronization with exiting threads.
164     static bool constructed = (inst_ = new StaticMeta<Tag>());
165     (void)constructed; // suppress unused warning
166     return *inst_;
167   }
168
169   int nextId_;
170   std::vector<int> freeIds_;
171   std::mutex lock_;
172   pthread_key_t pthreadKey_;
173   ThreadEntry head_;
174
175   void push_back(ThreadEntry* t) {
176     t->next = &head_;
177     t->prev = head_.prev;
178     head_.prev->next = t;
179     head_.prev = t;
180   }
181
182   void erase(ThreadEntry* t) {
183     t->next->prev = t->prev;
184     t->prev->next = t->next;
185     t->next = t->prev = t;
186   }
187
188 #if !__APPLE__
189   static FOLLY_TLS ThreadEntry threadEntry_;
190 #endif
191   static StaticMeta<Tag>* inst_;
192
193   StaticMeta() : nextId_(1) {
194     head_.next = head_.prev = &head_;
195     int ret = pthread_key_create(&pthreadKey_, &onThreadExit);
196     checkPosixError(ret, "pthread_key_create failed");
197
198     // pthread_atfork is not part of the Android NDK at least as of n9d. If
199     // something is trying to call native fork() directly at all with Android's
200     // process management model, this is probably the least of the problems.
201 #if !__ANDROID__
202     ret = pthread_atfork(/*prepare*/ &StaticMeta::preFork,
203                          /*parent*/ &StaticMeta::onForkParent,
204                          /*child*/ &StaticMeta::onForkChild);
205     checkPosixError(ret, "pthread_atfork failed");
206 #endif
207   }
208   ~StaticMeta() {
209     LOG(FATAL) << "StaticMeta lives forever!";
210   }
211
212   static ThreadEntry* getThreadEntry() {
213 #if !__APPLE__
214     return &threadEntry_;
215 #else
216     ThreadEntry* threadEntry =
217         static_cast<ThreadEntry*>(pthread_getspecific(inst_->pthreadKey_));
218     if (!threadEntry) {
219         threadEntry = new ThreadEntry();
220         int ret = pthread_setspecific(inst_->pthreadKey_, threadEntry);
221         checkPosixError(ret, "pthread_setspecific failed");
222     }
223     return threadEntry;
224 #endif
225   }
226
227   static void preFork(void) {
228     instance().lock_.lock();  // Make sure it's created
229   }
230
231   static void onForkParent(void) {
232     inst_->lock_.unlock();
233   }
234
235   static void onForkChild(void) {
236     // only the current thread survives
237     inst_->head_.next = inst_->head_.prev = &inst_->head_;
238     ThreadEntry* threadEntry = getThreadEntry();
239     // If this thread was in the list before the fork, add it back.
240     if (threadEntry->elementsCapacity != 0) {
241       inst_->push_back(threadEntry);
242     }
243     inst_->lock_.unlock();
244   }
245
246   static void onThreadExit(void* ptr) {
247     auto& meta = instance();
248 #if !__APPLE__
249     ThreadEntry* threadEntry = getThreadEntry();
250
251     DCHECK_EQ(ptr, &meta);
252     DCHECK_GT(threadEntry->elementsCapacity, 0);
253 #else
254     ThreadEntry* threadEntry = static_cast<ThreadEntry*>(ptr);
255 #endif
256     {
257       std::lock_guard<std::mutex> g(meta.lock_);
258       meta.erase(threadEntry);
259       // No need to hold the lock any longer; the ThreadEntry is private to this
260       // thread now that it's been removed from meta.
261     }
262     // NOTE: User-provided deleter / object dtor itself may be using ThreadLocal
263     // with the same Tag, so dispose() calls below may (re)create some of the
264     // elements or even increase elementsCapacity, thus multiple cleanup rounds
265     // may be required.
266     for (bool shouldRun = true; shouldRun; ) {
267       shouldRun = false;
268       FOR_EACH_RANGE(i, 0, threadEntry->elementsCapacity) {
269         if (threadEntry->elements[i].dispose(TLPDestructionMode::THIS_THREAD)) {
270           shouldRun = true;
271         }
272       }
273     }
274     free(threadEntry->elements);
275     threadEntry->elements = nullptr;
276     pthread_setspecific(meta.pthreadKey_, nullptr);
277
278 #if __APPLE__
279     // Allocated in getThreadEntry(); free it
280     delete threadEntry;
281 #endif
282   }
283
284   static int create() {
285     int id;
286     auto & meta = instance();
287     std::lock_guard<std::mutex> g(meta.lock_);
288     if (!meta.freeIds_.empty()) {
289       id = meta.freeIds_.back();
290       meta.freeIds_.pop_back();
291     } else {
292       id = meta.nextId_++;
293     }
294     return id;
295   }
296
297   static void destroy(size_t id) {
298     try {
299       auto & meta = instance();
300       // Elements in other threads that use this id.
301       std::vector<ElementWrapper> elements;
302       {
303         std::lock_guard<std::mutex> g(meta.lock_);
304         for (ThreadEntry* e = meta.head_.next; e != &meta.head_; e = e->next) {
305           if (id < e->elementsCapacity && e->elements[id].ptr) {
306             elements.push_back(e->elements[id]);
307
308             /*
309              * Writing another thread's ThreadEntry from here is fine;
310              * the only other potential reader is the owning thread --
311              * from onThreadExit (which grabs the lock, so is properly
312              * synchronized with us) or from get(), which also grabs
313              * the lock if it needs to resize the elements vector.
314              *
315              * We can't conflict with reads for a get(id), because
316              * it's illegal to call get on a thread local that's
317              * destructing.
318              */
319             e->elements[id].ptr = nullptr;
320             e->elements[id].deleter = nullptr;
321             e->elements[id].ownsDeleter = false;
322           }
323         }
324         meta.freeIds_.push_back(id);
325       }
326       // Delete elements outside the lock
327       FOR_EACH(it, elements) {
328         it->dispose(TLPDestructionMode::ALL_THREADS);
329       }
330     } catch (...) { // Just in case we get a lock error or something anyway...
331       LOG(WARNING) << "Destructor discarding an exception that was thrown.";
332     }
333   }
334
335   /**
336    * Reserve enough space in the ThreadEntry::elements for the item
337    * @id to fit in.
338    */
339   static void reserve(int id) {
340     auto& meta = instance();
341     ThreadEntry* threadEntry = getThreadEntry();
342     size_t prevCapacity = threadEntry->elementsCapacity;
343     // Growth factor < 2, see folly/docs/FBVector.md; + 5 to prevent
344     // very slow start.
345     size_t newCapacity = static_cast<size_t>((id + 5) * 1.7);
346     assert(newCapacity > prevCapacity);
347     ElementWrapper* reallocated = nullptr;
348
349     // Need to grow. Note that we can't call realloc, as elements is
350     // still linked in meta, so another thread might access invalid memory
351     // after realloc succeeds. We'll copy by hand and update our ThreadEntry
352     // under the lock.
353     if (usingJEMalloc()) {
354       bool success = false;
355       size_t newByteSize = nallocx(newCapacity * sizeof(ElementWrapper), 0);
356
357       // Try to grow in place.
358       //
359       // Note that xallocx(MALLOCX_ZERO) will only zero newly allocated memory,
360       // even if a previous allocation allocated more than we requested.
361       // This is fine; we always use MALLOCX_ZERO with jemalloc and we
362       // always expand our allocation to the real size.
363       if (prevCapacity * sizeof(ElementWrapper) >=
364           jemallocMinInPlaceExpandable) {
365         success = (xallocx(threadEntry->elements, newByteSize, 0, MALLOCX_ZERO)
366                    == newByteSize);
367       }
368
369       // In-place growth failed.
370       if (!success) {
371         success = ((reallocated = static_cast<ElementWrapper*>(
372                     mallocx(newByteSize, MALLOCX_ZERO))) != nullptr);
373       }
374
375       if (success) {
376         // Expand to real size
377         assert(newByteSize / sizeof(ElementWrapper) >= newCapacity);
378         newCapacity = newByteSize / sizeof(ElementWrapper);
379       } else {
380         throw std::bad_alloc();
381       }
382     } else {  // no jemalloc
383       // calloc() is simpler than malloc() followed by memset(), and
384       // potentially faster when dealing with a lot of memory, as it can get
385       // already-zeroed pages from the kernel.
386       reallocated = static_cast<ElementWrapper*>(
387           calloc(newCapacity, sizeof(ElementWrapper)));
388       if (!reallocated) {
389         throw std::bad_alloc();
390       }
391     }
392
393     // Success, update the entry
394     {
395       std::lock_guard<std::mutex> g(meta.lock_);
396
397       if (prevCapacity == 0) {
398         meta.push_back(threadEntry);
399       }
400
401       if (reallocated) {
402        /*
403         * Note: we need to hold the meta lock when copying data out of
404         * the old vector, because some other thread might be
405         * destructing a ThreadLocal and writing to the elements vector
406         * of this thread.
407         */
408         memcpy(reallocated, threadEntry->elements,
409                sizeof(ElementWrapper) * prevCapacity);
410         using std::swap;
411         swap(reallocated, threadEntry->elements);
412       }
413       threadEntry->elementsCapacity = newCapacity;
414     }
415
416     free(reallocated);
417
418 #if !__APPLE__
419     if (prevCapacity == 0) {
420       pthread_setspecific(meta.pthreadKey_, &meta);
421     }
422 #endif
423   }
424
425   static ElementWrapper& get(size_t id) {
426     ThreadEntry* threadEntry = getThreadEntry();
427     if (UNLIKELY(threadEntry->elementsCapacity <= id)) {
428       reserve(id);
429       assert(threadEntry->elementsCapacity > id);
430     }
431     return threadEntry->elements[id];
432   }
433 };
434
435 #if !__APPLE__
436 template <class Tag>
437 FOLLY_TLS ThreadEntry StaticMeta<Tag>::threadEntry_{nullptr, 0,
438                                                     nullptr, nullptr};
439 #endif
440 template <class Tag> StaticMeta<Tag>* StaticMeta<Tag>::inst_ = nullptr;
441
442 }  // namespace threadlocal_detail
443 }  // namespace folly
444
445 #endif /* FOLLY_DETAIL_THREADLOCALDETAIL_H_ */