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