You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

atomic_hook.h 9.0 kB

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