]> git.lizzy.rs Git - dragonfireclient.git/blob - src/script/cpp_api/s_base.cpp
DevTest: Fix broken PNG textures
[dragonfireclient.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         // Add and save an error handler
107         lua_getglobal(m_luastack, "debug");
108         lua_getfield(m_luastack, -1, "traceback");
109         lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_BACKTRACE);
110         lua_pop(m_luastack, 1); // pop debug
111
112         // If we are using LuaJIT add a C++ wrapper function to catch
113         // exceptions thrown in Lua -> C++ calls
114 #if USE_LUAJIT
115         lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper);
116         luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
117         lua_pop(m_luastack, 1);
118 #endif
119
120         // Add basic globals
121         lua_newtable(m_luastack);
122         lua_setglobal(m_luastack, "core");
123
124         // vector.metatable is stored in the registry for quick access from C++.
125         lua_newtable(m_luastack);
126         lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_VECTOR_METATABLE);
127         lua_newtable(m_luastack);
128         lua_rawgeti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_VECTOR_METATABLE);
129         lua_setfield(m_luastack, -2, "metatable");
130         lua_setglobal(m_luastack, "vector");
131
132         if (m_type == ScriptingType::Client)
133                 lua_pushstring(m_luastack, "/");
134         else
135                 lua_pushstring(m_luastack, DIR_DELIM);
136         lua_setglobal(m_luastack, "DIR_DELIM");
137
138         lua_pushstring(m_luastack, porting::getPlatformName());
139         lua_setglobal(m_luastack, "PLATFORM");
140
141         // Make sure Lua uses the right locale
142         setlocale(LC_NUMERIC, "C");
143 }
144
145 ScriptApiBase::~ScriptApiBase()
146 {
147         lua_close(m_luastack);
148 }
149
150 int ScriptApiBase::luaPanic(lua_State *L)
151 {
152         std::ostringstream oss;
153         oss << "LUA PANIC: unprotected error in call to Lua API ("
154                 << readParam<std::string>(L, -1) << ")";
155         FATAL_ERROR(oss.str().c_str());
156         // NOTREACHED
157         return 0;
158 }
159
160 void ScriptApiBase::clientOpenLibs(lua_State *L)
161 {
162         static const std::vector<std::pair<std::string, lua_CFunction>> m_libs = {
163                 { "", luaopen_base },
164                 { LUA_TABLIBNAME,  luaopen_table   },
165                 { LUA_OSLIBNAME,   luaopen_os      },
166                 { LUA_STRLIBNAME,  luaopen_string  },
167                 { LUA_MATHLIBNAME, luaopen_math    },
168                 { LUA_DBLIBNAME,   luaopen_debug   },
169 #if USE_LUAJIT
170                 { LUA_JITLIBNAME,  luaopen_jit     },
171 #endif
172         };
173
174         for (const std::pair<std::string, lua_CFunction> &lib : m_libs) {
175             lua_pushcfunction(L, lib.second);
176             lua_pushstring(L, lib.first.c_str());
177             lua_call(L, 1, 0);
178         }
179 }
180
181 void ScriptApiBase::loadMod(const std::string &script_path,
182                 const std::string &mod_name)
183 {
184         ModNameStorer mod_name_storer(getStack(), mod_name);
185
186         loadScript(script_path);
187 }
188
189 void ScriptApiBase::loadScript(const std::string &script_path)
190 {
191         verbosestream << "Loading and running script from " << script_path << std::endl;
192
193         lua_State *L = getStack();
194
195         int error_handler = PUSH_ERROR_HANDLER(L);
196
197         bool ok;
198         if (m_secure) {
199                 ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
200         } else {
201                 ok = !luaL_loadfile(L, script_path.c_str());
202         }
203         ok = ok && !lua_pcall(L, 0, 0, error_handler);
204         if (!ok) {
205                 const char *error_msg = lua_tostring(L, -1);
206                 if (!error_msg)
207                         error_msg = "(error object is not a string)";
208                 lua_pop(L, 2); // Pop error message and error handler
209                 throw ModError("Failed to load and run script from " +
210                                 script_path + ":\n" + error_msg);
211         }
212         lua_pop(L, 1); // Pop error handler
213 }
214
215 #ifndef SERVER
216 void ScriptApiBase::loadModFromMemory(const std::string &mod_name)
217 {
218         ModNameStorer mod_name_storer(getStack(), mod_name);
219
220         sanity_check(m_type == ScriptingType::Client);
221
222         const std::string init_filename = mod_name + ":init.lua";
223         const std::string chunk_name = "@" + init_filename;
224
225         const std::string *contents = getClient()->getModFile(init_filename);
226         if (!contents)
227                 throw ModError("Mod \"" + mod_name + "\" lacks init.lua");
228
229         verbosestream << "Loading and running script " << chunk_name << std::endl;
230
231         lua_State *L = getStack();
232
233         int error_handler = PUSH_ERROR_HANDLER(L);
234
235         bool ok = ScriptApiSecurity::safeLoadString(L, *contents, chunk_name.c_str());
236         if (ok)
237                 ok = !lua_pcall(L, 0, 0, error_handler);
238         if (!ok) {
239                 const char *error_msg = lua_tostring(L, -1);
240                 if (!error_msg)
241                         error_msg = "(error object is not a string)";
242                 lua_pop(L, 2); // Pop error message and error handler
243                 throw ModError("Failed to load and run mod \"" +
244                                 mod_name + "\":\n" + error_msg);
245         }
246         lua_pop(L, 1); // Pop error handler
247 }
248 #endif
249
250 // Push the list of callbacks (a lua table).
251 // Then push nargs arguments.
252 // Then call this function, which
253 // - runs the callbacks
254 // - replaces the table and arguments with the return value,
255 //     computed depending on mode
256 // This function must only be called with scriptlock held (i.e. inside of a
257 // code block with SCRIPTAPI_PRECHECKHEADER declared)
258 void ScriptApiBase::runCallbacksRaw(int nargs,
259                 RunCallbacksMode mode, const char *fxn)
260 {
261 #ifndef SERVER
262         // Hard fail for bad guarded callbacks
263         // Only run callbacks when the scripting enviroment is loaded
264         FATAL_ERROR_IF(m_type == ScriptingType::Client &&
265                         !getClient()->modsLoaded(), fxn);
266 #endif
267
268 #ifdef SCRIPTAPI_LOCK_DEBUG
269         assert(m_lock_recursion_count > 0);
270 #endif
271         lua_State *L = getStack();
272         FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
273
274         // Insert error handler
275         PUSH_ERROR_HANDLER(L);
276         int error_handler = lua_gettop(L) - nargs - 1;
277         lua_insert(L, error_handler);
278
279         // Insert run_callbacks between error handler and table
280         lua_getglobal(L, "core");
281         lua_getfield(L, -1, "run_callbacks");
282         lua_remove(L, -2);
283         lua_insert(L, error_handler + 1);
284
285         // Insert mode after table
286         lua_pushnumber(L, (int)mode);
287         lua_insert(L, error_handler + 3);
288
289         // Stack now looks like this:
290         // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
291
292         int result = lua_pcall(L, nargs + 2, 1, error_handler);
293         if (result != 0)
294                 scriptError(result, fxn);
295
296         lua_remove(L, error_handler);
297 }
298
299 void ScriptApiBase::realityCheck()
300 {
301         int top = lua_gettop(m_luastack);
302         if (top >= 30) {
303                 dstream << "Stack is over 30:" << std::endl;
304                 stackDump(dstream);
305                 std::string traceback = script_get_backtrace(m_luastack);
306                 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
307         }
308 }
309
310 void ScriptApiBase::scriptError(int result, const char *fxn)
311 {
312         script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
313 }
314
315 void ScriptApiBase::stackDump(std::ostream &o)
316 {
317         int top = lua_gettop(m_luastack);
318         for (int i = 1; i <= top; i++) {  /* repeat for each level */
319                 int t = lua_type(m_luastack, i);
320                 switch (t) {
321                         case LUA_TSTRING:  /* strings */
322                                 o << "\"" << readParam<std::string>(m_luastack, i) << "\"";
323                                 break;
324                         case LUA_TBOOLEAN:  /* booleans */
325                                 o << (readParam<bool>(m_luastack, i) ? "true" : "false");
326                                 break;
327                         case LUA_TNUMBER:  /* numbers */ {
328                                 char buf[10];
329                                 porting::mt_snprintf(buf, sizeof(buf), "%lf", lua_tonumber(m_luastack, i));
330                                 o << buf;
331                                 break;
332                         }
333                         default:  /* other values */
334                                 o << lua_typename(m_luastack, t);
335                                 break;
336                 }
337                 o << " ";
338         }
339         o << std::endl;
340 }
341
342 void ScriptApiBase::setOriginDirect(const char *origin)
343 {
344         m_last_run_mod = origin ? origin : "??";
345 }
346
347 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
348 {
349         lua_State *L = getStack();
350         m_last_run_mod = lua_istable(L, index) ?
351                 getstringfield_default(L, index, "mod_origin", "") : "";
352 }
353
354 /*
355  * How ObjectRefs are handled in Lua:
356  * When an active object is created, an ObjectRef is created on the Lua side
357  * and stored in core.object_refs[id].
358  * Methods that require an ObjectRef to a certain object retrieve it from that
359  * table instead of creating their own.(*)
360  * When an active object is removed, the existing ObjectRef is invalidated
361  * using ::set_null() and removed from the core.object_refs table.
362  * (*) An exception to this are NULL ObjectRefs and anonymous ObjectRefs
363  *     for objects without ID.
364  *     It's unclear what the latter are needed for and their use is problematic
365  *     since we lose control over the ref and the contained pointer.
366  */
367
368 void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
369 {
370         SCRIPTAPI_PRECHECKHEADER
371         //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
372
373         // Create object on stack
374         ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
375         int object = lua_gettop(L);
376
377         // Get core.object_refs table
378         lua_getglobal(L, "core");
379         lua_getfield(L, -1, "object_refs");
380         luaL_checktype(L, -1, LUA_TTABLE);
381         int objectstable = lua_gettop(L);
382
383         // object_refs[id] = object
384         lua_pushnumber(L, cobj->getId()); // Push id
385         lua_pushvalue(L, object); // Copy object to top of stack
386         lua_settable(L, objectstable);
387 }
388
389 void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
390 {
391         SCRIPTAPI_PRECHECKHEADER
392         //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
393
394         // Get core.object_refs table
395         lua_getglobal(L, "core");
396         lua_getfield(L, -1, "object_refs");
397         luaL_checktype(L, -1, LUA_TTABLE);
398         int objectstable = lua_gettop(L);
399
400         // Get object_refs[id]
401         lua_pushnumber(L, cobj->getId()); // Push id
402         lua_gettable(L, objectstable);
403         // Set object reference to NULL
404         ObjectRef::set_null(L);
405         lua_pop(L, 1); // pop object
406
407         // Set object_refs[id] = nil
408         lua_pushnumber(L, cobj->getId()); // Push id
409         lua_pushnil(L);
410         lua_settable(L, objectstable);
411 }
412
413 // Creates a new anonymous reference if cobj=NULL or id=0
414 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
415                 ServerActiveObject *cobj)
416 {
417         if (cobj == NULL || cobj->getId() == 0) {
418                 ObjectRef::create(L, cobj);
419         } else {
420                 push_objectRef(L, cobj->getId());
421                 if (cobj->isGone())
422                         warningstream << "ScriptApiBase::objectrefGetOrCreate(): "
423                                         << "Pushing ObjectRef to removed/deactivated object"
424                                         << ", this is probably a bug." << std::endl;
425         }
426 }
427
428 void ScriptApiBase::pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeReason &reason)
429 {
430         if (reason.hasLuaReference())
431                 lua_rawgeti(L, LUA_REGISTRYINDEX, reason.lua_reference);
432         else
433                 lua_newtable(L);
434
435         lua_getfield(L, -1, "type");
436         bool has_type = (bool)lua_isstring(L, -1);
437         lua_pop(L, 1);
438         if (!has_type) {
439                 lua_pushstring(L, reason.getTypeAsString().c_str());
440                 lua_setfield(L, -2, "type");
441         }
442
443         lua_pushstring(L, reason.from_mod ? "mod" : "engine");
444         lua_setfield(L, -2, "from");
445
446         if (reason.object) {
447                 objectrefGetOrCreate(L, reason.object);
448                 lua_setfield(L, -2, "object");
449         }
450         if (!reason.node.empty()) {
451                 lua_pushstring(L, reason.node.c_str());
452                 lua_setfield(L, -2, "node");
453         }
454 }
455
456 Server* ScriptApiBase::getServer()
457 {
458         return dynamic_cast<Server *>(m_gamedef);
459 }
460 #ifndef SERVER
461 Client* ScriptApiBase::getClient()
462 {
463         return dynamic_cast<Client *>(m_gamedef);
464 }
465 #endif