]> git.lizzy.rs Git - minetest.git/blob - src/script/cpp_api/s_base.cpp
[CSM] Don't load the IO library. (#6087)
[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_LOADLIBNAME, luaopen_package },
143                 { LUA_TABLIBNAME,  luaopen_table   },
144                 { LUA_OSLIBNAME,   luaopen_os      },
145                 { LUA_STRLIBNAME,  luaopen_string  },
146                 { LUA_MATHLIBNAME, luaopen_math    },
147                 { LUA_DBLIBNAME,   luaopen_debug   },
148 #if USE_LUAJIT
149                 { LUA_JITLIBNAME,  luaopen_jit     },
150 #endif
151         };
152         
153         for (const std::pair<std::string, lua_CFunction> &lib : m_libs) {
154             lua_pushcfunction(L, lib.second);
155             lua_pushstring(L, lib.first.c_str());
156             lua_call(L, 1, 0);
157         }
158 }
159
160 void ScriptApiBase::loadMod(const std::string &script_path,
161                 const std::string &mod_name)
162 {
163         ModNameStorer mod_name_storer(getStack(), mod_name);
164
165         loadScript(script_path);
166 }
167
168 void ScriptApiBase::loadScript(const std::string &script_path)
169 {
170         verbosestream << "Loading and running script from " << script_path << std::endl;
171
172         lua_State *L = getStack();
173
174         int error_handler = PUSH_ERROR_HANDLER(L);
175
176         bool ok;
177         if (m_secure) {
178                 ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
179         } else {
180                 ok = !luaL_loadfile(L, script_path.c_str());
181         }
182         ok = ok && !lua_pcall(L, 0, 0, error_handler);
183         if (!ok) {
184                 std::string error_msg = lua_tostring(L, -1);
185                 lua_pop(L, 2); // Pop error message and error handler
186                 throw ModError("Failed to load and run script from " +
187                                 script_path + ":\n" + error_msg);
188         }
189         lua_pop(L, 1); // Pop error handler
190 }
191
192 #ifndef SERVER
193 void ScriptApiBase::loadModFromMemory(const std::string &mod_name)
194 {
195         ModNameStorer mod_name_storer(getStack(), mod_name);
196
197         const std::string *init_filename = getClient()->getModFile(mod_name + ":init.lua");
198         const std::string display_filename = mod_name + ":init.lua";
199         if(init_filename == NULL)
200                 throw ModError("Mod:\"" + mod_name + "\" lacks init.lua");
201
202         verbosestream << "Loading and running script " << display_filename << std::endl;
203
204         lua_State *L = getStack();
205
206         int error_handler = PUSH_ERROR_HANDLER(L);
207
208         bool ok = ScriptApiSecurity::safeLoadFile(L, init_filename->c_str(), display_filename.c_str());
209         if (ok)
210                 ok = !lua_pcall(L, 0, 0, error_handler);
211         if (!ok) {
212                 std::string error_msg = luaL_checkstring(L, -1);
213                 lua_pop(L, 2); // Pop error message and error handler
214                 throw ModError("Failed to load and run mod \"" +
215                                 mod_name + "\":\n" + error_msg);
216         }
217         lua_pop(L, 1); // Pop error handler
218 }
219 #endif
220
221 // Push the list of callbacks (a lua table).
222 // Then push nargs arguments.
223 // Then call this function, which
224 // - runs the callbacks
225 // - replaces the table and arguments with the return value,
226 //     computed depending on mode
227 // This function must only be called with scriptlock held (i.e. inside of a
228 // code block with SCRIPTAPI_PRECHECKHEADER declared)
229 void ScriptApiBase::runCallbacksRaw(int nargs,
230                 RunCallbacksMode mode, const char *fxn)
231 {
232 #ifdef SCRIPTAPI_LOCK_DEBUG
233         assert(m_lock_recursion_count > 0);
234 #endif
235         lua_State *L = getStack();
236         FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
237
238         // Insert error handler
239         PUSH_ERROR_HANDLER(L);
240         int error_handler = lua_gettop(L) - nargs - 1;
241         lua_insert(L, error_handler);
242
243         // Insert run_callbacks between error handler and table
244         lua_getglobal(L, "core");
245         lua_getfield(L, -1, "run_callbacks");
246         lua_remove(L, -2);
247         lua_insert(L, error_handler + 1);
248
249         // Insert mode after table
250         lua_pushnumber(L, (int)mode);
251         lua_insert(L, error_handler + 3);
252
253         // Stack now looks like this:
254         // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
255
256         int result = lua_pcall(L, nargs + 2, 1, error_handler);
257         if (result != 0)
258                 scriptError(result, fxn);
259
260         lua_remove(L, error_handler);
261 }
262
263 void ScriptApiBase::realityCheck()
264 {
265         int top = lua_gettop(m_luastack);
266         if (top >= 30) {
267                 dstream << "Stack is over 30:" << std::endl;
268                 stackDump(dstream);
269                 std::string traceback = script_get_backtrace(m_luastack);
270                 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
271         }
272 }
273
274 void ScriptApiBase::scriptError(int result, const char *fxn)
275 {
276         script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
277 }
278
279 void ScriptApiBase::stackDump(std::ostream &o)
280 {
281         int top = lua_gettop(m_luastack);
282         for (int i = 1; i <= top; i++) {  /* repeat for each level */
283                 int t = lua_type(m_luastack, i);
284                 switch (t) {
285                         case LUA_TSTRING:  /* strings */
286                                 o << "\"" << lua_tostring(m_luastack, i) << "\"";
287                                 break;
288                         case LUA_TBOOLEAN:  /* booleans */
289                                 o << (lua_toboolean(m_luastack, i) ? "true" : "false");
290                                 break;
291                         case LUA_TNUMBER:  /* numbers */ {
292                                 char buf[10];
293                                 snprintf(buf, 10, "%lf", lua_tonumber(m_luastack, i));
294                                 o << buf;
295                                 break;
296                         }
297                         default:  /* other values */
298                                 o << lua_typename(m_luastack, t);
299                                 break;
300                 }
301                 o << " ";
302         }
303         o << std::endl;
304 }
305
306 void ScriptApiBase::setOriginDirect(const char *origin)
307 {
308         m_last_run_mod = origin ? origin : "??";
309 }
310
311 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
312 {
313 #ifdef SCRIPTAPI_DEBUG
314         lua_State *L = getStack();
315
316         m_last_run_mod = lua_istable(L, index) ?
317                 getstringfield_default(L, index, "mod_origin", "") : "";
318         //printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str());
319 #endif
320 }
321
322 void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
323 {
324         SCRIPTAPI_PRECHECKHEADER
325         //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
326
327         // Create object on stack
328         ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
329         int object = lua_gettop(L);
330
331         // Get core.object_refs table
332         lua_getglobal(L, "core");
333         lua_getfield(L, -1, "object_refs");
334         luaL_checktype(L, -1, LUA_TTABLE);
335         int objectstable = lua_gettop(L);
336
337         // object_refs[id] = object
338         lua_pushnumber(L, cobj->getId()); // Push id
339         lua_pushvalue(L, object); // Copy object to top of stack
340         lua_settable(L, objectstable);
341 }
342
343 void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
344 {
345         SCRIPTAPI_PRECHECKHEADER
346         //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
347
348         // Get core.object_refs table
349         lua_getglobal(L, "core");
350         lua_getfield(L, -1, "object_refs");
351         luaL_checktype(L, -1, LUA_TTABLE);
352         int objectstable = lua_gettop(L);
353
354         // Get object_refs[id]
355         lua_pushnumber(L, cobj->getId()); // Push id
356         lua_gettable(L, objectstable);
357         // Set object reference to NULL
358         ObjectRef::set_null(L);
359         lua_pop(L, 1); // pop object
360
361         // Set object_refs[id] = nil
362         lua_pushnumber(L, cobj->getId()); // Push id
363         lua_pushnil(L);
364         lua_settable(L, objectstable);
365 }
366
367 // Creates a new anonymous reference if cobj=NULL or id=0
368 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
369                 ServerActiveObject *cobj)
370 {
371         if (cobj == NULL || cobj->getId() == 0) {
372                 ObjectRef::create(L, cobj);
373         } else {
374                 push_objectRef(L, cobj->getId());
375                 if (cobj->isGone())
376                         warningstream << "ScriptApiBase::objectrefGetOrCreate(): "
377                                         << "Pushing ObjectRef to removed/deactivated object"
378                                         << ", this is probably a bug." << std::endl;
379         }
380 }
381
382 Server* ScriptApiBase::getServer()
383 {
384         return dynamic_cast<Server *>(m_gamedef);
385 }
386 #ifndef SERVER
387 Client* ScriptApiBase::getClient()
388 {
389         return dynamic_cast<Client *>(m_gamedef);
390 }
391 #endif