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