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(ScriptingType type):
77 #ifdef SCRIPTAPI_LOCK_DEBUG
78 m_lock_recursion_count = 0;
81 m_luastack = luaL_newstate();
82 FATAL_ERROR_IF(!m_luastack, "luaL_newstate() failed");
84 lua_atpanic(m_luastack, &luaPanic);
86 if (m_type == ScriptingType::Client)
87 clientOpenLibs(m_luastack);
89 luaL_openlibs(m_luastack);
91 // Make the ScriptApiBase* accessible to ModApiBase
92 lua_pushlightuserdata(m_luastack, this);
93 lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
95 // Add and save an error handler
96 lua_getglobal(m_luastack, "debug");
97 lua_getfield(m_luastack, -1, "traceback");
98 lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_BACKTRACE);
99 lua_pop(m_luastack, 1); // pop debug
101 // If we are using LuaJIT add a C++ wrapper function to catch
102 // exceptions thrown in Lua -> C++ calls
104 lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper);
105 luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
106 lua_pop(m_luastack, 1);
110 lua_newtable(m_luastack);
111 lua_setglobal(m_luastack, "core");
113 if (m_type == ScriptingType::Client)
114 lua_pushstring(m_luastack, "/");
116 lua_pushstring(m_luastack, DIR_DELIM);
117 lua_setglobal(m_luastack, "DIR_DELIM");
119 lua_pushstring(m_luastack, porting::getPlatformName());
120 lua_setglobal(m_luastack, "PLATFORM");
123 ScriptApiBase::~ScriptApiBase()
125 lua_close(m_luastack);
128 int ScriptApiBase::luaPanic(lua_State *L)
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());
138 void ScriptApiBase::clientOpenLibs(lua_State *L)
140 static const std::vector<std::pair<std::string, lua_CFunction>> m_libs = {
141 { "", luaopen_base },
142 { LUA_TABLIBNAME, luaopen_table },
143 { LUA_OSLIBNAME, luaopen_os },
144 { LUA_STRLIBNAME, luaopen_string },
145 { LUA_MATHLIBNAME, luaopen_math },
146 { LUA_DBLIBNAME, luaopen_debug },
148 { LUA_JITLIBNAME, luaopen_jit },
152 for (const std::pair<std::string, lua_CFunction> &lib : m_libs) {
153 lua_pushcfunction(L, lib.second);
154 lua_pushstring(L, lib.first.c_str());
159 void ScriptApiBase::loadMod(const std::string &script_path,
160 const std::string &mod_name)
162 ModNameStorer mod_name_storer(getStack(), mod_name);
164 loadScript(script_path);
167 void ScriptApiBase::loadScript(const std::string &script_path)
169 verbosestream << "Loading and running script from " << script_path << std::endl;
171 lua_State *L = getStack();
173 int error_handler = PUSH_ERROR_HANDLER(L);
177 ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
179 ok = !luaL_loadfile(L, script_path.c_str());
181 ok = ok && !lua_pcall(L, 0, 0, error_handler);
183 std::string error_msg = lua_tostring(L, -1);
184 lua_pop(L, 2); // Pop error message and error handler
185 throw ModError("Failed to load and run script from " +
186 script_path + ":\n" + error_msg);
188 lua_pop(L, 1); // Pop error handler
192 void ScriptApiBase::loadModFromMemory(const std::string &mod_name)
194 ModNameStorer mod_name_storer(getStack(), mod_name);
196 const std::string *init_filename = getClient()->getModFile(mod_name + ":init.lua");
197 const std::string display_filename = mod_name + ":init.lua";
198 if(init_filename == NULL)
199 throw ModError("Mod:\"" + mod_name + "\" lacks init.lua");
201 verbosestream << "Loading and running script " << display_filename << std::endl;
203 lua_State *L = getStack();
205 int error_handler = PUSH_ERROR_HANDLER(L);
207 bool ok = ScriptApiSecurity::safeLoadFile(L, init_filename->c_str(), display_filename.c_str());
209 ok = !lua_pcall(L, 0, 0, error_handler);
211 std::string error_msg = luaL_checkstring(L, -1);
212 lua_pop(L, 2); // Pop error message and error handler
213 throw ModError("Failed to load and run mod \"" +
214 mod_name + "\":\n" + error_msg);
216 lua_pop(L, 1); // Pop error handler
220 // Push the list of callbacks (a lua table).
221 // Then push nargs arguments.
222 // Then call this function, which
223 // - runs the callbacks
224 // - replaces the table and arguments with the return value,
225 // computed depending on mode
226 // This function must only be called with scriptlock held (i.e. inside of a
227 // code block with SCRIPTAPI_PRECHECKHEADER declared)
228 void ScriptApiBase::runCallbacksRaw(int nargs,
229 RunCallbacksMode mode, const char *fxn)
231 #ifdef SCRIPTAPI_LOCK_DEBUG
232 assert(m_lock_recursion_count > 0);
234 lua_State *L = getStack();
235 FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
237 // Insert error handler
238 PUSH_ERROR_HANDLER(L);
239 int error_handler = lua_gettop(L) - nargs - 1;
240 lua_insert(L, error_handler);
242 // Insert run_callbacks between error handler and table
243 lua_getglobal(L, "core");
244 lua_getfield(L, -1, "run_callbacks");
246 lua_insert(L, error_handler + 1);
248 // Insert mode after table
249 lua_pushnumber(L, (int)mode);
250 lua_insert(L, error_handler + 3);
252 // Stack now looks like this:
253 // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
255 int result = lua_pcall(L, nargs + 2, 1, error_handler);
257 scriptError(result, fxn);
259 lua_remove(L, error_handler);
262 void ScriptApiBase::realityCheck()
264 int top = lua_gettop(m_luastack);
266 dstream << "Stack is over 30:" << std::endl;
268 std::string traceback = script_get_backtrace(m_luastack);
269 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
273 void ScriptApiBase::scriptError(int result, const char *fxn)
275 script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
278 void ScriptApiBase::stackDump(std::ostream &o)
280 int top = lua_gettop(m_luastack);
281 for (int i = 1; i <= top; i++) { /* repeat for each level */
282 int t = lua_type(m_luastack, i);
284 case LUA_TSTRING: /* strings */
285 o << "\"" << lua_tostring(m_luastack, i) << "\"";
287 case LUA_TBOOLEAN: /* booleans */
288 o << (lua_toboolean(m_luastack, i) ? "true" : "false");
290 case LUA_TNUMBER: /* numbers */ {
292 snprintf(buf, 10, "%lf", lua_tonumber(m_luastack, i));
296 default: /* other values */
297 o << lua_typename(m_luastack, t);
305 void ScriptApiBase::setOriginDirect(const char *origin)
307 m_last_run_mod = origin ? origin : "??";
310 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
312 #ifdef SCRIPTAPI_DEBUG
313 lua_State *L = getStack();
315 m_last_run_mod = lua_istable(L, index) ?
316 getstringfield_default(L, index, "mod_origin", "") : "";
317 //printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str());
321 void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
323 SCRIPTAPI_PRECHECKHEADER
324 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
326 // Create object on stack
327 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
328 int object = lua_gettop(L);
330 // Get core.object_refs table
331 lua_getglobal(L, "core");
332 lua_getfield(L, -1, "object_refs");
333 luaL_checktype(L, -1, LUA_TTABLE);
334 int objectstable = lua_gettop(L);
336 // object_refs[id] = object
337 lua_pushnumber(L, cobj->getId()); // Push id
338 lua_pushvalue(L, object); // Copy object to top of stack
339 lua_settable(L, objectstable);
342 void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
344 SCRIPTAPI_PRECHECKHEADER
345 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
347 // Get core.object_refs table
348 lua_getglobal(L, "core");
349 lua_getfield(L, -1, "object_refs");
350 luaL_checktype(L, -1, LUA_TTABLE);
351 int objectstable = lua_gettop(L);
353 // Get object_refs[id]
354 lua_pushnumber(L, cobj->getId()); // Push id
355 lua_gettable(L, objectstable);
356 // Set object reference to NULL
357 ObjectRef::set_null(L);
358 lua_pop(L, 1); // pop object
360 // Set object_refs[id] = nil
361 lua_pushnumber(L, cobj->getId()); // Push id
363 lua_settable(L, objectstable);
366 // Creates a new anonymous reference if cobj=NULL or id=0
367 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
368 ServerActiveObject *cobj)
370 if (cobj == NULL || cobj->getId() == 0) {
371 ObjectRef::create(L, cobj);
373 push_objectRef(L, cobj->getId());
375 warningstream << "ScriptApiBase::objectrefGetOrCreate(): "
376 << "Pushing ObjectRef to removed/deactivated object"
377 << ", this is probably a bug." << std::endl;
381 Server* ScriptApiBase::getServer()
383 return dynamic_cast<Server *>(m_gamedef);
386 Client* ScriptApiBase::getClient()
388 return dynamic_cast<Client *>(m_gamedef);