]> git.lizzy.rs Git - minetest.git/blob - src/script/cpp_api/s_base.cpp
Use a Lua error handler that calls tostring (#11913)
[minetest.git] / src / script / cpp_api / s_base.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "cpp_api/s_base.h"
21 #include "cpp_api/s_internal.h"
22 #include "cpp_api/s_security.h"
23 #include "lua_api/l_object.h"
24 #include "common/c_converter.h"
25 #include "server/player_sao.h"
26 #include "filesys.h"
27 #include "content/mods.h"
28 #include "porting.h"
29 #include "util/string.h"
30 #include "server.h"
31 #ifndef SERVER
32 #include "client/client.h"
33 #endif
34
35
36 extern "C" {
37 #include "lualib.h"
38 #if USE_LUAJIT
39         #include "luajit.h"
40 #else
41         #include "bit.h"
42 #endif
43 }
44
45 #include <cstdio>
46 #include <cstdarg>
47 #include "script/common/c_content.h"
48 #include <sstream>
49
50
51 class ModNameStorer
52 {
53 private:
54         lua_State *L;
55 public:
56         ModNameStorer(lua_State *L_, const std::string &mod_name):
57                 L(L_)
58         {
59                 // Store current mod name in registry
60                 lua_pushstring(L, mod_name.c_str());
61                 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
62         }
63         ~ModNameStorer()
64         {
65                 // Clear current mod name from registry
66                 lua_pushnil(L);
67                 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
68         }
69 };
70
71
72 /*
73         ScriptApiBase
74 */
75
76 ScriptApiBase::ScriptApiBase(ScriptingType type):
77                 m_type(type)
78 {
79 #ifdef SCRIPTAPI_LOCK_DEBUG
80         m_lock_recursion_count = 0;
81 #endif
82
83         m_luastack = luaL_newstate();
84         FATAL_ERROR_IF(!m_luastack, "luaL_newstate() failed");
85
86         lua_atpanic(m_luastack, &luaPanic);
87
88         if (m_type == ScriptingType::Client)
89                 clientOpenLibs(m_luastack);
90         else
91                 luaL_openlibs(m_luastack);
92
93         // Load bit library
94         lua_pushcfunction(m_luastack, luaopen_bit);
95         lua_pushstring(m_luastack, LUA_BITLIBNAME);
96         lua_call(m_luastack, 1, 0);
97
98         // Make the ScriptApiBase* accessible to ModApiBase
99 #if INDIRECT_SCRIPTAPI_RIDX
100         *(void **)(lua_newuserdata(m_luastack, sizeof(void *))) = this;
101 #else
102         lua_pushlightuserdata(m_luastack, this);
103 #endif
104         lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
105
106         lua_pushcfunction(m_luastack, script_error_handler);
107         lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_ERROR_HANDLER);
108
109         // Add a C++ wrapper function to catch exceptions thrown in Lua -> C++ calls
110 #if USE_LUAJIT
111         lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper);
112         luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
113         lua_pop(m_luastack, 1);
114 #else
115         // (This is a custom API from the bundled Lua.)
116         lua_atccall(m_luastack, script_exception_wrapper);
117 #endif
118
119         // Add basic globals
120
121         // "core" table:
122         lua_newtable(m_luastack);
123         // Populate with some internal functions which will be removed in Lua:
124         lua_pushcfunction(m_luastack, [](lua_State *L) -> int {
125                 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_READ_VECTOR);
126                 return 0;
127         });
128         lua_setfield(m_luastack, -2, "set_read_vector");
129         lua_pushcfunction(m_luastack, [](lua_State *L) -> int {
130                 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_PUSH_VECTOR);
131                 return 0;
132         });
133         lua_setfield(m_luastack, -2, "set_push_vector");
134         lua_pushcfunction(m_luastack, [](lua_State *L) -> int {
135                 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_READ_NODE);
136                 return 0;
137         });
138         lua_setfield(m_luastack, -2, "set_read_node");
139         lua_pushcfunction(m_luastack, [](lua_State *L) -> int {
140                 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_PUSH_NODE);
141                 return 0;
142         });
143         lua_setfield(m_luastack, -2, "set_push_node");
144         // Finally, put the table into the global environment:
145         lua_setglobal(m_luastack, "core");
146
147         if (m_type == ScriptingType::Client)
148                 lua_pushstring(m_luastack, "/");
149         else
150                 lua_pushstring(m_luastack, DIR_DELIM);
151         lua_setglobal(m_luastack, "DIR_DELIM");
152
153         lua_pushstring(m_luastack, porting::getPlatformName());
154         lua_setglobal(m_luastack, "PLATFORM");
155
156         // Make sure Lua uses the right locale
157         setlocale(LC_NUMERIC, "C");
158 }
159
160 ScriptApiBase::~ScriptApiBase()
161 {
162         lua_close(m_luastack);
163 }
164
165 int ScriptApiBase::luaPanic(lua_State *L)
166 {
167         std::ostringstream oss;
168         oss << "LUA PANIC: unprotected error in call to Lua API ("
169                 << readParam<std::string>(L, -1) << ")";
170         FATAL_ERROR(oss.str().c_str());
171         // NOTREACHED
172         return 0;
173 }
174
175 void ScriptApiBase::clientOpenLibs(lua_State *L)
176 {
177         static const std::vector<std::pair<std::string, lua_CFunction>> m_libs = {
178                 { "", luaopen_base },
179                 { LUA_TABLIBNAME,  luaopen_table   },
180                 { LUA_OSLIBNAME,   luaopen_os      },
181                 { LUA_STRLIBNAME,  luaopen_string  },
182                 { LUA_MATHLIBNAME, luaopen_math    },
183                 { LUA_DBLIBNAME,   luaopen_debug   },
184 #if USE_LUAJIT
185                 { LUA_JITLIBNAME,  luaopen_jit     },
186 #endif
187         };
188
189         for (const auto &lib : m_libs) {
190             lua_pushcfunction(L, lib.second);
191             lua_pushstring(L, lib.first.c_str());
192             lua_call(L, 1, 0);
193         }
194 }
195
196 void ScriptApiBase::checkSetByBuiltin()
197 {
198         lua_State *L = getStack();
199
200         if (m_gamedef) {
201                 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_READ_VECTOR);
202                 FATAL_ERROR_IF(lua_type(L, -1) != LUA_TFUNCTION, "missing read_vector");
203                 lua_pop(L, 1);
204
205                 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_PUSH_VECTOR);
206                 FATAL_ERROR_IF(lua_type(L, -1) != LUA_TFUNCTION, "missing push_vector");
207                 lua_pop(L, 1);
208
209                 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_READ_NODE);
210                 FATAL_ERROR_IF(lua_type(L, -1) != LUA_TFUNCTION, "missing read_node");
211                 lua_pop(L, 1);
212
213                 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_PUSH_NODE);
214                 FATAL_ERROR_IF(lua_type(L, -1) != LUA_TFUNCTION, "missing push_node");
215                 lua_pop(L, 1);
216         }
217 }
218
219 void ScriptApiBase::loadMod(const std::string &script_path,
220                 const std::string &mod_name)
221 {
222         ModNameStorer mod_name_storer(getStack(), mod_name);
223
224         loadScript(script_path);
225 }
226
227 void ScriptApiBase::loadScript(const std::string &script_path)
228 {
229         verbosestream << "Loading and running script from " << script_path << std::endl;
230
231         lua_State *L = getStack();
232
233         int error_handler = PUSH_ERROR_HANDLER(L);
234
235         bool ok;
236         if (m_secure) {
237                 ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
238         } else {
239                 ok = !luaL_loadfile(L, script_path.c_str());
240         }
241         ok = ok && !lua_pcall(L, 0, 0, error_handler);
242         if (!ok) {
243                 const char *error_msg = lua_tostring(L, -1);
244                 if (!error_msg)
245                         error_msg = "(error object is not a string)";
246                 lua_pop(L, 2); // Pop error message and error handler
247                 throw ModError("Failed to load and run script from " +
248                                 script_path + ":\n" + error_msg);
249         }
250         lua_pop(L, 1); // Pop error handler
251 }
252
253 #ifndef SERVER
254 void ScriptApiBase::loadModFromMemory(const std::string &mod_name)
255 {
256         ModNameStorer mod_name_storer(getStack(), mod_name);
257
258         sanity_check(m_type == ScriptingType::Client);
259
260         const std::string init_filename = mod_name + ":init.lua";
261         const std::string chunk_name = "@" + init_filename;
262
263         const std::string *contents = getClient()->getModFile(init_filename);
264         if (!contents)
265                 throw ModError("Mod \"" + mod_name + "\" lacks init.lua");
266
267         verbosestream << "Loading and running script " << chunk_name << std::endl;
268
269         lua_State *L = getStack();
270
271         int error_handler = PUSH_ERROR_HANDLER(L);
272
273         bool ok = ScriptApiSecurity::safeLoadString(L, *contents, chunk_name.c_str());
274         if (ok)
275                 ok = !lua_pcall(L, 0, 0, error_handler);
276         if (!ok) {
277                 const char *error_msg = lua_tostring(L, -1);
278                 if (!error_msg)
279                         error_msg = "(error object is not a string)";
280                 lua_pop(L, 2); // Pop error message and error handler
281                 throw ModError("Failed to load and run mod \"" +
282                                 mod_name + "\":\n" + error_msg);
283         }
284         lua_pop(L, 1); // Pop error handler
285 }
286 #endif
287
288 // Push the list of callbacks (a lua table).
289 // Then push nargs arguments.
290 // Then call this function, which
291 // - runs the callbacks
292 // - replaces the table and arguments with the return value,
293 //     computed depending on mode
294 // This function must only be called with scriptlock held (i.e. inside of a
295 // code block with SCRIPTAPI_PRECHECKHEADER declared)
296 void ScriptApiBase::runCallbacksRaw(int nargs,
297                 RunCallbacksMode mode, const char *fxn)
298 {
299 #ifndef SERVER
300         // Hard fail for bad guarded callbacks
301         // Only run callbacks when the scripting enviroment is loaded
302         FATAL_ERROR_IF(m_type == ScriptingType::Client &&
303                         !getClient()->modsLoaded(), fxn);
304 #endif
305
306 #ifdef SCRIPTAPI_LOCK_DEBUG
307         assert(m_lock_recursion_count > 0);
308 #endif
309         lua_State *L = getStack();
310         FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
311
312         // Insert error handler
313         PUSH_ERROR_HANDLER(L);
314         int error_handler = lua_gettop(L) - nargs - 1;
315         lua_insert(L, error_handler);
316
317         // Insert run_callbacks between error handler and table
318         lua_getglobal(L, "core");
319         lua_getfield(L, -1, "run_callbacks");
320         lua_remove(L, -2);
321         lua_insert(L, error_handler + 1);
322
323         // Insert mode after table
324         lua_pushnumber(L, (int)mode);
325         lua_insert(L, error_handler + 3);
326
327         // Stack now looks like this:
328         // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
329
330         int result = lua_pcall(L, nargs + 2, 1, error_handler);
331         if (result != 0)
332                 scriptError(result, fxn);
333
334         lua_remove(L, error_handler);
335 }
336
337 void ScriptApiBase::realityCheck()
338 {
339         int top = lua_gettop(m_luastack);
340         if (top >= 30) {
341                 dstream << "Stack is over 30:" << std::endl;
342                 stackDump(dstream);
343                 std::string traceback = script_get_backtrace(m_luastack);
344                 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
345         }
346 }
347
348 void ScriptApiBase::scriptError(int result, const char *fxn)
349 {
350         script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
351 }
352
353 void ScriptApiBase::stackDump(std::ostream &o)
354 {
355         int top = lua_gettop(m_luastack);
356         for (int i = 1; i <= top; i++) {  /* repeat for each level */
357                 int t = lua_type(m_luastack, i);
358                 switch (t) {
359                         case LUA_TSTRING:  /* strings */
360                                 o << "\"" << readParam<std::string>(m_luastack, i) << "\"";
361                                 break;
362                         case LUA_TBOOLEAN:  /* booleans */
363                                 o << (readParam<bool>(m_luastack, i) ? "true" : "false");
364                                 break;
365                         case LUA_TNUMBER:  /* numbers */ {
366                                 char buf[10];
367                                 porting::mt_snprintf(buf, sizeof(buf), "%lf", lua_tonumber(m_luastack, i));
368                                 o << buf;
369                                 break;
370                         }
371                         default:  /* other values */
372                                 o << lua_typename(m_luastack, t);
373                                 break;
374                 }
375                 o << " ";
376         }
377         o << std::endl;
378 }
379
380 void ScriptApiBase::setOriginDirect(const char *origin)
381 {
382         m_last_run_mod = origin ? origin : "??";
383 }
384
385 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
386 {
387         lua_State *L = getStack();
388         m_last_run_mod = lua_istable(L, index) ?
389                 getstringfield_default(L, index, "mod_origin", "") : "";
390 }
391
392 /*
393  * How ObjectRefs are handled in Lua:
394  * When an active object is created, an ObjectRef is created on the Lua side
395  * and stored in core.object_refs[id].
396  * Methods that require an ObjectRef to a certain object retrieve it from that
397  * table instead of creating their own.(*)
398  * When an active object is removed, the existing ObjectRef is invalidated
399  * using ::set_null() and removed from the core.object_refs table.
400  * (*) An exception to this are NULL ObjectRefs and anonymous ObjectRefs
401  *     for objects without ID.
402  *     It's unclear what the latter are needed for and their use is problematic
403  *     since we lose control over the ref and the contained pointer.
404  */
405
406 void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
407 {
408         SCRIPTAPI_PRECHECKHEADER
409         //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
410
411         // Create object on stack
412         ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
413         int object = lua_gettop(L);
414
415         // Get core.object_refs table
416         lua_getglobal(L, "core");
417         lua_getfield(L, -1, "object_refs");
418         luaL_checktype(L, -1, LUA_TTABLE);
419         int objectstable = lua_gettop(L);
420
421         // object_refs[id] = object
422         lua_pushnumber(L, cobj->getId()); // Push id
423         lua_pushvalue(L, object); // Copy object to top of stack
424         lua_settable(L, objectstable);
425 }
426
427 void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
428 {
429         SCRIPTAPI_PRECHECKHEADER
430         //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
431
432         // Get core.object_refs table
433         lua_getglobal(L, "core");
434         lua_getfield(L, -1, "object_refs");
435         luaL_checktype(L, -1, LUA_TTABLE);
436         int objectstable = lua_gettop(L);
437
438         // Get object_refs[id]
439         lua_pushnumber(L, cobj->getId()); // Push id
440         lua_gettable(L, objectstable);
441         // Set object reference to NULL
442         ObjectRef::set_null(L);
443         lua_pop(L, 1); // pop object
444
445         // Set object_refs[id] = nil
446         lua_pushnumber(L, cobj->getId()); // Push id
447         lua_pushnil(L);
448         lua_settable(L, objectstable);
449 }
450
451 // Creates a new anonymous reference if cobj=NULL or id=0
452 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
453                 ServerActiveObject *cobj)
454 {
455         if (cobj == NULL || cobj->getId() == 0) {
456                 ObjectRef::create(L, cobj);
457         } else {
458                 push_objectRef(L, cobj->getId());
459                 if (cobj->isGone())
460                         warningstream << "ScriptApiBase::objectrefGetOrCreate(): "
461                                         << "Pushing ObjectRef to removed/deactivated object"
462                                         << ", this is probably a bug." << std::endl;
463         }
464 }
465
466 void ScriptApiBase::pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeReason &reason)
467 {
468         if (reason.hasLuaReference())
469                 lua_rawgeti(L, LUA_REGISTRYINDEX, reason.lua_reference);
470         else
471                 lua_newtable(L);
472
473         lua_getfield(L, -1, "type");
474         bool has_type = (bool)lua_isstring(L, -1);
475         lua_pop(L, 1);
476         if (!has_type) {
477                 lua_pushstring(L, reason.getTypeAsString().c_str());
478                 lua_setfield(L, -2, "type");
479         }
480
481         lua_pushstring(L, reason.from_mod ? "mod" : "engine");
482         lua_setfield(L, -2, "from");
483
484         if (reason.object) {
485                 objectrefGetOrCreate(L, reason.object);
486                 lua_setfield(L, -2, "object");
487         }
488         if (!reason.node.empty()) {
489                 lua_pushstring(L, reason.node.c_str());
490                 lua_setfield(L, -2, "node");
491         }
492 }
493
494 Server* ScriptApiBase::getServer()
495 {
496         return dynamic_cast<Server *>(m_gamedef);
497 }
498 #ifndef SERVER
499 Client* ScriptApiBase::getClient()
500 {
501         return dynamic_cast<Client *>(m_gamedef);
502 }
503 #endif