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");
122 // Make sure Lua uses the right locale
123 setlocale(LC_NUMERIC, "C");
126 ScriptApiBase::~ScriptApiBase()
128 lua_close(m_luastack);
131 int ScriptApiBase::luaPanic(lua_State *L)
133 std::ostringstream oss;
134 oss << "LUA PANIC: unprotected error in call to Lua API ("
135 << lua_tostring(L, -1) << ")";
136 FATAL_ERROR(oss.str().c_str());
141 void ScriptApiBase::clientOpenLibs(lua_State *L)
143 static const std::vector<std::pair<std::string, lua_CFunction>> m_libs = {
144 { "", luaopen_base },
145 { LUA_TABLIBNAME, luaopen_table },
146 { LUA_OSLIBNAME, luaopen_os },
147 { LUA_STRLIBNAME, luaopen_string },
148 { LUA_MATHLIBNAME, luaopen_math },
149 { LUA_DBLIBNAME, luaopen_debug },
151 { LUA_JITLIBNAME, luaopen_jit },
155 for (const std::pair<std::string, lua_CFunction> &lib : m_libs) {
156 lua_pushcfunction(L, lib.second);
157 lua_pushstring(L, lib.first.c_str());
162 void ScriptApiBase::loadMod(const std::string &script_path,
163 const std::string &mod_name)
165 ModNameStorer mod_name_storer(getStack(), mod_name);
167 loadScript(script_path);
170 void ScriptApiBase::loadScript(const std::string &script_path)
172 verbosestream << "Loading and running script from " << script_path << std::endl;
174 lua_State *L = getStack();
176 int error_handler = PUSH_ERROR_HANDLER(L);
180 ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
182 ok = !luaL_loadfile(L, script_path.c_str());
184 ok = ok && !lua_pcall(L, 0, 0, error_handler);
186 std::string error_msg = lua_tostring(L, -1);
187 lua_pop(L, 2); // Pop error message and error handler
188 throw ModError("Failed to load and run script from " +
189 script_path + ":\n" + error_msg);
191 lua_pop(L, 1); // Pop error handler
195 void ScriptApiBase::loadModFromMemory(const std::string &mod_name)
197 ModNameStorer mod_name_storer(getStack(), mod_name);
199 const std::string *init_filename = getClient()->getModFile(mod_name + ":init.lua");
200 const std::string display_filename = mod_name + ":init.lua";
201 if(init_filename == NULL)
202 throw ModError("Mod:\"" + mod_name + "\" lacks init.lua");
204 verbosestream << "Loading and running script " << display_filename << std::endl;
206 lua_State *L = getStack();
208 int error_handler = PUSH_ERROR_HANDLER(L);
210 bool ok = ScriptApiSecurity::safeLoadFile(L, init_filename->c_str(), display_filename.c_str());
212 ok = !lua_pcall(L, 0, 0, error_handler);
214 std::string error_msg = luaL_checkstring(L, -1);
215 lua_pop(L, 2); // Pop error message and error handler
216 throw ModError("Failed to load and run mod \"" +
217 mod_name + "\":\n" + error_msg);
219 lua_pop(L, 1); // Pop error handler
223 // Push the list of callbacks (a lua table).
224 // Then push nargs arguments.
225 // Then call this function, which
226 // - runs the callbacks
227 // - replaces the table and arguments with the return value,
228 // computed depending on mode
229 // This function must only be called with scriptlock held (i.e. inside of a
230 // code block with SCRIPTAPI_PRECHECKHEADER declared)
231 void ScriptApiBase::runCallbacksRaw(int nargs,
232 RunCallbacksMode mode, const char *fxn)
234 #ifdef SCRIPTAPI_LOCK_DEBUG
235 assert(m_lock_recursion_count > 0);
237 lua_State *L = getStack();
238 FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
240 // Insert error handler
241 PUSH_ERROR_HANDLER(L);
242 int error_handler = lua_gettop(L) - nargs - 1;
243 lua_insert(L, error_handler);
245 // Insert run_callbacks between error handler and table
246 lua_getglobal(L, "core");
247 lua_getfield(L, -1, "run_callbacks");
249 lua_insert(L, error_handler + 1);
251 // Insert mode after table
252 lua_pushnumber(L, (int)mode);
253 lua_insert(L, error_handler + 3);
255 // Stack now looks like this:
256 // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
258 int result = lua_pcall(L, nargs + 2, 1, error_handler);
260 scriptError(result, fxn);
262 lua_remove(L, error_handler);
265 void ScriptApiBase::realityCheck()
267 int top = lua_gettop(m_luastack);
269 dstream << "Stack is over 30:" << std::endl;
271 std::string traceback = script_get_backtrace(m_luastack);
272 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
276 void ScriptApiBase::scriptError(int result, const char *fxn)
278 script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
281 void ScriptApiBase::stackDump(std::ostream &o)
283 int top = lua_gettop(m_luastack);
284 for (int i = 1; i <= top; i++) { /* repeat for each level */
285 int t = lua_type(m_luastack, i);
287 case LUA_TSTRING: /* strings */
288 o << "\"" << lua_tostring(m_luastack, i) << "\"";
290 case LUA_TBOOLEAN: /* booleans */
291 o << (lua_toboolean(m_luastack, i) ? "true" : "false");
293 case LUA_TNUMBER: /* numbers */ {
295 snprintf(buf, 10, "%lf", lua_tonumber(m_luastack, i));
299 default: /* other values */
300 o << lua_typename(m_luastack, t);
308 void ScriptApiBase::setOriginDirect(const char *origin)
310 m_last_run_mod = origin ? origin : "??";
313 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
315 #ifdef SCRIPTAPI_DEBUG
316 lua_State *L = getStack();
318 m_last_run_mod = lua_istable(L, index) ?
319 getstringfield_default(L, index, "mod_origin", "") : "";
320 //printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str());
324 void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
326 SCRIPTAPI_PRECHECKHEADER
327 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
329 // Create object on stack
330 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
331 int object = lua_gettop(L);
333 // Get core.object_refs table
334 lua_getglobal(L, "core");
335 lua_getfield(L, -1, "object_refs");
336 luaL_checktype(L, -1, LUA_TTABLE);
337 int objectstable = lua_gettop(L);
339 // object_refs[id] = object
340 lua_pushnumber(L, cobj->getId()); // Push id
341 lua_pushvalue(L, object); // Copy object to top of stack
342 lua_settable(L, objectstable);
345 void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
347 SCRIPTAPI_PRECHECKHEADER
348 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
350 // Get core.object_refs table
351 lua_getglobal(L, "core");
352 lua_getfield(L, -1, "object_refs");
353 luaL_checktype(L, -1, LUA_TTABLE);
354 int objectstable = lua_gettop(L);
356 // Get object_refs[id]
357 lua_pushnumber(L, cobj->getId()); // Push id
358 lua_gettable(L, objectstable);
359 // Set object reference to NULL
360 ObjectRef::set_null(L);
361 lua_pop(L, 1); // pop object
363 // Set object_refs[id] = nil
364 lua_pushnumber(L, cobj->getId()); // Push id
366 lua_settable(L, objectstable);
369 // Creates a new anonymous reference if cobj=NULL or id=0
370 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
371 ServerActiveObject *cobj)
373 if (cobj == NULL || cobj->getId() == 0) {
374 ObjectRef::create(L, cobj);
376 push_objectRef(L, cobj->getId());
378 warningstream << "ScriptApiBase::objectrefGetOrCreate(): "
379 << "Pushing ObjectRef to removed/deactivated object"
380 << ", this is probably a bug." << std::endl;
384 Server* ScriptApiBase::getServer()
386 return dynamic_cast<Server *>(m_gamedef);
389 Client* ScriptApiBase::getClient()
391 return dynamic_cast<Client *>(m_gamedef);