]> git.lizzy.rs Git - dragonfireclient.git/blob - src/script/cpp_api/s_base.cpp
Clean up threading
[dragonfireclient.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 "debug.h"
27 #include "filesys.h"
28 #include "log.h"
29 #include "mods.h"
30 #include "porting.h"
31 #include "util/string.h"
32
33
34 extern "C" {
35 #include "lualib.h"
36 #if USE_LUAJIT
37         #include "luajit.h"
38 #endif
39 }
40
41 #include <stdio.h>
42 #include <cstdarg>
43
44
45 class ModNameStorer
46 {
47 private:
48         lua_State *L;
49 public:
50         ModNameStorer(lua_State *L_, const std::string &mod_name):
51                 L(L_)
52         {
53                 // Store current mod name in registry
54                 lua_pushstring(L, mod_name.c_str());
55                 lua_setfield(L, LUA_REGISTRYINDEX, SCRIPT_MOD_NAME_FIELD);
56         }
57         ~ModNameStorer()
58         {
59                 // Clear current mod name from registry
60                 lua_pushnil(L);
61                 lua_setfield(L, LUA_REGISTRYINDEX, SCRIPT_MOD_NAME_FIELD);
62         }
63 };
64
65
66 /*
67         ScriptApiBase
68 */
69
70 ScriptApiBase::ScriptApiBase()
71 {
72 #ifdef SCRIPTAPI_LOCK_DEBUG
73         m_locked = false;
74 #endif
75
76         m_luastack = luaL_newstate();
77         FATAL_ERROR_IF(!m_luastack, "luaL_newstate() failed");
78
79         luaL_openlibs(m_luastack);
80
81         // Add and save an error handler
82         lua_pushcfunction(m_luastack, script_error_handler);
83         m_errorhandler = lua_gettop(m_luastack);
84
85         // Make the ScriptApiBase* accessible to ModApiBase
86         lua_pushlightuserdata(m_luastack, this);
87         lua_setfield(m_luastack, LUA_REGISTRYINDEX, "scriptapi");
88
89         // If we are using LuaJIT add a C++ wrapper function to catch
90         // exceptions thrown in Lua -> C++ calls
91 #if USE_LUAJIT
92         lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper);
93         luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
94         lua_pop(m_luastack, 1);
95 #endif
96
97         // Add basic globals
98         lua_newtable(m_luastack);
99         lua_setglobal(m_luastack, "core");
100
101         lua_pushstring(m_luastack, DIR_DELIM);
102         lua_setglobal(m_luastack, "DIR_DELIM");
103
104         lua_pushstring(m_luastack, porting::getPlatformName());
105         lua_setglobal(m_luastack, "PLATFORM");
106
107         // m_secure gets set to true inside
108         // ScriptApiSecurity::initializeSecurity(), if neccessary.
109         // Default to false otherwise
110         m_secure = false;
111
112         m_server = NULL;
113         m_environment = NULL;
114         m_guiengine = NULL;
115 }
116
117 ScriptApiBase::~ScriptApiBase()
118 {
119         lua_close(m_luastack);
120 }
121
122 bool ScriptApiBase::loadMod(const std::string &script_path,
123                 const std::string &mod_name, std::string *error)
124 {
125         ModNameStorer mod_name_storer(getStack(), mod_name);
126
127         return loadScript(script_path, error);
128 }
129
130 bool ScriptApiBase::loadScript(const std::string &script_path, std::string *error)
131 {
132         verbosestream << "Loading and running script from " << script_path << std::endl;
133
134         lua_State *L = getStack();
135
136         bool ok;
137         if (m_secure) {
138                 ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
139         } else {
140                 ok = !luaL_loadfile(L, script_path.c_str());
141         }
142         ok = ok && !lua_pcall(L, 0, 0, m_errorhandler);
143         if (!ok) {
144                 std::string error_msg = lua_tostring(L, -1);
145                 if (error)
146                         *error = error_msg;
147                 errorstream << "========== ERROR FROM LUA ===========" << std::endl
148                         << "Failed to load and run script from " << std::endl
149                         << script_path << ":" << std::endl << std::endl
150                         << error_msg << std::endl << std::endl
151                         << "======= END OF ERROR FROM LUA ========" << std::endl;
152                 lua_pop(L, 1); // Pop error message from stack
153                 return false;
154         }
155         return true;
156 }
157
158 // Push the list of callbacks (a lua table).
159 // Then push nargs arguments.
160 // Then call this function, which
161 // - runs the callbacks
162 // - replaces the table and arguments with the return value,
163 //     computed depending on mode
164 void ScriptApiBase::runCallbacksRaw(int nargs,
165                 RunCallbacksMode mode, const char *fxn)
166 {
167         lua_State *L = getStack();
168         FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
169
170         // Insert error handler
171         lua_pushcfunction(L, script_error_handler);
172         int errorhandler = lua_gettop(L) - nargs - 1;
173         lua_insert(L, errorhandler);
174
175         // Insert run_callbacks between error handler and table
176         lua_getglobal(L, "core");
177         lua_getfield(L, -1, "run_callbacks");
178         lua_remove(L, -2);
179         lua_insert(L, errorhandler + 1);
180
181         // Insert mode after table
182         lua_pushnumber(L, (int)mode);
183         lua_insert(L, errorhandler + 3);
184
185         // Stack now looks like this:
186         // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
187
188         int result = lua_pcall(L, nargs + 2, 1, errorhandler);
189         if (result != 0)
190                 scriptError(result, fxn);
191
192         lua_remove(L, -2); // Remove error handler
193 }
194
195 void ScriptApiBase::realityCheck()
196 {
197         int top = lua_gettop(m_luastack);
198         if (top >= 30) {
199                 dstream << "Stack is over 30:" << std::endl;
200                 stackDump(dstream);
201                 std::string traceback = script_get_backtrace(m_luastack);
202                 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
203         }
204 }
205
206 void ScriptApiBase::scriptError(int result, const char *fxn)
207 {
208         script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
209 }
210
211 void ScriptApiBase::stackDump(std::ostream &o)
212 {
213         int top = lua_gettop(m_luastack);
214         for (int i = 1; i <= top; i++) {  /* repeat for each level */
215                 int t = lua_type(m_luastack, i);
216                 switch (t) {
217                         case LUA_TSTRING:  /* strings */
218                                 o << "\"" << lua_tostring(m_luastack, i) << "\"";
219                                 break;
220                         case LUA_TBOOLEAN:  /* booleans */
221                                 o << (lua_toboolean(m_luastack, i) ? "true" : "false");
222                                 break;
223                         case LUA_TNUMBER:  /* numbers */ {
224                                 char buf[10];
225                                 snprintf(buf, 10, "%g", lua_tonumber(m_luastack, i));
226                                 o << buf;
227                                 break;
228                         }
229                         default:  /* other values */
230                                 o << lua_typename(m_luastack, t);
231                                 break;
232                 }
233                 o << " ";
234         }
235         o << std::endl;
236 }
237
238 void ScriptApiBase::setOriginDirect(const char *origin)
239 {
240         m_last_run_mod = origin ? origin : "??";
241 }
242
243 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
244 {
245 #ifdef SCRIPTAPI_DEBUG
246         lua_State *L = getStack();
247
248         m_last_run_mod = lua_istable(L, index) ?
249                 getstringfield_default(L, index, "mod_origin", "") : "";
250         //printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str());
251 #endif
252 }
253
254 void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
255 {
256         SCRIPTAPI_PRECHECKHEADER
257         //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
258
259         // Create object on stack
260         ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
261         int object = lua_gettop(L);
262
263         // Get core.object_refs table
264         lua_getglobal(L, "core");
265         lua_getfield(L, -1, "object_refs");
266         luaL_checktype(L, -1, LUA_TTABLE);
267         int objectstable = lua_gettop(L);
268
269         // object_refs[id] = object
270         lua_pushnumber(L, cobj->getId()); // Push id
271         lua_pushvalue(L, object); // Copy object to top of stack
272         lua_settable(L, objectstable);
273 }
274
275 void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
276 {
277         SCRIPTAPI_PRECHECKHEADER
278         //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
279
280         // Get core.object_refs table
281         lua_getglobal(L, "core");
282         lua_getfield(L, -1, "object_refs");
283         luaL_checktype(L, -1, LUA_TTABLE);
284         int objectstable = lua_gettop(L);
285
286         // Get object_refs[id]
287         lua_pushnumber(L, cobj->getId()); // Push id
288         lua_gettable(L, objectstable);
289         // Set object reference to NULL
290         ObjectRef::set_null(L);
291         lua_pop(L, 1); // pop object
292
293         // Set object_refs[id] = nil
294         lua_pushnumber(L, cobj->getId()); // Push id
295         lua_pushnil(L);
296         lua_settable(L, objectstable);
297 }
298
299 // Creates a new anonymous reference if cobj=NULL or id=0
300 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
301                 ServerActiveObject *cobj)
302 {
303         if (cobj == NULL || cobj->getId() == 0) {
304                 ObjectRef::create(L, cobj);
305         } else {
306                 objectrefGet(L, cobj->getId());
307         }
308 }
309
310 void ScriptApiBase::objectrefGet(lua_State *L, u16 id)
311 {
312         // Get core.object_refs[i]
313         lua_getglobal(L, "core");
314         lua_getfield(L, -1, "object_refs");
315         luaL_checktype(L, -1, LUA_TTABLE);
316         lua_pushnumber(L, id);
317         lua_gettable(L, -2);
318         lua_remove(L, -2); // object_refs
319         lua_remove(L, -2); // core
320 }