]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/scudo/scudo_tsd_exclusive.cpp
Merge clang 7.0.1 and several follow-up changes
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / scudo / scudo_tsd_exclusive.cpp
1 //===-- scudo_tsd_exclusive.cpp ---------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// Scudo exclusive TSD implementation.
11 ///
12 //===----------------------------------------------------------------------===//
13
14 #include "scudo_tsd.h"
15
16 #if SCUDO_TSD_EXCLUSIVE
17
18 namespace __scudo {
19
20 static pthread_once_t GlobalInitialized = PTHREAD_ONCE_INIT;
21 static pthread_key_t PThreadKey;
22
23 __attribute__((tls_model("initial-exec")))
24 THREADLOCAL ThreadState ScudoThreadState = ThreadNotInitialized;
25 __attribute__((tls_model("initial-exec")))
26 THREADLOCAL ScudoTSD TSD;
27
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.
30 ScudoTSD FallbackTSD;
31
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.
39   if (I > 1) {
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))
43       return;
44   }
45   TSD.commitBack();
46   ScudoThreadState = ThreadTornDown;
47 }
48
49
50 static void initOnce() {
51   CHECK_EQ(pthread_key_create(&PThreadKey, teardownThread), 0);
52   initScudo();
53   FallbackTSD.init();
54 }
55
56 void initThread(bool MinimalInit) {
57   CHECK_EQ(pthread_once(&GlobalInitialized, initOnce), 0);
58   if (UNLIKELY(MinimalInit))
59     return;
60   CHECK_EQ(pthread_setspecific(PThreadKey, reinterpret_cast<void *>(
61       GetPthreadDestructorIterations())), 0);
62   TSD.init();
63   ScudoThreadState = ThreadInitialized;
64 }
65
66 }  // namespace __scudo
67
68 #endif  // SCUDO_TSD_EXCLUSIVE