]> git.lizzy.rs Git - minetest.git/blob - src/script/cpp_api/s_base.cpp
[CSM] Client side modding
[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 <sstream>
46
47
48 class ModNameStorer
49 {
50 private:
51         lua_State *L;
52 public:
53         ModNameStorer(lua_State *L_, const std::string &mod_name):
54                 L(L_)
55         {
56                 // Store current mod name in registry
57                 lua_pushstring(L, mod_name.c_str());
58                 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
59         }
60         ~ModNameStorer()
61         {
62                 // Clear current mod name from registry
63                 lua_pushnil(L);
64                 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
65         }
66 };
67
68
69 /*
70         ScriptApiBase
71 */
72
73 ScriptApiBase::ScriptApiBase() :
74         m_luastackmutex(),
75         m_gamedef(NULL)
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         luaL_openlibs(m_luastack);
87
88         // Make the ScriptApiBase* accessible to ModApiBase
89         lua_pushlightuserdata(m_luastack, this);
90         lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
91
92         // Add and save an error handler
93         lua_pushcfunction(m_luastack, script_error_handler);
94         lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_ERROR_HANDLER);
95
96         // If we are using LuaJIT add a C++ wrapper function to catch
97         // exceptions thrown in Lua -> C++ calls
98 #if USE_LUAJIT
99         lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper);
100         luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
101         lua_pop(m_luastack, 1);
102 #endif
103
104         // Add basic globals
105         lua_newtable(m_luastack);
106         lua_setglobal(m_luastack, "core");
107
108         lua_pushstring(m_luastack, DIR_DELIM);
109         lua_setglobal(m_luastack, "DIR_DELIM");
110
111         lua_pushstring(m_luastack, porting::getPlatformName());
112         lua_setglobal(m_luastack, "PLATFORM");
113
114         // m_secure gets set to true inside
115         // ScriptApiSecurity::initializeSecurity(), if neccessary.
116         // Default to false otherwise
117         m_secure = false;
118
119         m_environment = NULL;
120         m_guiengine = NULL;
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::loadMod(const std::string &script_path,
139                 const std::string &mod_name)
140 {
141         ModNameStorer mod_name_storer(getStack(), mod_name);
142
143         loadScript(script_path);
144 }
145
146 void ScriptApiBase::loadScript(const std::string &script_path)
147 {
148         verbosestream << "Loading and running script from " << script_path << std::endl;
149
150         lua_State *L = getStack();
151
152         int error_handler = PUSH_ERROR_HANDLER(L);
153
154         bool ok;
155         if (m_secure) {
156                 ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
157         } else {
158                 ok = !luaL_loadfile(L, script_path.c_str());
159         }
160         ok = ok && !lua_pcall(L, 0, 0, error_handler);
161         if (!ok) {
162                 std::string error_msg = lua_tostring(L, -1);
163                 lua_pop(L, 2); // Pop error message and error handler
164                 throw ModError("Failed to load and run script from " +
165                                 script_path + ":\n" + error_msg);
166         }
167         lua_pop(L, 1); // Pop error handler
168 }
169
170 // Push the list of callbacks (a lua table).
171 // Then push nargs arguments.
172 // Then call this function, which
173 // - runs the callbacks
174 // - replaces the table and arguments with the return value,
175 //     computed depending on mode
176 // This function must only be called with scriptlock held (i.e. inside of a
177 // code block with SCRIPTAPI_PRECHECKHEADER declared)
178 void ScriptApiBase::runCallbacksRaw(int nargs,
179                 RunCallbacksMode mode, const char *fxn)
180 {
181 #ifdef SCRIPTAPI_LOCK_DEBUG
182         assert(m_lock_recursion_count > 0);
183 #endif
184         lua_State *L = getStack();
185         FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
186
187         // Insert error handler
188         PUSH_ERROR_HANDLER(L);
189         int error_handler = lua_gettop(L) - nargs - 1;
190         lua_insert(L, error_handler);
191
192         // Insert run_callbacks between error handler and table
193         lua_getglobal(L, "core");
194         lua_getfield(L, -1, "run_callbacks");
195         lua_remove(L, -2);
196         lua_insert(L, error_handler + 1);
197
198         // Insert mode after table
199         lua_pushnumber(L, (int)mode);
200         lua_insert(L, error_handler + 3);
201
202         // Stack now looks like this:
203         // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
204
205         int result = lua_pcall(L, nargs + 2, 1, error_handler);
206         if (result != 0)
207                 scriptError(result, fxn);
208
209         lua_remove(L, error_handler);
210 }
211
212 void ScriptApiBase::realityCheck()
213 {
214         int top = lua_gettop(m_luastack);
215         if (top >= 30) {
216                 dstream << "Stack is over 30:" << std::endl;
217                 stackDump(dstream);
218                 std::string traceback = script_get_backtrace(m_luastack);
219                 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
220         }
221 }
222
223 void ScriptApiBase::scriptError(int result, const char *fxn)
224 {
225         script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
226 }
227
228 void ScriptApiBase::stackDump(std::ostream &o)
229 {
230         int top = lua_gettop(m_luastack);
231         for (int i = 1; i <= top; i++) {  /* repeat for each level */
232                 int t = lua_type(m_luastack, i);
233                 switch (t) {
234                         case LUA_TSTRING:  /* strings */
235                                 o << "\"" << lua_tostring(m_luastack, i) << "\"";
236                                 break;
237                         case LUA_TBOOLEAN:  /* booleans */
238                                 o << (lua_toboolean(m_luastack, i) ? "true" : "false");
239                                 break;
240                         case LUA_TNUMBER:  /* numbers */ {
241                                 char buf[10];
242                                 snprintf(buf, 10, "%g", lua_tonumber(m_luastack, i));
243                                 o << buf;
244                                 break;
245                         }
246                         default:  /* other values */
247                                 o << lua_typename(m_luastack, t);
248                                 break;
249                 }
250                 o << " ";
251         }
252         o << std::endl;
253 }
254
255 void ScriptApiBase::setOriginDirect(const char *origin)
256 {
257         m_last_run_mod = origin ? origin : "??";
258 }
259
260 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
261 {
262 #ifdef SCRIPTAPI_DEBUG
263         lua_State *L = getStack();
264
265         m_last_run_mod = lua_istable(L, index) ?
266                 getstringfield_default(L, index, "mod_origin", "") : "";
267         //printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str());
268 #endif
269 }
270
271 void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
272 {
273         SCRIPTAPI_PRECHECKHEADER
274         //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
275
276         // Create object on stack
277         ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
278         int object = lua_gettop(L);
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         // object_refs[id] = object
287         lua_pushnumber(L, cobj->getId()); // Push id
288         lua_pushvalue(L, object); // Copy object to top of stack
289         lua_settable(L, objectstable);
290 }
291
292 void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
293 {
294         SCRIPTAPI_PRECHECKHEADER
295         //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
296
297         // Get core.object_refs table
298         lua_getglobal(L, "core");
299         lua_getfield(L, -1, "object_refs");
300         luaL_checktype(L, -1, LUA_TTABLE);
301         int objectstable = lua_gettop(L);
302
303         // Get object_refs[id]
304         lua_pushnumber(L, cobj->getId()); // Push id
305         lua_gettable(L, objectstable);
306         // Set object reference to NULL
307         ObjectRef::set_null(L);
308         lua_pop(L, 1); // pop object
309
310         // Set object_refs[id] = nil
311         lua_pushnumber(L, cobj->getId()); // Push id
312         lua_pushnil(L);
313         lua_settable(L, objectstable);
314 }
315
316 // Creates a new anonymous reference if cobj=NULL or id=0
317 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
318                 ServerActiveObject *cobj)
319 {
320         if (cobj == NULL || cobj->getId() == 0) {
321                 ObjectRef::create(L, cobj);
322         } else {
323                 objectrefGet(L, cobj->getId());
324         }
325 }
326
327 void ScriptApiBase::objectrefGet(lua_State *L, u16 id)
328 {
329         // Get core.object_refs[i]
330         lua_getglobal(L, "core");
331         lua_getfield(L, -1, "object_refs");
332         luaL_checktype(L, -1, LUA_TTABLE);
333         lua_pushnumber(L, id);
334         lua_gettable(L, -2);
335         lua_remove(L, -2); // object_refs
336         lua_remove(L, -2); // core
337 }
338
339 Server* ScriptApiBase::getServer()
340 {
341         return dynamic_cast<Server *>(m_gamedef);
342 }
343 #ifndef SERVER
344 Client* ScriptApiBase::getClient()
345 {
346         return dynamic_cast<Client *>(m_gamedef);
347 }
348 #endif