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