]> git.lizzy.rs Git - minetest.git/blob - src/script/cpp_api/s_base.cpp
C++11 cleanup on constructors (#6000)
[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 <stdio.h>
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()
75 {
76 #ifdef SCRIPTAPI_LOCK_DEBUG
77         m_lock_recursion_count = 0;
78 #endif
79
80         m_luastack = luaL_newstate();
81         FATAL_ERROR_IF(!m_luastack, "luaL_newstate() failed");
82
83         lua_atpanic(m_luastack, &luaPanic);
84
85         luaL_openlibs(m_luastack);
86
87         // Make the ScriptApiBase* accessible to ModApiBase
88         lua_pushlightuserdata(m_luastack, this);
89         lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
90
91         // Add and save an error handler
92         lua_pushcfunction(m_luastack, script_error_handler);
93         lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_ERROR_HANDLER);
94
95         // If we are using LuaJIT add a C++ wrapper function to catch
96         // exceptions thrown in Lua -> C++ calls
97 #if USE_LUAJIT
98         lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper);
99         luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
100         lua_pop(m_luastack, 1);
101 #endif
102
103         // Add basic globals
104         lua_newtable(m_luastack);
105         lua_setglobal(m_luastack, "core");
106
107         lua_pushstring(m_luastack, DIR_DELIM);
108         lua_setglobal(m_luastack, "DIR_DELIM");
109
110         lua_pushstring(m_luastack, porting::getPlatformName());
111         lua_setglobal(m_luastack, "PLATFORM");
112 }
113
114 ScriptApiBase::~ScriptApiBase()
115 {
116         lua_close(m_luastack);
117 }
118
119 int ScriptApiBase::luaPanic(lua_State *L)
120 {
121         std::ostringstream oss;
122         oss << "LUA PANIC: unprotected error in call to Lua API ("
123                 << lua_tostring(L, -1) << ")";
124         FATAL_ERROR(oss.str().c_str());
125         // NOTREACHED
126         return 0;
127 }
128
129 void ScriptApiBase::loadMod(const std::string &script_path,
130                 const std::string &mod_name)
131 {
132         ModNameStorer mod_name_storer(getStack(), mod_name);
133
134         loadScript(script_path);
135 }
136
137 void ScriptApiBase::loadScript(const std::string &script_path)
138 {
139         verbosestream << "Loading and running script from " << script_path << std::endl;
140
141         lua_State *L = getStack();
142
143         int error_handler = PUSH_ERROR_HANDLER(L);
144
145         bool ok;
146         if (m_secure) {
147                 ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
148         } else {
149                 ok = !luaL_loadfile(L, script_path.c_str());
150         }
151         ok = ok && !lua_pcall(L, 0, 0, error_handler);
152         if (!ok) {
153                 std::string error_msg = lua_tostring(L, -1);
154                 lua_pop(L, 2); // Pop error message and error handler
155                 throw ModError("Failed to load and run script from " +
156                                 script_path + ":\n" + error_msg);
157         }
158         lua_pop(L, 1); // Pop error handler
159 }
160
161 // Push the list of callbacks (a lua table).
162 // Then push nargs arguments.
163 // Then call this function, which
164 // - runs the callbacks
165 // - replaces the table and arguments with the return value,
166 //     computed depending on mode
167 // This function must only be called with scriptlock held (i.e. inside of a
168 // code block with SCRIPTAPI_PRECHECKHEADER declared)
169 void ScriptApiBase::runCallbacksRaw(int nargs,
170                 RunCallbacksMode mode, const char *fxn)
171 {
172 #ifdef SCRIPTAPI_LOCK_DEBUG
173         assert(m_lock_recursion_count > 0);
174 #endif
175         lua_State *L = getStack();
176         FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
177
178         // Insert error handler
179         PUSH_ERROR_HANDLER(L);
180         int error_handler = lua_gettop(L) - nargs - 1;
181         lua_insert(L, error_handler);
182
183         // Insert run_callbacks between error handler and table
184         lua_getglobal(L, "core");
185         lua_getfield(L, -1, "run_callbacks");
186         lua_remove(L, -2);
187         lua_insert(L, error_handler + 1);
188
189         // Insert mode after table
190         lua_pushnumber(L, (int)mode);
191         lua_insert(L, error_handler + 3);
192
193         // Stack now looks like this:
194         // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
195
196         int result = lua_pcall(L, nargs + 2, 1, error_handler);
197         if (result != 0)
198                 scriptError(result, fxn);
199
200         lua_remove(L, error_handler);
201 }
202
203 void ScriptApiBase::realityCheck()
204 {
205         int top = lua_gettop(m_luastack);
206         if (top >= 30) {
207                 dstream << "Stack is over 30:" << std::endl;
208                 stackDump(dstream);
209                 std::string traceback = script_get_backtrace(m_luastack);
210                 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
211         }
212 }
213
214 void ScriptApiBase::scriptError(int result, const char *fxn)
215 {
216         script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
217 }
218
219 void ScriptApiBase::stackDump(std::ostream &o)
220 {
221         int top = lua_gettop(m_luastack);
222         for (int i = 1; i <= top; i++) {  /* repeat for each level */
223                 int t = lua_type(m_luastack, i);
224                 switch (t) {
225                         case LUA_TSTRING:  /* strings */
226                                 o << "\"" << lua_tostring(m_luastack, i) << "\"";
227                                 break;
228                         case LUA_TBOOLEAN:  /* booleans */
229                                 o << (lua_toboolean(m_luastack, i) ? "true" : "false");
230                                 break;
231                         case LUA_TNUMBER:  /* numbers */ {
232                                 char buf[10];
233                                 snprintf(buf, 10, "%lf", lua_tonumber(m_luastack, i));
234                                 o << buf;
235                                 break;
236                         }
237                         default:  /* other values */
238                                 o << lua_typename(m_luastack, t);
239                                 break;
240                 }
241                 o << " ";
242         }
243         o << std::endl;
244 }
245
246 void ScriptApiBase::setOriginDirect(const char *origin)
247 {
248         m_last_run_mod = origin ? origin : "??";
249 }
250
251 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
252 {
253 #ifdef SCRIPTAPI_DEBUG
254         lua_State *L = getStack();
255
256         m_last_run_mod = lua_istable(L, index) ?
257                 getstringfield_default(L, index, "mod_origin", "") : "";
258         //printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str());
259 #endif
260 }
261
262 void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
263 {
264         SCRIPTAPI_PRECHECKHEADER
265         //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
266
267         // Create object on stack
268         ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
269         int object = lua_gettop(L);
270
271         // Get core.object_refs table
272         lua_getglobal(L, "core");
273         lua_getfield(L, -1, "object_refs");
274         luaL_checktype(L, -1, LUA_TTABLE);
275         int objectstable = lua_gettop(L);
276
277         // object_refs[id] = object
278         lua_pushnumber(L, cobj->getId()); // Push id
279         lua_pushvalue(L, object); // Copy object to top of stack
280         lua_settable(L, objectstable);
281 }
282
283 void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
284 {
285         SCRIPTAPI_PRECHECKHEADER
286         //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
287
288         // Get core.object_refs table
289         lua_getglobal(L, "core");
290         lua_getfield(L, -1, "object_refs");
291         luaL_checktype(L, -1, LUA_TTABLE);
292         int objectstable = lua_gettop(L);
293
294         // Get object_refs[id]
295         lua_pushnumber(L, cobj->getId()); // Push id
296         lua_gettable(L, objectstable);
297         // Set object reference to NULL
298         ObjectRef::set_null(L);
299         lua_pop(L, 1); // pop object
300
301         // Set object_refs[id] = nil
302         lua_pushnumber(L, cobj->getId()); // Push id
303         lua_pushnil(L);
304         lua_settable(L, objectstable);
305 }
306
307 // Creates a new anonymous reference if cobj=NULL or id=0
308 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
309                 ServerActiveObject *cobj)
310 {
311         if (cobj == NULL || cobj->getId() == 0) {
312                 ObjectRef::create(L, cobj);
313         } else {
314                 push_objectRef(L, cobj->getId());
315         }
316 }
317
318 Server* ScriptApiBase::getServer()
319 {
320         return dynamic_cast<Server *>(m_gamedef);
321 }
322 #ifndef SERVER
323 Client* ScriptApiBase::getClient()
324 {
325         return dynamic_cast<Client *>(m_gamedef);
326 }
327 #endif