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