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