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"
29 #include "util/string.h"
45 #include "script/common/c_content.h"
54 ModNameStorer(lua_State *L_, const std::string &mod_name):
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);
63 // Clear current mod name from registry
65 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
74 ScriptApiBase::ScriptApiBase()
76 #ifdef SCRIPTAPI_LOCK_DEBUG
77 m_lock_recursion_count = 0;
80 m_luastack = luaL_newstate();
81 FATAL_ERROR_IF(!m_luastack, "luaL_newstate() failed");
83 lua_atpanic(m_luastack, &luaPanic);
85 luaL_openlibs(m_luastack);
87 // Make the ScriptApiBase* accessible to ModApiBase
88 lua_pushlightuserdata(m_luastack, this);
89 lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
91 // Add and save an error handler
92 lua_getglobal(m_luastack, "debug");
93 lua_getfield(m_luastack, -1, "traceback");
94 lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_BACKTRACE);
95 lua_pop(m_luastack, 1); // pop debug
97 // If we are using LuaJIT add a C++ wrapper function to catch
98 // exceptions thrown in Lua -> C++ calls
100 lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper);
101 luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
102 lua_pop(m_luastack, 1);
106 lua_newtable(m_luastack);
107 lua_setglobal(m_luastack, "core");
109 lua_pushstring(m_luastack, DIR_DELIM);
110 lua_setglobal(m_luastack, "DIR_DELIM");
112 lua_pushstring(m_luastack, porting::getPlatformName());
113 lua_setglobal(m_luastack, "PLATFORM");
116 ScriptApiBase::~ScriptApiBase()
118 lua_close(m_luastack);
121 int ScriptApiBase::luaPanic(lua_State *L)
123 std::ostringstream oss;
124 oss << "LUA PANIC: unprotected error in call to Lua API ("
125 << lua_tostring(L, -1) << ")";
126 FATAL_ERROR(oss.str().c_str());
131 void ScriptApiBase::loadMod(const std::string &script_path,
132 const std::string &mod_name)
134 ModNameStorer mod_name_storer(getStack(), mod_name);
136 loadScript(script_path);
139 void ScriptApiBase::loadScript(const std::string &script_path)
141 verbosestream << "Loading and running script from " << script_path << std::endl;
143 lua_State *L = getStack();
145 int error_handler = PUSH_ERROR_HANDLER(L);
149 ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
151 ok = !luaL_loadfile(L, script_path.c_str());
153 ok = ok && !lua_pcall(L, 0, 0, error_handler);
155 std::string error_msg = lua_tostring(L, -1);
156 lua_pop(L, 2); // Pop error message and error handler
157 throw ModError("Failed to load and run script from " +
158 script_path + ":\n" + error_msg);
160 lua_pop(L, 1); // Pop error handler
164 void ScriptApiBase::loadModFromMemory(const std::string &mod_name)
166 ModNameStorer mod_name_storer(getStack(), mod_name);
168 const std::string *init_filename = getClient()->getModFile(mod_name + ":init.lua");
169 const std::string display_filename = mod_name + ":init.lua";
170 if(init_filename == NULL)
171 throw ModError("Mod:\"" + mod_name + "\" lacks init.lua");
173 verbosestream << "Loading and running script " << display_filename << std::endl;
175 lua_State *L = getStack();
177 int error_handler = PUSH_ERROR_HANDLER(L);
179 bool ok = ScriptApiSecurity::safeLoadFile(L, init_filename->c_str(), display_filename.c_str());
181 ok = !lua_pcall(L, 0, 0, error_handler);
183 std::string error_msg = luaL_checkstring(L, -1);
184 lua_pop(L, 2); // Pop error message and error handler
185 throw ModError("Failed to load and run mod \"" +
186 mod_name + "\":\n" + error_msg);
188 lua_pop(L, 1); // Pop error handler
192 // Push the list of callbacks (a lua table).
193 // Then push nargs arguments.
194 // Then call this function, which
195 // - runs the callbacks
196 // - replaces the table and arguments with the return value,
197 // computed depending on mode
198 // This function must only be called with scriptlock held (i.e. inside of a
199 // code block with SCRIPTAPI_PRECHECKHEADER declared)
200 void ScriptApiBase::runCallbacksRaw(int nargs,
201 RunCallbacksMode mode, const char *fxn)
203 #ifdef SCRIPTAPI_LOCK_DEBUG
204 assert(m_lock_recursion_count > 0);
206 lua_State *L = getStack();
207 FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
209 // Insert error handler
210 PUSH_ERROR_HANDLER(L);
211 int error_handler = lua_gettop(L) - nargs - 1;
212 lua_insert(L, error_handler);
214 // Insert run_callbacks between error handler and table
215 lua_getglobal(L, "core");
216 lua_getfield(L, -1, "run_callbacks");
218 lua_insert(L, error_handler + 1);
220 // Insert mode after table
221 lua_pushnumber(L, (int)mode);
222 lua_insert(L, error_handler + 3);
224 // Stack now looks like this:
225 // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
227 int result = lua_pcall(L, nargs + 2, 1, error_handler);
229 scriptError(result, fxn);
231 lua_remove(L, error_handler);
234 void ScriptApiBase::realityCheck()
236 int top = lua_gettop(m_luastack);
238 dstream << "Stack is over 30:" << std::endl;
240 std::string traceback = script_get_backtrace(m_luastack);
241 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
245 void ScriptApiBase::scriptError(int result, const char *fxn)
247 script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
250 void ScriptApiBase::stackDump(std::ostream &o)
252 int top = lua_gettop(m_luastack);
253 for (int i = 1; i <= top; i++) { /* repeat for each level */
254 int t = lua_type(m_luastack, i);
256 case LUA_TSTRING: /* strings */
257 o << "\"" << lua_tostring(m_luastack, i) << "\"";
259 case LUA_TBOOLEAN: /* booleans */
260 o << (lua_toboolean(m_luastack, i) ? "true" : "false");
262 case LUA_TNUMBER: /* numbers */ {
264 snprintf(buf, 10, "%lf", lua_tonumber(m_luastack, i));
268 default: /* other values */
269 o << lua_typename(m_luastack, t);
277 void ScriptApiBase::setOriginDirect(const char *origin)
279 m_last_run_mod = origin ? origin : "??";
282 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
284 #ifdef SCRIPTAPI_DEBUG
285 lua_State *L = getStack();
287 m_last_run_mod = lua_istable(L, index) ?
288 getstringfield_default(L, index, "mod_origin", "") : "";
289 //printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str());
293 void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
295 SCRIPTAPI_PRECHECKHEADER
296 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
298 // Create object on stack
299 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
300 int object = lua_gettop(L);
302 // Get core.object_refs table
303 lua_getglobal(L, "core");
304 lua_getfield(L, -1, "object_refs");
305 luaL_checktype(L, -1, LUA_TTABLE);
306 int objectstable = lua_gettop(L);
308 // object_refs[id] = object
309 lua_pushnumber(L, cobj->getId()); // Push id
310 lua_pushvalue(L, object); // Copy object to top of stack
311 lua_settable(L, objectstable);
314 void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
316 SCRIPTAPI_PRECHECKHEADER
317 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
319 // Get core.object_refs table
320 lua_getglobal(L, "core");
321 lua_getfield(L, -1, "object_refs");
322 luaL_checktype(L, -1, LUA_TTABLE);
323 int objectstable = lua_gettop(L);
325 // Get object_refs[id]
326 lua_pushnumber(L, cobj->getId()); // Push id
327 lua_gettable(L, objectstable);
328 // Set object reference to NULL
329 ObjectRef::set_null(L);
330 lua_pop(L, 1); // pop object
332 // Set object_refs[id] = nil
333 lua_pushnumber(L, cobj->getId()); // Push id
335 lua_settable(L, objectstable);
338 // Creates a new anonymous reference if cobj=NULL or id=0
339 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
340 ServerActiveObject *cobj)
342 if (cobj == NULL || cobj->getId() == 0) {
343 ObjectRef::create(L, cobj);
345 push_objectRef(L, cobj->getId());
347 warningstream << "ScriptApiBase::objectrefGetOrCreate(): "
348 << "Pushing ObjectRef to removed/deactivated object"
349 << ", this is probably a bug." << std::endl;
353 Server* ScriptApiBase::getServer()
355 return dynamic_cast<Server *>(m_gamedef);
358 Client* ScriptApiBase::getClient()
360 return dynamic_cast<Client *>(m_gamedef);