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