]> git.lizzy.rs Git - minetest.git/blob - src/script/cpp_api/s_base.cpp
[CSM] Don't Load the package library (#6944)
[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 "serverobject.h"
26 #include "filesys.h"
27 #include "mods.h"
28 #include "porting.h"
29 #include "util/string.h"
30 #include "server.h"
31 #ifndef SERVER
32 #include "client.h"
33 #endif
34
35
36 extern "C" {
37 #include "lualib.h"
38 #if USE_LUAJIT
39         #include "luajit.h"
40 #endif
41 }
42
43 #include <cstdio>
44 #include <cstdarg>
45 #include "script/common/c_content.h"
46 #include <sstream>
47
48
49 class ModNameStorer
50 {
51 private:
52         lua_State *L;
53 public:
54         ModNameStorer(lua_State *L_, const std::string &mod_name):
55                 L(L_)
56         {
57                 // Store current mod name in registry
58                 lua_pushstring(L, mod_name.c_str());
59                 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
60         }
61         ~ModNameStorer()
62         {
63                 // Clear current mod name from registry
64                 lua_pushnil(L);
65                 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
66         }
67 };
68
69
70 /*
71         ScriptApiBase
72 */
73
74 ScriptApiBase::ScriptApiBase(ScriptingType type):
75                 m_type(type)
76 {
77 #ifdef SCRIPTAPI_LOCK_DEBUG
78         m_lock_recursion_count = 0;
79 #endif
80
81         m_luastack = luaL_newstate();
82         FATAL_ERROR_IF(!m_luastack, "luaL_newstate() failed");
83
84         lua_atpanic(m_luastack, &luaPanic);
85
86         if (m_type == ScriptingType::Client)
87                 clientOpenLibs(m_luastack);
88         else
89                 luaL_openlibs(m_luastack);
90
91         // Make the ScriptApiBase* accessible to ModApiBase
92         lua_pushlightuserdata(m_luastack, this);
93         lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
94
95         // Add and save an error handler
96         lua_getglobal(m_luastack, "debug");
97         lua_getfield(m_luastack, -1, "traceback");
98         lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_BACKTRACE);
99         lua_pop(m_luastack, 1); // pop debug
100
101         // If we are using LuaJIT add a C++ wrapper function to catch
102         // exceptions thrown in Lua -> C++ calls
103 #if USE_LUAJIT
104         lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper);
105         luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
106         lua_pop(m_luastack, 1);
107 #endif
108
109         // Add basic globals
110         lua_newtable(m_luastack);
111         lua_setglobal(m_luastack, "core");
112
113         if (m_type == ScriptingType::Client)
114                 lua_pushstring(m_luastack, "/");
115         else
116                 lua_pushstring(m_luastack, DIR_DELIM);
117         lua_setglobal(m_luastack, "DIR_DELIM");
118
119         lua_pushstring(m_luastack, porting::getPlatformName());
120         lua_setglobal(m_luastack, "PLATFORM");
121 }
122
123 ScriptApiBase::~ScriptApiBase()
124 {
125         lua_close(m_luastack);
126 }
127
128 int ScriptApiBase::luaPanic(lua_State *L)
129 {
130         std::ostringstream oss;
131         oss << "LUA PANIC: unprotected error in call to Lua API ("
132                 << lua_tostring(L, -1) << ")";
133         FATAL_ERROR(oss.str().c_str());
134         // NOTREACHED
135         return 0;
136 }
137
138 void ScriptApiBase::clientOpenLibs(lua_State *L)
139 {
140         static const std::vector<std::pair<std::string, lua_CFunction>> m_libs = {
141                 { "", luaopen_base },
142                 { LUA_TABLIBNAME,  luaopen_table   },
143                 { LUA_OSLIBNAME,   luaopen_os      },
144                 { LUA_STRLIBNAME,  luaopen_string  },
145                 { LUA_MATHLIBNAME, luaopen_math    },
146                 { LUA_DBLIBNAME,   luaopen_debug   },
147 #if USE_LUAJIT
148                 { LUA_JITLIBNAME,  luaopen_jit     },
149 #endif
150         };
151         
152         for (const std::pair<std::string, lua_CFunction> &lib : m_libs) {
153             lua_pushcfunction(L, lib.second);
154             lua_pushstring(L, lib.first.c_str());
155             lua_call(L, 1, 0);
156         }
157 }
158
159 void ScriptApiBase::loadMod(const std::string &script_path,
160                 const std::string &mod_name)
161 {
162         ModNameStorer mod_name_storer(getStack(), mod_name);
163
164         loadScript(script_path);
165 }
166
167 void ScriptApiBase::loadScript(const std::string &script_path)
168 {
169         verbosestream << "Loading and running script from " << script_path << std::endl;
170
171         lua_State *L = getStack();
172
173         int error_handler = PUSH_ERROR_HANDLER(L);
174
175         bool ok;
176         if (m_secure) {
177                 ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
178         } else {
179                 ok = !luaL_loadfile(L, script_path.c_str());
180         }
181         ok = ok && !lua_pcall(L, 0, 0, error_handler);
182         if (!ok) {
183                 std::string error_msg = lua_tostring(L, -1);
184                 lua_pop(L, 2); // Pop error message and error handler
185                 throw ModError("Failed to load and run script from " +
186                                 script_path + ":\n" + error_msg);
187         }
188         lua_pop(L, 1); // Pop error handler
189 }
190
191 #ifndef SERVER
192 void ScriptApiBase::loadModFromMemory(const std::string &mod_name)
193 {
194         ModNameStorer mod_name_storer(getStack(), mod_name);
195
196         const std::string *init_filename = getClient()->getModFile(mod_name + ":init.lua");
197         const std::string display_filename = mod_name + ":init.lua";
198         if(init_filename == NULL)
199                 throw ModError("Mod:\"" + mod_name + "\" lacks init.lua");
200
201         verbosestream << "Loading and running script " << display_filename << std::endl;
202
203         lua_State *L = getStack();
204
205         int error_handler = PUSH_ERROR_HANDLER(L);
206
207         bool ok = ScriptApiSecurity::safeLoadFile(L, init_filename->c_str(), display_filename.c_str());
208         if (ok)
209                 ok = !lua_pcall(L, 0, 0, error_handler);
210         if (!ok) {
211                 std::string error_msg = luaL_checkstring(L, -1);
212                 lua_pop(L, 2); // Pop error message and error handler
213                 throw ModError("Failed to load and run mod \"" +
214                                 mod_name + "\":\n" + error_msg);
215         }
216         lua_pop(L, 1); // Pop error handler
217 }
218 #endif
219
220 // Push the list of callbacks (a lua table).
221 // Then push nargs arguments.
222 // Then call this function, which
223 // - runs the callbacks
224 // - replaces the table and arguments with the return value,
225 //     computed depending on mode
226 // This function must only be called with scriptlock held (i.e. inside of a
227 // code block with SCRIPTAPI_PRECHECKHEADER declared)
228 void ScriptApiBase::runCallbacksRaw(int nargs,
229                 RunCallbacksMode mode, const char *fxn)
230 {
231 #ifdef SCRIPTAPI_LOCK_DEBUG
232         assert(m_lock_recursion_count > 0);
233 #endif
234         lua_State *L = getStack();
235         FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
236
237         // Insert error handler
238         PUSH_ERROR_HANDLER(L);
239         int error_handler = lua_gettop(L) - nargs - 1;
240         lua_insert(L, error_handler);
241
242         // Insert run_callbacks between error handler and table
243         lua_getglobal(L, "core");
244         lua_getfield(L, -1, "run_callbacks");
245         lua_remove(L, -2);
246         lua_insert(L, error_handler + 1);
247
248         // Insert mode after table
249         lua_pushnumber(L, (int)mode);
250         lua_insert(L, error_handler + 3);
251
252         // Stack now looks like this:
253         // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
254
255         int result = lua_pcall(L, nargs + 2, 1, error_handler);
256         if (result != 0)
257                 scriptError(result, fxn);
258
259         lua_remove(L, error_handler);
260 }
261
262 void ScriptApiBase::realityCheck()
263 {
264         int top = lua_gettop(m_luastack);
265         if (top >= 30) {
266                 dstream << "Stack is over 30:" << std::endl;
267                 stackDump(dstream);
268                 std::string traceback = script_get_backtrace(m_luastack);
269                 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
270         }
271 }
272
273 void ScriptApiBase::scriptError(int result, const char *fxn)
274 {
275         script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
276 }
277
278 void ScriptApiBase::stackDump(std::ostream &o)
279 {
280         int top = lua_gettop(m_luastack);
281         for (int i = 1; i <= top; i++) {  /* repeat for each level */
282                 int t = lua_type(m_luastack, i);
283                 switch (t) {
284                         case LUA_TSTRING:  /* strings */
285                                 o << "\"" << lua_tostring(m_luastack, i) << "\"";
286                                 break;
287                         case LUA_TBOOLEAN:  /* booleans */
288                                 o << (lua_toboolean(m_luastack, i) ? "true" : "false");
289                                 break;
290                         case LUA_TNUMBER:  /* numbers */ {
291                                 char buf[10];
292                                 snprintf(buf, 10, "%lf", lua_tonumber(m_luastack, i));
293                                 o << buf;
294                                 break;
295                         }
296                         default:  /* other values */
297                                 o << lua_typename(m_luastack, t);
298                                 break;
299                 }
300                 o << " ";
301         }
302         o << std::endl;
303 }
304
305 void ScriptApiBase::setOriginDirect(const char *origin)
306 {
307         m_last_run_mod = origin ? origin : "??";
308 }
309
310 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
311 {
312 #ifdef SCRIPTAPI_DEBUG
313         lua_State *L = getStack();
314
315         m_last_run_mod = lua_istable(L, index) ?
316                 getstringfield_default(L, index, "mod_origin", "") : "";
317         //printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str());
318 #endif
319 }
320
321 void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
322 {
323         SCRIPTAPI_PRECHECKHEADER
324         //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
325
326         // Create object on stack
327         ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
328         int object = lua_gettop(L);
329
330         // Get core.object_refs table
331         lua_getglobal(L, "core");
332         lua_getfield(L, -1, "object_refs");
333         luaL_checktype(L, -1, LUA_TTABLE);
334         int objectstable = lua_gettop(L);
335
336         // object_refs[id] = object
337         lua_pushnumber(L, cobj->getId()); // Push id
338         lua_pushvalue(L, object); // Copy object to top of stack
339         lua_settable(L, objectstable);
340 }
341
342 void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
343 {
344         SCRIPTAPI_PRECHECKHEADER
345         //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
346
347         // Get core.object_refs table
348         lua_getglobal(L, "core");
349         lua_getfield(L, -1, "object_refs");
350         luaL_checktype(L, -1, LUA_TTABLE);
351         int objectstable = lua_gettop(L);
352
353         // Get object_refs[id]
354         lua_pushnumber(L, cobj->getId()); // Push id
355         lua_gettable(L, objectstable);
356         // Set object reference to NULL
357         ObjectRef::set_null(L);
358         lua_pop(L, 1); // pop object
359
360         // Set object_refs[id] = nil
361         lua_pushnumber(L, cobj->getId()); // Push id
362         lua_pushnil(L);
363         lua_settable(L, objectstable);
364 }
365
366 // Creates a new anonymous reference if cobj=NULL or id=0
367 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
368                 ServerActiveObject *cobj)
369 {
370         if (cobj == NULL || cobj->getId() == 0) {
371                 ObjectRef::create(L, cobj);
372         } else {
373                 push_objectRef(L, cobj->getId());
374                 if (cobj->isGone())
375                         warningstream << "ScriptApiBase::objectrefGetOrCreate(): "
376                                         << "Pushing ObjectRef to removed/deactivated object"
377                                         << ", this is probably a bug." << std::endl;
378         }
379 }
380
381 Server* ScriptApiBase::getServer()
382 {
383         return dynamic_cast<Server *>(m_gamedef);
384 }
385 #ifndef SERVER
386 Client* ScriptApiBase::getClient()
387 {
388         return dynamic_cast<Client *>(m_gamedef);
389 }
390 #endif