1 //===----------------------------------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
8 #ifndef LIBCXXABI_SRC_INCLUDE_CXA_GUARD_IMPL_H
9 #define LIBCXXABI_SRC_INCLUDE_CXA_GUARD_IMPL_H
11 /* cxa_guard_impl.h - Implements the C++ runtime support for function local
13 * The layout of the guard object is the same across ARM and Itanium.
15 * The first "guard byte" (which is checked by the compiler) is set only upon
16 * the completion of cxa release.
18 * The second "init byte" does the rest of the bookkeeping. It tracks if
19 * initialization is complete or pending, and if there are waiting threads.
21 * If the guard variable is 64-bits and the platforms supplies a 32-bit thread
22 * identifier, it is used to detect recursive initialization. The thread ID of
23 * the thread currently performing initialization is stored in the second word.
25 * Guard Object Layout:
26 * ---------------------------------------------------------------------------
27 * | a+0: guard byte | a+1: init byte | a+2: unused ... | a+4: thread-id ... |
28 * ---------------------------------------------------------------------------
30 * Note that we don't do what the ABI docs suggest (put a mutex in the guard
31 * object which we acquire in cxa_guard_acquire and release in
32 * cxa_guard_release). Instead we use the init byte to imitate that behaviour,
33 * but without actually holding anything mutex related between aquire and
37 * For each implementation the guard byte is checked and set before accessing
41 * The implementation was designed to allow each implementation to be tested
42 * independent of the C++ runtime or platform support.
46 #include "__cxxabi_config.h"
47 #include "include/atomic_support.h" // from libc++
48 #if defined(__has_include)
49 # if __has_include(<sys/syscall.h>)
50 # include <sys/syscall.h>
52 # if __has_include(<unistd.h>)
59 #include <__threading_support>
60 #ifndef _LIBCXXABI_HAS_NO_THREADS
61 # if defined(__ELF__) && defined(_LIBCXXABI_LINK_PTHREAD_LIB)
62 # pragma comment(lib, "pthread")
66 #if defined(__clang__)
67 # pragma clang diagnostic push
68 # pragma clang diagnostic ignored "-Wtautological-pointer-compare"
69 #elif defined(__GNUC__)
70 # pragma GCC diagnostic push
71 # pragma GCC diagnostic ignored "-Waddress"
74 // To make testing possible, this header is included from both cxa_guard.cpp
75 // and a number of tests.
77 // For this reason we place everything in an anonymous namespace -- even though
78 // we're in a header. We want the actual implementation and the tests to have
79 // unique definitions of the types in this header (since the tests may depend
80 // on function local statics).
82 // To enforce this either `BUILDING_CXA_GUARD` or `TESTING_CXA_GUARD` must be
83 // defined when including this file. Only `src/cxa_guard.cpp` should define
85 #ifdef BUILDING_CXA_GUARD
86 # include "abort_message.h"
87 # define ABORT_WITH_MESSAGE(...) ::abort_message(__VA_ARGS__)
88 #elif defined(TESTING_CXA_GUARD)
89 # define ABORT_WITH_MESSAGE(...) ::abort()
91 # error "Either BUILDING_CXA_GUARD or TESTING_CXA_GUARD must be defined"
94 #if __has_feature(thread_sanitizer)
95 extern "C" void __tsan_acquire(void*);
96 extern "C" void __tsan_release(void*);
98 # define __tsan_acquire(addr) ((void)0)
99 # define __tsan_release(addr) ((void)0)
102 namespace __cxxabiv1
{
103 // Use an anonymous namespace to ensure that the tests and actual implementation
104 // have unique definitions of these symbols.
107 //===----------------------------------------------------------------------===//
109 //===----------------------------------------------------------------------===//
111 template <class T
, T (*Init
)()>
113 LazyValue() : is_init(false) {}
125 bool is_init
= false;
128 template <class IntType
>
131 using MemoryOrder
= std::__libcpp_atomic_order
;
133 explicit AtomicInt(IntType
* b
) : b_(b
) {}
134 AtomicInt(AtomicInt
const&) = delete;
135 AtomicInt
& operator=(AtomicInt
const&) = delete;
137 IntType
load(MemoryOrder ord
) { return std::__libcpp_atomic_load(b_
, ord
); }
138 void store(IntType val
, MemoryOrder ord
) { std::__libcpp_atomic_store(b_
, val
, ord
); }
139 IntType
exchange(IntType new_val
, MemoryOrder ord
) { return std::__libcpp_atomic_exchange(b_
, new_val
, ord
); }
140 bool compare_exchange(IntType
* expected
, IntType desired
, MemoryOrder ord_success
, MemoryOrder ord_failure
) {
141 return std::__libcpp_atomic_compare_exchange(b_
, expected
, desired
, ord_success
, ord_failure
);
148 //===----------------------------------------------------------------------===//
149 // PlatformGetThreadID
150 //===----------------------------------------------------------------------===//
152 #if defined(__APPLE__) && defined(_LIBCPP_HAS_THREAD_API_PTHREAD)
153 uint32_t PlatformThreadID() {
154 static_assert(sizeof(mach_port_t
) == sizeof(uint32_t), "");
155 return static_cast<uint32_t>(pthread_mach_thread_np(std::__libcpp_thread_get_current_id()));
157 #elif defined(SYS_gettid) && defined(_LIBCPP_HAS_THREAD_API_PTHREAD)
158 uint32_t PlatformThreadID() {
159 static_assert(sizeof(pid_t
) == sizeof(uint32_t), "");
160 return static_cast<uint32_t>(syscall(SYS_gettid
));
163 constexpr uint32_t (*PlatformThreadID
)() = nullptr;
166 //===----------------------------------------------------------------------===//
168 //===----------------------------------------------------------------------===//
170 static constexpr uint8_t UNSET
= 0;
171 static constexpr uint8_t COMPLETE_BIT
= (1 << 0);
172 static constexpr uint8_t PENDING_BIT
= (1 << 1);
173 static constexpr uint8_t WAITING_BIT
= (1 << 2);
175 /// Manages reads and writes to the guard byte.
177 GuardByte() = delete;
178 GuardByte(GuardByte
const&) = delete;
179 GuardByte
& operator=(GuardByte
const&) = delete;
181 explicit GuardByte(uint8_t* const guard_byte_address
) : guard_byte(guard_byte_address
) {}
184 /// The guard byte portion of cxa_guard_acquire. Returns true if
185 /// initialization has already been completed.
187 // if guard_byte is non-zero, we have already completed initialization
188 // (i.e. release has been called)
189 return guard_byte
.load(std::_AO_Acquire
) != UNSET
;
192 /// The guard byte portion of cxa_guard_release.
193 void release() { guard_byte
.store(COMPLETE_BIT
, std::_AO_Release
); }
195 /// The guard byte portion of cxa_guard_abort.
196 void abort() {} // Nothing to do
199 AtomicInt
<uint8_t> guard_byte
;
202 //===----------------------------------------------------------------------===//
203 // InitByte Implementations
204 //===----------------------------------------------------------------------===//
206 // Each initialization byte implementation supports the following methods:
208 // InitByte(uint8_t* _init_byte_address, uint32_t* _thread_id_address)
209 // Construct the InitByte object, initializing our member variables
212 // Called before we start the initialization. Check if someone else has already started, and if
213 // not to signal our intent to start it ourselves. We determine the current status from the init
214 // byte, which is one of 4 possible values:
215 // COMPLETE: Initialization was finished by somebody else. Return true.
216 // PENDING: Somebody has started the initialization already, set the WAITING bit,
217 // then wait for the init byte to get updated with a new value.
218 // (PENDING|WAITING): Somebody has started the initialization already, and we're not the
219 // first one waiting. Wait for the init byte to get updated.
220 // UNSET: Initialization hasn't successfully completed, and nobody is currently
221 // performing the initialization. Set the PENDING bit to indicate our
222 // intention to start the initialization, and return false.
223 // The return value indicates whether initialization has already been completed.
226 // Called after successfully completing the initialization. Update the init byte to reflect
227 // that, then if anybody else is waiting, wake them up.
230 // Called after an error is thrown during the initialization. Reset the init byte to UNSET to
231 // indicate that we're no longer performing the initialization, then if anybody is waiting, wake
232 // them up so they can try performing the initialization.
235 //===----------------------------------------------------------------------===//
236 // Single Threaded Implementation
237 //===----------------------------------------------------------------------===//
239 /// InitByteNoThreads - Doesn't use any inter-thread synchronization when
240 /// managing reads and writes to the init byte.
241 struct InitByteNoThreads
{
242 InitByteNoThreads() = delete;
243 InitByteNoThreads(InitByteNoThreads
const&) = delete;
244 InitByteNoThreads
& operator=(InitByteNoThreads
const&) = delete;
246 explicit InitByteNoThreads(uint8_t* _init_byte_address
, uint32_t*) : init_byte_address(_init_byte_address
) {}
248 /// The init byte portion of cxa_guard_acquire. Returns true if
249 /// initialization has already been completed.
251 if (*init_byte_address
== COMPLETE_BIT
)
253 if (*init_byte_address
& PENDING_BIT
)
254 ABORT_WITH_MESSAGE("__cxa_guard_acquire detected recursive initialization");
255 *init_byte_address
= PENDING_BIT
;
259 /// The init byte portion of cxa_guard_release.
260 void release() { *init_byte_address
= COMPLETE_BIT
; }
261 /// The init byte portion of cxa_guard_abort.
262 void abort() { *init_byte_address
= UNSET
; }
265 /// The address of the byte used during initialization.
266 uint8_t* const init_byte_address
;
269 //===----------------------------------------------------------------------===//
270 // Global Mutex Implementation
271 //===----------------------------------------------------------------------===//
274 struct LibcppCondVar
;
276 #ifndef _LIBCXXABI_HAS_NO_THREADS
278 LibcppMutex() = default;
279 LibcppMutex(LibcppMutex
const&) = delete;
280 LibcppMutex
& operator=(LibcppMutex
const&) = delete;
282 bool lock() { return std::__libcpp_mutex_lock(&mutex
); }
283 bool unlock() { return std::__libcpp_mutex_unlock(&mutex
); }
286 friend struct LibcppCondVar
;
287 std::__libcpp_mutex_t mutex
= _LIBCPP_MUTEX_INITIALIZER
;
290 struct LibcppCondVar
{
291 LibcppCondVar() = default;
292 LibcppCondVar(LibcppCondVar
const&) = delete;
293 LibcppCondVar
& operator=(LibcppCondVar
const&) = delete;
295 bool wait(LibcppMutex
& mut
) { return std::__libcpp_condvar_wait(&cond
, &mut
.mutex
); }
296 bool broadcast() { return std::__libcpp_condvar_broadcast(&cond
); }
299 std::__libcpp_condvar_t cond
= _LIBCPP_CONDVAR_INITIALIZER
;
302 struct LibcppMutex
{};
303 struct LibcppCondVar
{};
304 #endif // !defined(_LIBCXXABI_HAS_NO_THREADS)
306 /// InitByteGlobalMutex - Uses a global mutex and condition variable (common to
307 /// all static local variables) to manage reads and writes to the init byte.
308 template <class Mutex
, class CondVar
, Mutex
& global_mutex
, CondVar
& global_cond
,
309 uint32_t (*GetThreadID
)() = PlatformThreadID
>
310 struct InitByteGlobalMutex
{
312 explicit InitByteGlobalMutex(uint8_t* _init_byte_address
, uint32_t* _thread_id_address
)
313 : init_byte_address(_init_byte_address
), thread_id_address(_thread_id_address
),
314 has_thread_id_support(_thread_id_address
!= nullptr && GetThreadID
!= nullptr) {}
317 /// The init byte portion of cxa_guard_acquire. Returns true if
318 /// initialization has already been completed.
320 LockGuard
g("__cxa_guard_acquire");
321 // Check for possible recursive initialization.
322 if (has_thread_id_support
&& (*init_byte_address
& PENDING_BIT
)) {
323 if (*thread_id_address
== current_thread_id
.get())
324 ABORT_WITH_MESSAGE("__cxa_guard_acquire detected recursive initialization");
327 // Wait until the pending bit is not set.
328 while (*init_byte_address
& PENDING_BIT
) {
329 *init_byte_address
|= WAITING_BIT
;
330 global_cond
.wait(global_mutex
);
333 if (*init_byte_address
== COMPLETE_BIT
)
336 if (has_thread_id_support
)
337 *thread_id_address
= current_thread_id
.get();
339 *init_byte_address
= PENDING_BIT
;
343 /// The init byte portion of cxa_guard_release.
347 LockGuard
g("__cxa_guard_release");
348 has_waiting
= *init_byte_address
& WAITING_BIT
;
349 *init_byte_address
= COMPLETE_BIT
;
352 if (global_cond
.broadcast()) {
353 ABORT_WITH_MESSAGE("%s failed to broadcast", "__cxa_guard_release");
358 /// The init byte portion of cxa_guard_abort.
362 LockGuard
g("__cxa_guard_abort");
363 if (has_thread_id_support
)
364 *thread_id_address
= 0;
365 has_waiting
= *init_byte_address
& WAITING_BIT
;
366 *init_byte_address
= UNSET
;
369 if (global_cond
.broadcast()) {
370 ABORT_WITH_MESSAGE("%s failed to broadcast", "__cxa_guard_abort");
376 /// The address of the byte used during initialization.
377 uint8_t* const init_byte_address
;
378 /// An optional address storing an identifier for the thread performing initialization.
379 /// It's used to detect recursive initialization.
380 uint32_t* const thread_id_address
;
382 const bool has_thread_id_support
;
383 LazyValue
<uint32_t, GetThreadID
> current_thread_id
;
387 LockGuard() = delete;
388 LockGuard(LockGuard
const&) = delete;
389 LockGuard
& operator=(LockGuard
const&) = delete;
391 explicit LockGuard(const char* calling_func
) : calling_func_(calling_func
) {
392 if (global_mutex
.lock())
393 ABORT_WITH_MESSAGE("%s failed to acquire mutex", calling_func_
);
397 if (global_mutex
.unlock())
398 ABORT_WITH_MESSAGE("%s failed to release mutex", calling_func_
);
402 const char* const calling_func_
;
406 //===----------------------------------------------------------------------===//
407 // Futex Implementation
408 //===----------------------------------------------------------------------===//
410 #if defined(SYS_futex)
411 void PlatformFutexWait(int* addr
, int expect
) {
412 constexpr int WAIT
= 0;
413 syscall(SYS_futex
, addr
, WAIT
, expect
, 0);
414 __tsan_acquire(addr
);
416 void PlatformFutexWake(int* addr
) {
417 constexpr int WAKE
= 1;
418 __tsan_release(addr
);
419 syscall(SYS_futex
, addr
, WAKE
, INT_MAX
);
422 constexpr void (*PlatformFutexWait
)(int*, int) = nullptr;
423 constexpr void (*PlatformFutexWake
)(int*) = nullptr;
426 constexpr bool PlatformSupportsFutex() { return +PlatformFutexWait
!= nullptr; }
428 /// InitByteFutex - Uses a futex to manage reads and writes to the init byte.
429 template <void (*Wait
)(int*, int) = PlatformFutexWait
, void (*Wake
)(int*) = PlatformFutexWake
,
430 uint32_t (*GetThreadIDArg
)() = PlatformThreadID
>
431 struct InitByteFutex
{
433 explicit InitByteFutex(uint8_t* _init_byte_address
, uint32_t* _thread_id_address
)
434 : init_byte(_init_byte_address
),
435 has_thread_id_support(_thread_id_address
!= nullptr && GetThreadIDArg
!= nullptr),
436 thread_id(_thread_id_address
),
437 base_address(reinterpret_cast<int*>(/*_init_byte_address & ~0x3*/ _init_byte_address
- 1)) {}
440 /// The init byte portion of cxa_guard_acquire. Returns true if
441 /// initialization has already been completed.
444 uint8_t last_val
= UNSET
;
445 if (init_byte
.compare_exchange(&last_val
, PENDING_BIT
, std::_AO_Acq_Rel
, std::_AO_Acquire
)) {
446 if (has_thread_id_support
) {
447 thread_id
.store(current_thread_id
.get(), std::_AO_Relaxed
);
452 if (last_val
== COMPLETE_BIT
)
455 if (last_val
& PENDING_BIT
) {
457 // Check for recursive initialization
458 if (has_thread_id_support
&& thread_id
.load(std::_AO_Relaxed
) == current_thread_id
.get()) {
459 ABORT_WITH_MESSAGE("__cxa_guard_acquire detected recursive initialization");
462 if ((last_val
& WAITING_BIT
) == 0) {
463 // This compare exchange can fail for several reasons
464 // (1) another thread finished the whole thing before we got here
465 // (2) another thread set the waiting bit we were trying to thread
466 // (3) another thread had an exception and failed to finish
467 if (!init_byte
.compare_exchange(&last_val
, PENDING_BIT
| WAITING_BIT
, std::_AO_Acq_Rel
, std::_AO_Release
)) {
468 // (1) success, via someone else's work!
469 if (last_val
== COMPLETE_BIT
)
472 // (3) someone else, bailed on doing the work, retry from the start!
473 if (last_val
== UNSET
)
476 // (2) the waiting bit got set, so we are happy to keep waiting
479 wait_on_initialization();
484 /// The init byte portion of cxa_guard_release.
486 uint8_t old
= init_byte
.exchange(COMPLETE_BIT
, std::_AO_Acq_Rel
);
487 if (old
& WAITING_BIT
)
491 /// The init byte portion of cxa_guard_abort.
493 if (has_thread_id_support
)
494 thread_id
.store(0, std::_AO_Relaxed
);
496 uint8_t old
= init_byte
.exchange(UNSET
, std::_AO_Acq_Rel
);
497 if (old
& WAITING_BIT
)
502 /// Use the futex to wait on the current guard variable. Futex expects a
503 /// 32-bit 4-byte aligned address as the first argument, so we use the 4-byte
504 /// aligned address that encompasses the init byte (i.e. the address of the
505 /// raw guard object that was passed to __cxa_guard_acquire/release/abort).
506 void wait_on_initialization() { Wait(base_address
, expected_value_for_futex(PENDING_BIT
| WAITING_BIT
)); }
507 void wake_all() { Wake(base_address
); }
510 AtomicInt
<uint8_t> init_byte
;
512 const bool has_thread_id_support
;
513 // Unsafe to use unless has_thread_id_support
514 AtomicInt
<uint32_t> thread_id
;
515 LazyValue
<uint32_t, GetThreadIDArg
> current_thread_id
;
517 /// the 4-byte-aligned address that encompasses the init byte (i.e. the
518 /// address of the raw guard object).
519 int* const base_address
;
521 /// Create the expected integer value for futex `wait(int* addr, int expected)`.
522 /// We pass the base address as the first argument, So this function creates
523 /// an zero-initialized integer with `b` copied at the correct offset.
524 static int expected_value_for_futex(uint8_t b
) {
526 std::memcpy(reinterpret_cast<char*>(&dest_val
) + 1, &b
, 1);
530 static_assert(Wait
!= nullptr && Wake
!= nullptr, "");
533 //===----------------------------------------------------------------------===//
535 //===----------------------------------------------------------------------===//
537 enum class AcquireResult
{
541 constexpr AcquireResult INIT_IS_DONE
= AcquireResult::INIT_IS_DONE
;
542 constexpr AcquireResult INIT_IS_PENDING
= AcquireResult::INIT_IS_PENDING
;
544 /// Co-ordinates between GuardByte and InitByte.
545 template <class InitByteT
>
547 GuardObject() = delete;
548 GuardObject(GuardObject
const&) = delete;
549 GuardObject
& operator=(GuardObject
const&) = delete;
552 GuardByte guard_byte
;
557 explicit GuardObject(uint32_t* raw_guard_object
)
558 : guard_byte(reinterpret_cast<uint8_t*>(raw_guard_object
)),
559 init_byte(reinterpret_cast<uint8_t*>(raw_guard_object
) + 1, nullptr) {}
561 /// Itanium Constructor
562 explicit GuardObject(uint64_t* raw_guard_object
)
563 : guard_byte(reinterpret_cast<uint8_t*>(raw_guard_object
)),
564 init_byte(reinterpret_cast<uint8_t*>(raw_guard_object
) + 1, reinterpret_cast<uint32_t*>(raw_guard_object
) + 1) {
567 /// Implements __cxa_guard_acquire.
568 AcquireResult
cxa_guard_acquire() {
569 // Use short-circuit evaluation to avoid calling init_byte.acquire when
570 // guard_byte.acquire returns true. (i.e. don't call it when we know from
571 // the guard byte that initialization has already been completed)
572 if (guard_byte
.acquire() || init_byte
.acquire())
574 return INIT_IS_PENDING
;
577 /// Implements __cxa_guard_release.
578 void cxa_guard_release() {
579 // Update guard byte first, so if somebody is woken up by init_byte.release
580 // and comes all the way back around to __cxa_guard_acquire again, they see
581 // it as having completed initialization.
582 guard_byte
.release();
586 /// Implements __cxa_guard_abort.
587 void cxa_guard_abort() {
593 //===----------------------------------------------------------------------===//
594 // Convenience Classes
595 //===----------------------------------------------------------------------===//
597 /// NoThreadsGuard - Manages initialization without performing any inter-thread
599 using NoThreadsGuard
= GuardObject
<InitByteNoThreads
>;
601 /// GlobalMutexGuard - Manages initialization using a global mutex and
602 /// condition variable.
603 template <class Mutex
, class CondVar
, Mutex
& global_mutex
, CondVar
& global_cond
,
604 uint32_t (*GetThreadID
)() = PlatformThreadID
>
605 using GlobalMutexGuard
= GuardObject
<InitByteGlobalMutex
<Mutex
, CondVar
, global_mutex
, global_cond
, GetThreadID
>>;
607 /// FutexGuard - Manages initialization using atomics and the futex syscall for
608 /// waiting and waking.
609 template <void (*Wait
)(int*, int) = PlatformFutexWait
, void (*Wake
)(int*) = PlatformFutexWake
,
610 uint32_t (*GetThreadIDArg
)() = PlatformThreadID
>
611 using FutexGuard
= GuardObject
<InitByteFutex
<Wait
, Wake
, GetThreadIDArg
>>;
613 //===----------------------------------------------------------------------===//
615 //===----------------------------------------------------------------------===//
618 struct GlobalStatic
{
622 _LIBCPP_SAFE_STATIC T GlobalStatic
<T
>::instance
= {};
624 enum class Implementation
{ NoThreads
, GlobalMutex
, Futex
};
626 template <Implementation Impl
>
627 struct SelectImplementation
;
630 struct SelectImplementation
<Implementation::NoThreads
> {
631 using type
= NoThreadsGuard
;
635 struct SelectImplementation
<Implementation::GlobalMutex
> {
636 using type
= GlobalMutexGuard
<LibcppMutex
, LibcppCondVar
, GlobalStatic
<LibcppMutex
>::instance
,
637 GlobalStatic
<LibcppCondVar
>::instance
, PlatformThreadID
>;
641 struct SelectImplementation
<Implementation::Futex
> {
642 using type
= FutexGuard
<PlatformFutexWait
, PlatformFutexWake
, PlatformThreadID
>;
645 // TODO(EricWF): We should prefer the futex implementation when available. But
646 // it should be done in a separate step from adding the implementation.
647 constexpr Implementation CurrentImplementation
=
648 #if defined(_LIBCXXABI_HAS_NO_THREADS)
649 Implementation::NoThreads
;
650 #elif defined(_LIBCXXABI_USE_FUTEX)
651 Implementation::Futex
;
653 Implementation::GlobalMutex
;
656 static_assert(CurrentImplementation
!= Implementation::Futex
|| PlatformSupportsFutex(),
657 "Futex selected but not supported");
659 using SelectedImplementation
= SelectImplementation
<CurrentImplementation
>::type
;
662 } // end namespace __cxxabiv1
664 #if defined(__clang__)
665 # pragma clang diagnostic pop
666 #elif defined(__GNUC__)
667 # pragma GCC diagnostic pop
670 #endif // LIBCXXABI_SRC_INCLUDE_CXA_GUARD_IMPL_H