3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
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"
31 #include "util/string.h"
50 ModNameStorer(lua_State *L_, const std::string &mod_name):
53 // Store current mod name in registry
54 lua_pushstring(L, mod_name.c_str());
55 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
59 // Clear current mod name from registry
61 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
70 ScriptApiBase::ScriptApiBase() :
73 #ifdef SCRIPTAPI_LOCK_DEBUG
74 m_lock_recursion_count = 0;
77 m_luastack = luaL_newstate();
78 FATAL_ERROR_IF(!m_luastack, "luaL_newstate() failed");
80 luaL_openlibs(m_luastack);
82 // Make the ScriptApiBase* accessible to ModApiBase
83 lua_pushlightuserdata(m_luastack, this);
84 lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
86 // Add and save an error handler
87 lua_pushcfunction(m_luastack, script_error_handler);
88 lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_ERROR_HANDLER);
90 // If we are using LuaJIT add a C++ wrapper function to catch
91 // exceptions thrown in Lua -> C++ calls
93 lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper);
94 luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
95 lua_pop(m_luastack, 1);
99 lua_newtable(m_luastack);
100 lua_setglobal(m_luastack, "core");
102 lua_pushstring(m_luastack, DIR_DELIM);
103 lua_setglobal(m_luastack, "DIR_DELIM");
105 lua_pushstring(m_luastack, porting::getPlatformName());
106 lua_setglobal(m_luastack, "PLATFORM");
108 // m_secure gets set to true inside
109 // ScriptApiSecurity::initializeSecurity(), if neccessary.
110 // Default to false otherwise
114 m_environment = NULL;
118 ScriptApiBase::~ScriptApiBase()
120 lua_close(m_luastack);
123 void ScriptApiBase::loadMod(const std::string &script_path,
124 const std::string &mod_name)
126 ModNameStorer mod_name_storer(getStack(), mod_name);
128 loadScript(script_path);
131 void ScriptApiBase::loadScript(const std::string &script_path)
133 verbosestream << "Loading and running script from " << script_path << std::endl;
135 lua_State *L = getStack();
137 int error_handler = PUSH_ERROR_HANDLER(L);
141 ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
143 ok = !luaL_loadfile(L, script_path.c_str());
145 ok = ok && !lua_pcall(L, 0, 0, error_handler);
147 std::string error_msg = lua_tostring(L, -1);
148 lua_pop(L, 2); // Pop error message and error handler
149 throw ModError("Failed to load and run script from " +
150 script_path + ":\n" + error_msg);
152 lua_pop(L, 1); // Pop error handler
155 // Push the list of callbacks (a lua table).
156 // Then push nargs arguments.
157 // Then call this function, which
158 // - runs the callbacks
159 // - replaces the table and arguments with the return value,
160 // computed depending on mode
161 // This function must only be called with scriptlock held (i.e. inside of a
162 // code block with SCRIPTAPI_PRECHECKHEADER declared)
163 void ScriptApiBase::runCallbacksRaw(int nargs,
164 RunCallbacksMode mode, const char *fxn)
166 #ifdef SCRIPTAPI_LOCK_DEBUG
167 assert(m_lock_recursion_count > 0);
169 lua_State *L = getStack();
170 FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
172 // Insert error handler
173 PUSH_ERROR_HANDLER(L);
174 int error_handler = lua_gettop(L) - nargs - 1;
175 lua_insert(L, error_handler);
177 // Insert run_callbacks between error handler and table
178 lua_getglobal(L, "core");
179 lua_getfield(L, -1, "run_callbacks");
181 lua_insert(L, error_handler + 1);
183 // Insert mode after table
184 lua_pushnumber(L, (int)mode);
185 lua_insert(L, error_handler + 3);
187 // Stack now looks like this:
188 // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
190 int result = lua_pcall(L, nargs + 2, 1, error_handler);
192 scriptError(result, fxn);
194 lua_remove(L, error_handler);
197 void ScriptApiBase::realityCheck()
199 int top = lua_gettop(m_luastack);
201 dstream << "Stack is over 30:" << std::endl;
203 std::string traceback = script_get_backtrace(m_luastack);
204 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
208 void ScriptApiBase::scriptError(int result, const char *fxn)
210 script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
213 void ScriptApiBase::stackDump(std::ostream &o)
215 int top = lua_gettop(m_luastack);
216 for (int i = 1; i <= top; i++) { /* repeat for each level */
217 int t = lua_type(m_luastack, i);
219 case LUA_TSTRING: /* strings */
220 o << "\"" << lua_tostring(m_luastack, i) << "\"";
222 case LUA_TBOOLEAN: /* booleans */
223 o << (lua_toboolean(m_luastack, i) ? "true" : "false");
225 case LUA_TNUMBER: /* numbers */ {
227 snprintf(buf, 10, "%g", lua_tonumber(m_luastack, i));
231 default: /* other values */
232 o << lua_typename(m_luastack, t);
240 void ScriptApiBase::setOriginDirect(const char *origin)
242 m_last_run_mod = origin ? origin : "??";
245 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
247 #ifdef SCRIPTAPI_DEBUG
248 lua_State *L = getStack();
250 m_last_run_mod = lua_istable(L, index) ?
251 getstringfield_default(L, index, "mod_origin", "") : "";
252 //printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str());
256 void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
258 SCRIPTAPI_PRECHECKHEADER
259 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
261 // Create object on stack
262 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
263 int object = lua_gettop(L);
265 // Get core.object_refs table
266 lua_getglobal(L, "core");
267 lua_getfield(L, -1, "object_refs");
268 luaL_checktype(L, -1, LUA_TTABLE);
269 int objectstable = lua_gettop(L);
271 // object_refs[id] = object
272 lua_pushnumber(L, cobj->getId()); // Push id
273 lua_pushvalue(L, object); // Copy object to top of stack
274 lua_settable(L, objectstable);
277 void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
279 SCRIPTAPI_PRECHECKHEADER
280 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
282 // Get core.object_refs table
283 lua_getglobal(L, "core");
284 lua_getfield(L, -1, "object_refs");
285 luaL_checktype(L, -1, LUA_TTABLE);
286 int objectstable = lua_gettop(L);
288 // Get object_refs[id]
289 lua_pushnumber(L, cobj->getId()); // Push id
290 lua_gettable(L, objectstable);
291 // Set object reference to NULL
292 ObjectRef::set_null(L);
293 lua_pop(L, 1); // pop object
295 // Set object_refs[id] = nil
296 lua_pushnumber(L, cobj->getId()); // Push id
298 lua_settable(L, objectstable);
301 // Creates a new anonymous reference if cobj=NULL or id=0
302 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
303 ServerActiveObject *cobj)
305 if (cobj == NULL || cobj->getId() == 0) {
306 ObjectRef::create(L, cobj);
308 objectrefGet(L, cobj->getId());
312 void ScriptApiBase::objectrefGet(lua_State *L, u16 id)
314 // Get core.object_refs[i]
315 lua_getglobal(L, "core");
316 lua_getfield(L, -1, "object_refs");
317 luaL_checktype(L, -1, LUA_TTABLE);
318 lua_pushnumber(L, id);
320 lua_remove(L, -2); // object_refs
321 lua_remove(L, -2); // core