protected_function.hpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. // sol2
  2. // The MIT License (MIT)
  3. // Copyright (c) 2013-2022 Rapptz, ThePhD and contributors
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy of
  5. // this software and associated documentation files (the "Software"), to deal in
  6. // the Software without restriction, including without limitation the rights to
  7. // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  8. // the Software, and to permit persons to whom the Software is furnished to do so,
  9. // subject to the following conditions:
  10. // The above copyright notice and this permission notice shall be included in all
  11. // copies or substantial portions of the Software.
  12. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  14. // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  15. // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  16. // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  17. // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  18. #ifndef SOL_PROTECTED_FUNCTION_HPP
  19. #define SOL_PROTECTED_FUNCTION_HPP
  20. #include <sol/reference.hpp>
  21. #include <sol/object.hpp>
  22. #include <sol/stack.hpp>
  23. #include <sol/protected_function_result.hpp>
  24. #include <sol/unsafe_function.hpp>
  25. #include <sol/protected_handler.hpp>
  26. #include <sol/bytecode.hpp>
  27. #include <sol/dump_handler.hpp>
  28. #include <cstdint>
  29. #include <algorithm>
  30. namespace sol {
  31. namespace detail {
  32. template <bool ShouldPush_, typename Handler_>
  33. inline void handle_protected_exception(
  34. lua_State* L_, optional<const std::exception&> maybe_ex, const char* error, detail::protected_handler<ShouldPush_, Handler_>& handler_) {
  35. handler_.stack_index = 0;
  36. if (ShouldPush_) {
  37. handler_.target.push(L_);
  38. detail::call_exception_handler(L_, maybe_ex, error);
  39. lua_call(L_, 1, 1);
  40. }
  41. else {
  42. detail::call_exception_handler(L_, maybe_ex, error);
  43. }
  44. }
  45. } // namespace detail
  46. template <typename Reference, bool Aligned = false, typename Handler = reference>
  47. class basic_protected_function : public basic_object<Reference> {
  48. private:
  49. using base_t = basic_object<Reference>;
  50. using handler_t = Handler;
  51. inline static constexpr bool is_stack_handler_v = is_stack_based_v<handler_t>;
  52. basic_protected_function(std::true_type, const basic_protected_function& other_) noexcept
  53. : base_t(other_), m_error_handler(other_.m_error_handler.copy(lua_state())) {
  54. }
  55. basic_protected_function(std::false_type, const basic_protected_function& other_) noexcept : base_t(other_), m_error_handler(other_.m_error_handler) {
  56. }
  57. public:
  58. basic_protected_function() = default;
  59. template <typename T,
  60. meta::enable<meta::neg<std::is_same<meta::unqualified_t<T>, basic_protected_function>>,
  61. meta::neg<std::is_base_of<proxy_base_tag, meta::unqualified_t<T>>>, meta::neg<std::is_same<base_t, stack_reference>>,
  62. meta::neg<std::is_same<lua_nil_t, meta::unqualified_t<T>>>, is_lua_reference<meta::unqualified_t<T>>> = meta::enabler>
  63. basic_protected_function(T&& r) noexcept : base_t(std::forward<T>(r)), m_error_handler(get_default_handler(r.lua_state())) {
  64. #if SOL_IS_ON(SOL_SAFE_REFERENCES)
  65. if (!is_function<meta::unqualified_t<T>>::value) {
  66. auto pp = stack::push_pop(*this);
  67. constructor_handler handler {};
  68. stack::check<basic_protected_function>(lua_state(), -1, handler);
  69. }
  70. #endif // Safety
  71. }
  72. basic_protected_function(const basic_protected_function& other_) noexcept
  73. : basic_protected_function(meta::boolean<is_stateless_lua_reference_v<Handler>>(), other_) {
  74. }
  75. basic_protected_function& operator=(const basic_protected_function& other_) {
  76. base_t::operator=(other_);
  77. if constexpr (is_stateless_lua_reference_v<Handler>) {
  78. m_error_handler.copy_assign(lua_state(), other_.m_error_handler);
  79. }
  80. else {
  81. m_error_handler = other_.m_error_handler;
  82. }
  83. return *this;
  84. }
  85. basic_protected_function(basic_protected_function&&) = default;
  86. basic_protected_function& operator=(basic_protected_function&&) = default;
  87. basic_protected_function(const basic_function<base_t>& b) : basic_protected_function(b, get_default_handler(b.lua_state())) {
  88. }
  89. basic_protected_function(basic_function<base_t>&& b) : basic_protected_function(std::move(b), get_default_handler(b.lua_state())) {
  90. }
  91. basic_protected_function(const basic_function<base_t>& b, handler_t eh) : base_t(b), m_error_handler(std::move(eh)) {
  92. }
  93. basic_protected_function(basic_function<base_t>&& b, handler_t eh) : base_t(std::move(b)), m_error_handler(std::move(eh)) {
  94. }
  95. basic_protected_function(const stack_reference& r) : basic_protected_function(r.lua_state(), r.stack_index(), get_default_handler(r.lua_state())) {
  96. }
  97. basic_protected_function(stack_reference&& r) : basic_protected_function(r.lua_state(), r.stack_index(), get_default_handler(r.lua_state())) {
  98. }
  99. basic_protected_function(const stack_reference& r, handler_t eh) : basic_protected_function(r.lua_state(), r.stack_index(), std::move(eh)) {
  100. }
  101. basic_protected_function(stack_reference&& r, handler_t eh) : basic_protected_function(r.lua_state(), r.stack_index(), std::move(eh)) {
  102. }
  103. template <typename Super>
  104. basic_protected_function(const proxy_base<Super>& p) : basic_protected_function(p, get_default_handler(p.lua_state())) {
  105. }
  106. template <typename Super>
  107. basic_protected_function(proxy_base<Super>&& p) : basic_protected_function(std::move(p), get_default_handler(p.lua_state())) {
  108. }
  109. template <typename Proxy, typename HandlerReference,
  110. meta::enable<std::is_base_of<proxy_base_tag, meta::unqualified_t<Proxy>>,
  111. meta::neg<is_lua_index<meta::unqualified_t<HandlerReference>>>> = meta::enabler>
  112. basic_protected_function(Proxy&& p, HandlerReference&& eh)
  113. : basic_protected_function(detail::force_cast<base_t>(p), make_reference<handler_t>(p.lua_state(), std::forward<HandlerReference>(eh))) {
  114. }
  115. template <typename T, meta::enable<is_lua_reference<meta::unqualified_t<T>>> = meta::enabler>
  116. basic_protected_function(lua_State* L_, T&& r) : basic_protected_function(L_, std::forward<T>(r), get_default_handler(L_)) {
  117. }
  118. template <typename T, meta::enable<is_lua_reference<meta::unqualified_t<T>>> = meta::enabler>
  119. basic_protected_function(lua_State* L_, T&& r, handler_t eh) : base_t(L_, std::forward<T>(r)), m_error_handler(std::move(eh)) {
  120. #if SOL_IS_ON(SOL_SAFE_REFERENCES)
  121. auto pp = stack::push_pop(*this);
  122. constructor_handler handler {};
  123. stack::check<basic_protected_function>(lua_state(), -1, handler);
  124. #endif // Safety
  125. }
  126. basic_protected_function(lua_nil_t n) : base_t(n), m_error_handler(n) {
  127. }
  128. basic_protected_function(lua_State* L_, int index_ = -1) : basic_protected_function(L_, index_, get_default_handler(L_)) {
  129. }
  130. basic_protected_function(lua_State* L_, int index_, handler_t eh) : base_t(L_, index_), m_error_handler(std::move(eh)) {
  131. #if SOL_IS_ON(SOL_SAFE_REFERENCES)
  132. constructor_handler handler {};
  133. stack::check<basic_protected_function>(L_, index_, handler);
  134. #endif // Safety
  135. }
  136. basic_protected_function(lua_State* L_, absolute_index index_) : basic_protected_function(L_, index_, get_default_handler(L_)) {
  137. }
  138. basic_protected_function(lua_State* L_, absolute_index index_, handler_t eh) : base_t(L_, index_), m_error_handler(std::move(eh)) {
  139. #if SOL_IS_ON(SOL_SAFE_REFERENCES)
  140. constructor_handler handler {};
  141. stack::check<basic_protected_function>(L_, index_, handler);
  142. #endif // Safety
  143. }
  144. basic_protected_function(lua_State* L_, raw_index index_) : basic_protected_function(L_, index_, get_default_handler(L_)) {
  145. }
  146. basic_protected_function(lua_State* L_, raw_index index_, handler_t eh) : base_t(L_, index_), m_error_handler(std::move(eh)) {
  147. #if SOL_IS_ON(SOL_SAFE_REFERENCES)
  148. constructor_handler handler {};
  149. stack::check<basic_protected_function>(L_, index_, handler);
  150. #endif // Safety
  151. }
  152. basic_protected_function(lua_State* L_, ref_index index_) : basic_protected_function(L_, index_, get_default_handler(L_)) {
  153. }
  154. basic_protected_function(lua_State* L_, ref_index index_, handler_t eh) : base_t(L_, index_), m_error_handler(std::move(eh)) {
  155. #if SOL_IS_ON(SOL_SAFE_REFERENCES)
  156. auto pp = stack::push_pop(*this);
  157. constructor_handler handler {};
  158. stack::check<basic_protected_function>(lua_state(), -1, handler);
  159. #endif // Safety
  160. }
  161. using base_t::lua_state;
  162. template <typename Fx>
  163. int dump(lua_Writer writer, void* userdata_pointer_, bool strip, Fx&& on_error) const {
  164. this->push();
  165. auto ppn = stack::push_popper_n<false>(this->lua_state(), 1);
  166. int r = lua_dump(this->lua_state(), writer, userdata_pointer_, strip ? 1 : 0);
  167. if (r != 0) {
  168. return on_error(this->lua_state(), r, writer, userdata_pointer_, strip);
  169. }
  170. return r;
  171. }
  172. int dump(lua_Writer writer, void* userdata_pointer_, bool strip = false) const {
  173. return dump(writer, userdata_pointer_, strip, &dump_pass_on_error);
  174. }
  175. template <typename Container = bytecode>
  176. Container dump() const {
  177. Container bc;
  178. (void)dump(static_cast<lua_Writer>(&basic_insert_dump_writer<Container>), static_cast<void*>(&bc), false, &dump_throw_on_error);
  179. return bc;
  180. }
  181. template <typename Container = bytecode, typename Fx>
  182. Container dump(Fx&& on_error) const {
  183. Container bc;
  184. (void)dump(static_cast<lua_Writer>(&basic_insert_dump_writer<Container>), static_cast<void*>(&bc), false, std::forward<Fx>(on_error));
  185. return bc;
  186. }
  187. template <typename... Args>
  188. protected_function_result operator()(Args&&... args) const {
  189. return call<>(std::forward<Args>(args)...);
  190. }
  191. template <typename... Ret, typename... Args>
  192. decltype(auto) operator()(types<Ret...>, Args&&... args) const {
  193. return call<Ret...>(std::forward<Args>(args)...);
  194. }
  195. template <typename... Ret, typename... Args>
  196. decltype(auto) call(Args&&... args) const {
  197. if constexpr (!Aligned) {
  198. // we do not expect the function to already be on the stack: push it
  199. if (m_error_handler.valid(lua_state())) {
  200. detail::protected_handler<true, handler_t> h(lua_state(), m_error_handler);
  201. base_t::push();
  202. int pushcount = stack::multi_push_reference(lua_state(), std::forward<Args>(args)...);
  203. return invoke(types<Ret...>(), std::make_index_sequence<sizeof...(Ret)>(), pushcount, h);
  204. }
  205. else {
  206. detail::protected_handler<false, handler_t> h(lua_state(), m_error_handler);
  207. base_t::push();
  208. int pushcount = stack::multi_push_reference(lua_state(), std::forward<Args>(args)...);
  209. return invoke(types<Ret...>(), std::make_index_sequence<sizeof...(Ret)>(), pushcount, h);
  210. }
  211. }
  212. else {
  213. // the function is already on the stack at the right location
  214. if (m_error_handler.valid()) {
  215. // the handler will be pushed onto the stack manually,
  216. // since it's not already on the stack this means we need to push our own
  217. // function on the stack too and swap things to be in-place
  218. if constexpr (!is_stack_handler_v) {
  219. // so, we need to remove the function at the top and then dump the handler out ourselves
  220. base_t::push();
  221. }
  222. detail::protected_handler<true, handler_t> h(lua_state(), m_error_handler);
  223. if constexpr (!is_stack_handler_v) {
  224. lua_replace(lua_state(), -3);
  225. h.stack_index = lua_absindex(lua_state(), -2);
  226. }
  227. int pushcount = stack::multi_push_reference(lua_state(), std::forward<Args>(args)...);
  228. return invoke(types<Ret...>(), std::make_index_sequence<sizeof...(Ret)>(), pushcount, h);
  229. }
  230. else {
  231. detail::protected_handler<false, handler_t> h(lua_state(), m_error_handler);
  232. int pushcount = stack::multi_push_reference(lua_state(), std::forward<Args>(args)...);
  233. return invoke(types<Ret...>(), std::make_index_sequence<sizeof...(Ret)>(), pushcount, h);
  234. }
  235. }
  236. }
  237. ~basic_protected_function() {
  238. if constexpr (is_stateless_lua_reference_v<handler_t>) {
  239. this->m_error_handler.reset(lua_state());
  240. }
  241. }
  242. static handler_t get_default_handler(lua_State* L_) {
  243. return detail::get_default_handler<handler_t, is_main_threaded_v<base_t>>(L_);
  244. }
  245. template <typename T>
  246. static void set_default_handler(const T& ref) {
  247. detail::set_default_handler(ref.lua_state(), ref);
  248. }
  249. auto get_error_handler() const noexcept {
  250. if constexpr (is_stateless_lua_reference_v<handler_t>) {
  251. if constexpr (is_stack_based_v<handler_t>) {
  252. return stack_reference(lua_state(), m_error_handler.stack_index());
  253. }
  254. else {
  255. return basic_reference<is_main_threaded_v<base_t>>(lua_state(), ref_index(m_error_handler.registry_index()));
  256. }
  257. }
  258. else {
  259. return m_error_handler;
  260. }
  261. }
  262. template <typename ErrorHandler_>
  263. void set_error_handler(ErrorHandler_&& error_handler_) noexcept {
  264. static_assert(!is_stack_based_v<handler_t> || is_stack_based_v<ErrorHandler_>,
  265. "A stack-based error handler can only be set from a parameter that is also stack-based.");
  266. if constexpr (std::is_rvalue_reference_v<ErrorHandler_>) {
  267. m_error_handler = std::forward<ErrorHandler_>(error_handler_);
  268. }
  269. else {
  270. m_error_handler.copy_assign(lua_state(), std::forward<ErrorHandler_>(error_handler_));
  271. }
  272. }
  273. void abandon () noexcept {
  274. this->m_error_handler.abandon();
  275. base_t::abandon();
  276. }
  277. private:
  278. handler_t m_error_handler;
  279. template <bool b>
  280. call_status luacall(std::ptrdiff_t argcount, std::ptrdiff_t result_count_, detail::protected_handler<b, handler_t>& h) const {
  281. return static_cast<call_status>(lua_pcall(lua_state(), static_cast<int>(argcount), static_cast<int>(result_count_), h.stack_index));
  282. }
  283. template <std::size_t... I, bool b, typename... Ret>
  284. auto invoke(types<Ret...>, std::index_sequence<I...>, std::ptrdiff_t n, detail::protected_handler<b, handler_t>& h) const {
  285. luacall(n, sizeof...(Ret), h);
  286. return stack::pop<std::tuple<Ret...>>(lua_state());
  287. }
  288. template <std::size_t I, bool b, typename Ret>
  289. Ret invoke(types<Ret>, std::index_sequence<I>, std::ptrdiff_t n, detail::protected_handler<b, handler_t>& h) const {
  290. luacall(n, 1, h);
  291. return stack::pop<Ret>(lua_state());
  292. }
  293. template <std::size_t I, bool b>
  294. void invoke(types<void>, std::index_sequence<I>, std::ptrdiff_t n, detail::protected_handler<b, handler_t>& h) const {
  295. luacall(n, 0, h);
  296. }
  297. template <bool b>
  298. protected_function_result invoke(types<>, std::index_sequence<>, std::ptrdiff_t n, detail::protected_handler<b, handler_t>& h) const {
  299. int stacksize = lua_gettop(lua_state());
  300. int poststacksize = stacksize;
  301. int firstreturn = 1;
  302. int returncount = 0;
  303. call_status code = call_status::ok;
  304. #if SOL_IS_ON(SOL_EXCEPTIONS) && SOL_IS_OFF(SOL_PROPAGATE_EXCEPTIONS)
  305. try {
  306. #endif // No Exceptions
  307. firstreturn = (std::max)(1, static_cast<int>(stacksize - n - static_cast<int>(h.valid() && !is_stack_handler_v)));
  308. code = luacall(n, LUA_MULTRET, h);
  309. poststacksize = lua_gettop(lua_state()) - static_cast<int>(h.valid() && !is_stack_handler_v);
  310. returncount = poststacksize - (firstreturn - 1);
  311. #if SOL_IS_ON(SOL_EXCEPTIONS) && SOL_IS_OFF(SOL_PROPAGATE_EXCEPTIONS)
  312. }
  313. // Handle C++ errors thrown from C++ functions bound inside of lua
  314. catch (const char* error) {
  315. detail::handle_protected_exception(lua_state(), optional<const std::exception&>(nullopt), error, h);
  316. firstreturn = lua_gettop(lua_state());
  317. return protected_function_result(lua_state(), firstreturn, 0, 1, call_status::runtime);
  318. }
  319. catch (const std::string& error) {
  320. detail::handle_protected_exception(lua_state(), optional<const std::exception&>(nullopt), error.c_str(), h);
  321. firstreturn = lua_gettop(lua_state());
  322. return protected_function_result(lua_state(), firstreturn, 0, 1, call_status::runtime);
  323. }
  324. catch (const std::exception& error) {
  325. detail::handle_protected_exception(lua_state(), optional<const std::exception&>(error), error.what(), h);
  326. firstreturn = lua_gettop(lua_state());
  327. return protected_function_result(lua_state(), firstreturn, 0, 1, call_status::runtime);
  328. }
  329. #if SOL_IS_ON(SOL_EXCEPTIONS_CATCH_ALL)
  330. // LuaJIT cannot have the catchall when the safe propagation is on
  331. // but LuaJIT will swallow all C++ errors
  332. // if we don't at least catch std::exception ones
  333. catch (...) {
  334. detail::handle_protected_exception(lua_state(), optional<const std::exception&>(nullopt), detail::protected_function_error, h);
  335. firstreturn = lua_gettop(lua_state());
  336. return protected_function_result(lua_state(), firstreturn, 0, 1, call_status::runtime);
  337. }
  338. #endif // Always catch edge case
  339. #else
  340. // do not handle exceptions: they can be propogated into C++ and keep all type information / rich information
  341. #endif // Exceptions vs. No Exceptions
  342. return protected_function_result(lua_state(), firstreturn, returncount, returncount, code);
  343. }
  344. };
  345. } // namespace sol
  346. #endif // SOL_FUNCTION_HPP