1 // Copyright 2017 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "absl/base/internal/thread_identity.h"
16
17 #ifndef _WIN32
18 #include <pthread.h>
19 #include <signal.h>
20 #endif
21
22 #include <atomic>
23 #include <cassert>
24 #include <memory>
25
26 #include "absl/base/attributes.h"
27 #include "absl/base/call_once.h"
28 #include "absl/base/internal/raw_logging.h"
29 #include "absl/base/internal/spinlock.h"
30
31 namespace absl {
32 ABSL_NAMESPACE_BEGIN
33 namespace base_internal {
34
35 #if ABSL_THREAD_IDENTITY_MODE != ABSL_THREAD_IDENTITY_MODE_USE_CPP11
36 namespace {
37 // Used to co-ordinate one-time creation of our pthread_key
38 absl::once_flag init_thread_identity_key_once;
39 pthread_key_t thread_identity_pthread_key;
40 std::atomic<bool> pthread_key_initialized(false);
41
AllocateThreadIdentityKey(ThreadIdentityReclaimerFunction reclaimer)42 void AllocateThreadIdentityKey(ThreadIdentityReclaimerFunction reclaimer) {
43 pthread_key_create(&thread_identity_pthread_key, reclaimer);
44 pthread_key_initialized.store(true, std::memory_order_release);
45 }
46 } // namespace
47 #endif
48
49 #if ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_TLS || \
50 ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_CPP11
51 // The actual TLS storage for a thread's currently associated ThreadIdentity.
52 // This is referenced by inline accessors in the header.
53 // "protected" visibility ensures that if multiple instances of Abseil code
54 // exist within a process (via dlopen() or similar), references to
55 // thread_identity_ptr from each instance of the code will refer to
56 // *different* instances of this ptr.
57 // Apple platforms have the visibility attribute, but issue a compile warning
58 // that protected visibility is unsupported.
59 #if ABSL_HAVE_ATTRIBUTE(visibility) && !defined(__APPLE__)
60 __attribute__((visibility("protected")))
61 #endif // ABSL_HAVE_ATTRIBUTE(visibility) && !defined(__APPLE__)
62 #if ABSL_PER_THREAD_TLS
63 // Prefer __thread to thread_local as benchmarks indicate it is a bit faster.
64 ABSL_PER_THREAD_TLS_KEYWORD ThreadIdentity* thread_identity_ptr = nullptr;
65 #elif defined(ABSL_HAVE_THREAD_LOCAL)
66 thread_local ThreadIdentity* thread_identity_ptr = nullptr;
67 #endif // ABSL_PER_THREAD_TLS
68 #endif // TLS or CPP11
69
SetCurrentThreadIdentity(ThreadIdentity * identity,ThreadIdentityReclaimerFunction reclaimer)70 void SetCurrentThreadIdentity(
71 ThreadIdentity* identity, ThreadIdentityReclaimerFunction reclaimer) {
72 assert(CurrentThreadIdentityIfPresent() == nullptr);
73 // Associate our destructor.
74 // NOTE: This call to pthread_setspecific is currently the only immovable
75 // barrier to CurrentThreadIdentity() always being async signal safe.
76 #if ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC
77 // NOTE: Not async-safe. But can be open-coded.
78 absl::call_once(init_thread_identity_key_once, AllocateThreadIdentityKey,
79 reclaimer);
80
81 #if defined(__EMSCRIPTEN__) || defined(__MINGW32__)
82 // Emscripten and MinGW pthread implementations does not support signals.
83 // See https://kripken.github.io/emscripten-site/docs/porting/pthreads.html
84 // for more information.
85 pthread_setspecific(thread_identity_pthread_key,
86 reinterpret_cast<void*>(identity));
87 #else
88 // We must mask signals around the call to setspecific as with current glibc,
89 // a concurrent getspecific (needed for GetCurrentThreadIdentityIfPresent())
90 // may zero our value.
91 //
92 // While not officially async-signal safe, getspecific within a signal handler
93 // is otherwise OK.
94 sigset_t all_signals;
95 sigset_t curr_signals;
96 sigfillset(&all_signals);
97 pthread_sigmask(SIG_SETMASK, &all_signals, &curr_signals);
98 pthread_setspecific(thread_identity_pthread_key,
99 reinterpret_cast<void*>(identity));
100 pthread_sigmask(SIG_SETMASK, &curr_signals, nullptr);
101 #endif // !__EMSCRIPTEN__ && !__MINGW32__
102
103 #elif ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_TLS
104 // NOTE: Not async-safe. But can be open-coded.
105 absl::call_once(init_thread_identity_key_once, AllocateThreadIdentityKey,
106 reclaimer);
107 pthread_setspecific(thread_identity_pthread_key,
108 reinterpret_cast<void*>(identity));
109 thread_identity_ptr = identity;
110 #elif ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_CPP11
111 thread_local std::unique_ptr<ThreadIdentity, ThreadIdentityReclaimerFunction>
112 holder(identity, reclaimer);
113 thread_identity_ptr = identity;
114 #else
115 #error Unimplemented ABSL_THREAD_IDENTITY_MODE
116 #endif
117 }
118
119 #if ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_TLS || \
120 ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_CPP11
121
122 // Please see the comment on `CurrentThreadIdentityIfPresent` in
123 // thread_identity.h. When we cannot expose thread_local variables in
124 // headers, we opt for the correct-but-slower option of not inlining this
125 // function.
126 #ifndef ABSL_INTERNAL_INLINE_CURRENT_THREAD_IDENTITY_IF_PRESENT
CurrentThreadIdentityIfPresent()127 ThreadIdentity* CurrentThreadIdentityIfPresent() { return thread_identity_ptr; }
128 #endif
129 #endif
130
ClearCurrentThreadIdentity()131 void ClearCurrentThreadIdentity() {
132 #if ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_TLS || \
133 ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_CPP11
134 thread_identity_ptr = nullptr;
135 #elif ABSL_THREAD_IDENTITY_MODE == \
136 ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC
137 // pthread_setspecific expected to clear value on destruction
138 assert(CurrentThreadIdentityIfPresent() == nullptr);
139 #endif
140 }
141
142 #if ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC
CurrentThreadIdentityIfPresent()143 ThreadIdentity* CurrentThreadIdentityIfPresent() {
144 bool initialized = pthread_key_initialized.load(std::memory_order_acquire);
145 if (!initialized) {
146 return nullptr;
147 }
148 return reinterpret_cast<ThreadIdentity*>(
149 pthread_getspecific(thread_identity_pthread_key));
150 }
151 #endif
152
153 } // namespace base_internal
154 ABSL_NAMESPACE_END
155 } // namespace absl
156