atomic_hook.h 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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. #ifndef ABSL_BASE_INTERNAL_ATOMIC_HOOK_H_
  15. #define ABSL_BASE_INTERNAL_ATOMIC_HOOK_H_
  16. #include <atomic>
  17. #include <cassert>
  18. #include <cstdint>
  19. #include <utility>
  20. #include "absl/base/attributes.h"
  21. #include "absl/base/config.h"
  22. #if defined(_MSC_VER) && !defined(__clang__)
  23. #define ABSL_HAVE_WORKING_CONSTEXPR_STATIC_INIT 0
  24. #else
  25. #define ABSL_HAVE_WORKING_CONSTEXPR_STATIC_INIT 1
  26. #endif
  27. #if defined(_MSC_VER)
  28. #define ABSL_HAVE_WORKING_ATOMIC_POINTER 0
  29. #else
  30. #define ABSL_HAVE_WORKING_ATOMIC_POINTER 1
  31. #endif
  32. namespace absl {
  33. ABSL_NAMESPACE_BEGIN
  34. namespace base_internal {
  35. template <typename T>
  36. class AtomicHook;
  37. // To workaround AtomicHook not being constant-initializable on some platforms,
  38. // prefer to annotate instances with `ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES`
  39. // instead of `ABSL_CONST_INIT`.
  40. #if ABSL_HAVE_WORKING_CONSTEXPR_STATIC_INIT
  41. #define ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES ABSL_CONST_INIT
  42. #else
  43. #define ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES
  44. #endif
  45. // `AtomicHook` is a helper class, templatized on a raw function pointer type,
  46. // for implementing Abseil customization hooks. It is a callable object that
  47. // dispatches to the registered hook. Objects of type `AtomicHook` must have
  48. // static or thread storage duration.
  49. //
  50. // A default constructed object performs a no-op (and returns a default
  51. // constructed object) if no hook has been registered.
  52. //
  53. // Hooks can be pre-registered via constant initialization, for example:
  54. //
  55. // ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES static AtomicHook<void(*)()>
  56. // my_hook(DefaultAction);
  57. //
  58. // and then changed at runtime via a call to `Store()`.
  59. //
  60. // Reads and writes guarantee memory_order_acquire/memory_order_release
  61. // semantics.
  62. template <typename ReturnType, typename... Args>
  63. class AtomicHook<ReturnType (*)(Args...)> {
  64. public:
  65. using FnPtr = ReturnType (*)(Args...);
  66. // Constructs an object that by default performs a no-op (and
  67. // returns a default constructed object) when no hook as been registered.
  68. constexpr AtomicHook() : AtomicHook(DummyFunction) {}
  69. // Constructs an object that by default dispatches to/returns the
  70. // pre-registered default_fn when no hook has been registered at runtime.
  71. #if ABSL_HAVE_WORKING_ATOMIC_POINTER && ABSL_HAVE_WORKING_CONSTEXPR_STATIC_INIT
  72. explicit constexpr AtomicHook(FnPtr default_fn)
  73. : hook_(default_fn), default_fn_(default_fn) {}
  74. #elif ABSL_HAVE_WORKING_CONSTEXPR_STATIC_INIT
  75. explicit constexpr AtomicHook(FnPtr default_fn)
  76. : hook_(kUninitialized), default_fn_(default_fn) {}
  77. #else
  78. // As of January 2020, on all known versions of MSVC this constructor runs in
  79. // the global constructor sequence. If `Store()` is called by a dynamic
  80. // initializer, we want to preserve the value, even if this constructor runs
  81. // after the call to `Store()`. If not, `hook_` will be
  82. // zero-initialized by the linker and we have no need to set it.
  83. // https://developercommunity.visualstudio.com/content/problem/336946/class-with-constexpr-constructor-not-using-static.html
  84. explicit constexpr AtomicHook(FnPtr default_fn)
  85. : /* hook_(deliberately omitted), */ default_fn_(default_fn) {
  86. static_assert(kUninitialized == 0, "here we rely on zero-initialization");
  87. }
  88. #endif
  89. // Stores the provided function pointer as the value for this hook.
  90. //
  91. // This is intended to be called once. Multiple calls are legal only if the
  92. // same function pointer is provided for each call. The store is implemented
  93. // as a memory_order_release operation, and read accesses are implemented as
  94. // memory_order_acquire.
  95. void Store(FnPtr fn) {
  96. bool success = DoStore(fn);
  97. static_cast<void>(success);
  98. assert(success);
  99. }
  100. // Invokes the registered callback. If no callback has yet been registered, a
  101. // default-constructed object of the appropriate type is returned instead.
  102. template <typename... CallArgs>
  103. ReturnType operator()(CallArgs&&... args) const {
  104. return DoLoad()(std::forward<CallArgs>(args)...);
  105. }
  106. // Returns the registered callback, or nullptr if none has been registered.
  107. // Useful if client code needs to conditionalize behavior based on whether a
  108. // callback was registered.
  109. //
  110. // Note that atomic_hook.Load()() and atomic_hook() have different semantics:
  111. // operator()() will perform a no-op if no callback was registered, while
  112. // Load()() will dereference a null function pointer. Prefer operator()() to
  113. // Load()() unless you must conditionalize behavior on whether a hook was
  114. // registered.
  115. FnPtr Load() const {
  116. FnPtr ptr = DoLoad();
  117. return (ptr == DummyFunction) ? nullptr : ptr;
  118. }
  119. private:
  120. static ReturnType DummyFunction(Args...) {
  121. return ReturnType();
  122. }
  123. // Current versions of MSVC (as of September 2017) have a broken
  124. // implementation of std::atomic<T*>: Its constructor attempts to do the
  125. // equivalent of a reinterpret_cast in a constexpr context, which is not
  126. // allowed.
  127. //
  128. // This causes an issue when building with LLVM under Windows. To avoid this,
  129. // we use a less-efficient, intptr_t-based implementation on Windows.
  130. #if ABSL_HAVE_WORKING_ATOMIC_POINTER
  131. // Return the stored value, or DummyFunction if no value has been stored.
  132. FnPtr DoLoad() const { return hook_.load(std::memory_order_acquire); }
  133. // Store the given value. Returns false if a different value was already
  134. // stored to this object.
  135. bool DoStore(FnPtr fn) {
  136. assert(fn);
  137. FnPtr expected = default_fn_;
  138. const bool store_succeeded = hook_.compare_exchange_strong(
  139. expected, fn, std::memory_order_acq_rel, std::memory_order_acquire);
  140. const bool same_value_already_stored = (expected == fn);
  141. return store_succeeded || same_value_already_stored;
  142. }
  143. std::atomic<FnPtr> hook_;
  144. #else // !ABSL_HAVE_WORKING_ATOMIC_POINTER
  145. // Use a sentinel value unlikely to be the address of an actual function.
  146. static constexpr intptr_t kUninitialized = 0;
  147. static_assert(sizeof(intptr_t) >= sizeof(FnPtr),
  148. "intptr_t can't contain a function pointer");
  149. FnPtr DoLoad() const {
  150. const intptr_t value = hook_.load(std::memory_order_acquire);
  151. if (value == kUninitialized) {
  152. return default_fn_;
  153. }
  154. return reinterpret_cast<FnPtr>(value);
  155. }
  156. bool DoStore(FnPtr fn) {
  157. assert(fn);
  158. const auto value = reinterpret_cast<intptr_t>(fn);
  159. intptr_t expected = kUninitialized;
  160. const bool store_succeeded = hook_.compare_exchange_strong(
  161. expected, value, std::memory_order_acq_rel, std::memory_order_acquire);
  162. const bool same_value_already_stored = (expected == value);
  163. return store_succeeded || same_value_already_stored;
  164. }
  165. std::atomic<intptr_t> hook_;
  166. #endif
  167. const FnPtr default_fn_;
  168. };
  169. #undef ABSL_HAVE_WORKING_ATOMIC_POINTER
  170. #undef ABSL_HAVE_WORKING_CONSTEXPR_STATIC_INIT
  171. } // namespace base_internal
  172. ABSL_NAMESPACE_END
  173. } // namespace absl
  174. #endif // ABSL_BASE_INTERNAL_ATOMIC_HOOK_H_