1 //===-- scudo_tsd_exclusive.cpp ---------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// Scudo exclusive TSD implementation.
12 //===----------------------------------------------------------------------===//
14 #include "scudo_tsd.h"
16 #if SCUDO_TSD_EXCLUSIVE
20 static pthread_once_t GlobalInitialized = PTHREAD_ONCE_INIT;
21 static pthread_key_t PThreadKey;
23 __attribute__((tls_model("initial-exec")))
24 THREADLOCAL ThreadState ScudoThreadState = ThreadNotInitialized;
25 __attribute__((tls_model("initial-exec")))
26 THREADLOCAL ScudoTSD TSD;
28 // Fallback TSD for when the thread isn't initialized yet or is torn down. It
29 // can be shared between multiple threads and as such must be locked.
32 static void teardownThread(void *Ptr) {
33 uptr I = reinterpret_cast<uptr>(Ptr);
34 // The glibc POSIX thread-local-storage deallocation routine calls user
35 // provided destructors in a loop of PTHREAD_DESTRUCTOR_ITERATIONS.
36 // We want to be called last since other destructors might call free and the
37 // like, so we wait until PTHREAD_DESTRUCTOR_ITERATIONS before draining the
38 // quarantine and swallowing the cache.
40 // If pthread_setspecific fails, we will go ahead with the teardown.
41 if (LIKELY(pthread_setspecific(PThreadKey,
42 reinterpret_cast<void *>(I - 1)) == 0))
46 ScudoThreadState = ThreadTornDown;
50 static void initOnce() {
51 CHECK_EQ(pthread_key_create(&PThreadKey, teardownThread), 0);
56 void initThread(bool MinimalInit) {
57 CHECK_EQ(pthread_once(&GlobalInitialized, initOnce), 0);
58 if (UNLIKELY(MinimalInit))
60 CHECK_EQ(pthread_setspecific(PThreadKey, reinterpret_cast<void *>(
61 GetPthreadDestructorIterations())), 0);
63 ScudoThreadState = ThreadInitialized;
66 } // namespace __scudo
68 #endif // SCUDO_TSD_EXCLUSIVE