SafeFunction.h 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. /*
  2. * Copyright (c) 2016 Apple Inc. All rights reserved.
  3. * Copyright (c) 2021, Gunnar Beutner <gbeutner@serenityos.org>
  4. * Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #pragma once
  9. #include <AK/Function.h>
  10. namespace JS {
  11. void register_safe_function_closure(void*, size_t);
  12. void unregister_safe_function_closure(void*, size_t);
  13. template<typename>
  14. class SafeFunction;
  15. template<typename Out, typename... In>
  16. class SafeFunction<Out(In...)> {
  17. AK_MAKE_NONCOPYABLE(SafeFunction);
  18. public:
  19. SafeFunction() = default;
  20. SafeFunction(std::nullptr_t)
  21. {
  22. }
  23. ~SafeFunction()
  24. {
  25. clear(false);
  26. }
  27. void register_closure()
  28. {
  29. if (auto* wrapper = callable_wrapper())
  30. register_safe_function_closure(wrapper, m_size);
  31. }
  32. void unregister_closure()
  33. {
  34. if (auto* wrapper = callable_wrapper())
  35. unregister_safe_function_closure(wrapper, m_size);
  36. }
  37. template<typename CallableType>
  38. SafeFunction(CallableType&& callable) requires((AK::IsFunctionObject<CallableType> && IsCallableWithArguments<CallableType, In...> && !IsSame<RemoveCVReference<CallableType>, SafeFunction>))
  39. {
  40. init_with_callable(forward<CallableType>(callable));
  41. }
  42. template<typename FunctionType>
  43. SafeFunction(FunctionType f) requires((AK::IsFunctionPointer<FunctionType> && IsCallableWithArguments<RemovePointer<FunctionType>, In...> && !IsSame<RemoveCVReference<FunctionType>, SafeFunction>))
  44. {
  45. init_with_callable(move(f));
  46. }
  47. SafeFunction(SafeFunction&& other)
  48. {
  49. move_from(move(other));
  50. }
  51. // Note: Despite this method being const, a mutable lambda _may_ modify its own captures.
  52. Out operator()(In... in) const
  53. {
  54. auto* wrapper = callable_wrapper();
  55. VERIFY(wrapper);
  56. ++m_call_nesting_level;
  57. ScopeGuard guard([this] {
  58. if (--m_call_nesting_level == 0 && m_deferred_clear)
  59. const_cast<SafeFunction*>(this)->clear(false);
  60. });
  61. return wrapper->call(forward<In>(in)...);
  62. }
  63. explicit operator bool() const { return !!callable_wrapper(); }
  64. template<typename CallableType>
  65. SafeFunction& operator=(CallableType&& callable) requires((AK::IsFunctionObject<CallableType> && IsCallableWithArguments<CallableType, In...>))
  66. {
  67. clear();
  68. init_with_callable(forward<CallableType>(callable));
  69. return *this;
  70. }
  71. template<typename FunctionType>
  72. SafeFunction& operator=(FunctionType f) requires((AK::IsFunctionPointer<FunctionType> && IsCallableWithArguments<RemovePointer<FunctionType>, In...>))
  73. {
  74. clear();
  75. if (f)
  76. init_with_callable(move(f));
  77. return *this;
  78. }
  79. SafeFunction& operator=(std::nullptr_t)
  80. {
  81. clear();
  82. return *this;
  83. }
  84. SafeFunction& operator=(SafeFunction&& other)
  85. {
  86. if (this != &other) {
  87. clear();
  88. move_from(move(other));
  89. }
  90. return *this;
  91. }
  92. private:
  93. class CallableWrapperBase {
  94. public:
  95. virtual ~CallableWrapperBase() = default;
  96. // Note: This is not const to allow storing mutable lambdas.
  97. virtual Out call(In...) = 0;
  98. virtual void destroy() = 0;
  99. virtual void init_and_swap(u8*, size_t) = 0;
  100. };
  101. template<typename CallableType>
  102. class CallableWrapper final : public CallableWrapperBase {
  103. AK_MAKE_NONMOVABLE(CallableWrapper);
  104. AK_MAKE_NONCOPYABLE(CallableWrapper);
  105. public:
  106. explicit CallableWrapper(CallableType&& callable)
  107. : m_callable(move(callable))
  108. {
  109. }
  110. Out call(In... in) final override
  111. {
  112. return m_callable(forward<In>(in)...);
  113. }
  114. void destroy() final override
  115. {
  116. delete this;
  117. }
  118. // NOLINTNEXTLINE(readability-non-const-parameter) False positive; destination is used in a placement new expression
  119. void init_and_swap(u8* destination, size_t size) final override
  120. {
  121. VERIFY(size >= sizeof(CallableWrapper));
  122. new (destination) CallableWrapper { move(m_callable) };
  123. }
  124. private:
  125. CallableType m_callable;
  126. };
  127. enum class FunctionKind {
  128. NullPointer,
  129. Inline,
  130. Outline,
  131. };
  132. CallableWrapperBase* callable_wrapper() const
  133. {
  134. switch (m_kind) {
  135. case FunctionKind::NullPointer:
  136. return nullptr;
  137. case FunctionKind::Inline:
  138. return bit_cast<CallableWrapperBase*>(&m_storage);
  139. case FunctionKind::Outline:
  140. return *bit_cast<CallableWrapperBase**>(&m_storage);
  141. default:
  142. VERIFY_NOT_REACHED();
  143. }
  144. }
  145. void clear(bool may_defer = true)
  146. {
  147. bool called_from_inside_function = m_call_nesting_level > 0;
  148. // NOTE: This VERIFY could fail because a Function is destroyed from within itself.
  149. VERIFY(may_defer || !called_from_inside_function);
  150. if (called_from_inside_function && may_defer) {
  151. m_deferred_clear = true;
  152. return;
  153. }
  154. m_deferred_clear = false;
  155. auto* wrapper = callable_wrapper();
  156. if (m_kind == FunctionKind::Inline) {
  157. VERIFY(wrapper);
  158. wrapper->~CallableWrapperBase();
  159. unregister_closure();
  160. } else if (m_kind == FunctionKind::Outline) {
  161. VERIFY(wrapper);
  162. wrapper->destroy();
  163. unregister_closure();
  164. }
  165. m_kind = FunctionKind::NullPointer;
  166. }
  167. template<typename Callable>
  168. void init_with_callable(Callable&& callable)
  169. {
  170. VERIFY(m_call_nesting_level == 0);
  171. VERIFY(m_kind == FunctionKind::NullPointer);
  172. using WrapperType = CallableWrapper<Callable>;
  173. if constexpr (sizeof(WrapperType) > inline_capacity) {
  174. *bit_cast<CallableWrapperBase**>(&m_storage) = new WrapperType(forward<Callable>(callable));
  175. m_kind = FunctionKind::Outline;
  176. } else {
  177. new (m_storage) WrapperType(forward<Callable>(callable));
  178. m_kind = FunctionKind::Inline;
  179. }
  180. m_size = sizeof(WrapperType);
  181. register_closure();
  182. }
  183. void move_from(SafeFunction&& other)
  184. {
  185. VERIFY(m_call_nesting_level == 0);
  186. VERIFY(other.m_call_nesting_level == 0);
  187. VERIFY(m_kind == FunctionKind::NullPointer);
  188. auto* other_wrapper = other.callable_wrapper();
  189. m_size = other.m_size;
  190. switch (other.m_kind) {
  191. case FunctionKind::NullPointer:
  192. break;
  193. case FunctionKind::Inline:
  194. other.unregister_closure();
  195. other_wrapper->init_and_swap(m_storage, inline_capacity);
  196. m_kind = FunctionKind::Inline;
  197. register_closure();
  198. break;
  199. case FunctionKind::Outline:
  200. *bit_cast<CallableWrapperBase**>(&m_storage) = other_wrapper;
  201. m_kind = FunctionKind::Outline;
  202. break;
  203. default:
  204. VERIFY_NOT_REACHED();
  205. }
  206. other.m_kind = FunctionKind::NullPointer;
  207. }
  208. FunctionKind m_kind { FunctionKind::NullPointer };
  209. bool m_deferred_clear { false };
  210. mutable Atomic<u16> m_call_nesting_level { 0 };
  211. size_t m_size { 0 };
  212. // Empirically determined to fit most lambdas and functions.
  213. static constexpr size_t inline_capacity = 4 * sizeof(void*);
  214. alignas(max(alignof(CallableWrapperBase), alignof(CallableWrapperBase*))) u8 m_storage[inline_capacity];
  215. };
  216. }