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 "server/player_sao.h"
27 #include "content/mods.h"
29 #include "util/string.h"
32 #include "client/client.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 #if INDIRECT_SCRIPTAPI_RIDX
93 *(void **)(lua_newuserdata(m_luastack, sizeof(void *))) = this;
95 lua_pushlightuserdata(m_luastack, this);
97 lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
99 // Add and save an error handler
100 lua_getglobal(m_luastack, "debug");
101 lua_getfield(m_luastack, -1, "traceback");
102 lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_BACKTRACE);
103 lua_pop(m_luastack, 1); // pop debug
105 // If we are using LuaJIT add a C++ wrapper function to catch
106 // exceptions thrown in Lua -> C++ calls
108 lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper);
109 luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
110 lua_pop(m_luastack, 1);
114 lua_newtable(m_luastack);
115 lua_setglobal(m_luastack, "core");
117 if (m_type == ScriptingType::Client)
118 lua_pushstring(m_luastack, "/");
120 lua_pushstring(m_luastack, DIR_DELIM);
121 lua_setglobal(m_luastack, "DIR_DELIM");
123 lua_pushstring(m_luastack, porting::getPlatformName());
124 lua_setglobal(m_luastack, "PLATFORM");
126 // Make sure Lua uses the right locale
127 setlocale(LC_NUMERIC, "C");
130 ScriptApiBase::~ScriptApiBase()
132 lua_close(m_luastack);
135 int ScriptApiBase::luaPanic(lua_State *L)
137 std::ostringstream oss;
138 oss << "LUA PANIC: unprotected error in call to Lua API ("
139 << readParam<std::string>(L, -1) << ")";
140 FATAL_ERROR(oss.str().c_str());
145 void ScriptApiBase::clientOpenLibs(lua_State *L)
147 static const std::vector<std::pair<std::string, lua_CFunction>> m_libs = {
148 { "", luaopen_base },
149 { LUA_TABLIBNAME, luaopen_table },
150 { LUA_OSLIBNAME, luaopen_os },
151 { LUA_STRLIBNAME, luaopen_string },
152 { LUA_MATHLIBNAME, luaopen_math },
153 { LUA_DBLIBNAME, luaopen_debug },
155 { LUA_JITLIBNAME, luaopen_jit },
159 for (const std::pair<std::string, lua_CFunction> &lib : m_libs) {
160 lua_pushcfunction(L, lib.second);
161 lua_pushstring(L, lib.first.c_str());
166 void ScriptApiBase::loadMod(const std::string &script_path,
167 const std::string &mod_name)
169 ModNameStorer mod_name_storer(getStack(), mod_name);
171 loadScript(script_path);
174 void ScriptApiBase::loadScript(const std::string &script_path)
176 verbosestream << "Loading and running script from " << script_path << std::endl;
178 lua_State *L = getStack();
180 int error_handler = PUSH_ERROR_HANDLER(L);
184 ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
186 ok = !luaL_loadfile(L, script_path.c_str());
188 ok = ok && !lua_pcall(L, 0, 0, error_handler);
190 const char *error_msg = lua_tostring(L, -1);
192 error_msg = "(error object is not a string)";
193 lua_pop(L, 2); // Pop error message and error handler
194 throw ModError("Failed to load and run script from " +
195 script_path + ":\n" + error_msg);
197 lua_pop(L, 1); // Pop error handler
201 void ScriptApiBase::loadModFromMemory(const std::string &mod_name)
203 ModNameStorer mod_name_storer(getStack(), mod_name);
205 sanity_check(m_type == ScriptingType::Client);
207 const std::string init_filename = mod_name + ":init.lua";
208 const std::string chunk_name = "@" + init_filename;
210 const std::string *contents = getClient()->getModFile(init_filename);
212 throw ModError("Mod \"" + mod_name + "\" lacks init.lua");
214 verbosestream << "Loading and running script " << chunk_name << std::endl;
216 lua_State *L = getStack();
218 int error_handler = PUSH_ERROR_HANDLER(L);
220 bool ok = ScriptApiSecurity::safeLoadString(L, *contents, chunk_name.c_str());
222 ok = !lua_pcall(L, 0, 0, error_handler);
224 const char *error_msg = lua_tostring(L, -1);
226 error_msg = "(error object is not a string)";
227 lua_pop(L, 2); // Pop error message and error handler
228 throw ModError("Failed to load and run mod \"" +
229 mod_name + "\":\n" + error_msg);
231 lua_pop(L, 1); // Pop error handler
235 // Push the list of callbacks (a lua table).
236 // Then push nargs arguments.
237 // Then call this function, which
238 // - runs the callbacks
239 // - replaces the table and arguments with the return value,
240 // computed depending on mode
241 // This function must only be called with scriptlock held (i.e. inside of a
242 // code block with SCRIPTAPI_PRECHECKHEADER declared)
243 void ScriptApiBase::runCallbacksRaw(int nargs,
244 RunCallbacksMode mode, const char *fxn)
247 // Hard fail for bad guarded callbacks
248 // Only run callbacks when the scripting enviroment is loaded
249 FATAL_ERROR_IF(m_type == ScriptingType::Client &&
250 !getClient()->modsLoaded(), fxn);
253 #ifdef SCRIPTAPI_LOCK_DEBUG
254 assert(m_lock_recursion_count > 0);
256 lua_State *L = getStack();
257 FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
259 // Insert error handler
260 PUSH_ERROR_HANDLER(L);
261 int error_handler = lua_gettop(L) - nargs - 1;
262 lua_insert(L, error_handler);
264 // Insert run_callbacks between error handler and table
265 lua_getglobal(L, "core");
266 lua_getfield(L, -1, "run_callbacks");
268 lua_insert(L, error_handler + 1);
270 // Insert mode after table
271 lua_pushnumber(L, (int)mode);
272 lua_insert(L, error_handler + 3);
274 // Stack now looks like this:
275 // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
277 int result = lua_pcall(L, nargs + 2, 1, error_handler);
279 scriptError(result, fxn);
281 lua_remove(L, error_handler);
284 void ScriptApiBase::realityCheck()
286 int top = lua_gettop(m_luastack);
288 dstream << "Stack is over 30:" << std::endl;
290 std::string traceback = script_get_backtrace(m_luastack);
291 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
295 void ScriptApiBase::scriptError(int result, const char *fxn)
297 script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
300 void ScriptApiBase::stackDump(std::ostream &o)
302 int top = lua_gettop(m_luastack);
303 for (int i = 1; i <= top; i++) { /* repeat for each level */
304 int t = lua_type(m_luastack, i);
306 case LUA_TSTRING: /* strings */
307 o << "\"" << readParam<std::string>(m_luastack, i) << "\"";
309 case LUA_TBOOLEAN: /* booleans */
310 o << (readParam<bool>(m_luastack, i) ? "true" : "false");
312 case LUA_TNUMBER: /* numbers */ {
314 porting::mt_snprintf(buf, sizeof(buf), "%lf", lua_tonumber(m_luastack, i));
318 default: /* other values */
319 o << lua_typename(m_luastack, t);
327 void ScriptApiBase::setOriginDirect(const char *origin)
329 m_last_run_mod = origin ? origin : "??";
332 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
334 #ifdef SCRIPTAPI_DEBUG
335 lua_State *L = getStack();
337 m_last_run_mod = lua_istable(L, index) ?
338 getstringfield_default(L, index, "mod_origin", "") : "";
339 //printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str());
344 * How ObjectRefs are handled in Lua:
345 * When an active object is created, an ObjectRef is created on the Lua side
346 * and stored in core.object_refs[id].
347 * Methods that require an ObjectRef to a certain object retrieve it from that
348 * table instead of creating their own.(*)
349 * When an active object is removed, the existing ObjectRef is invalidated
350 * using ::set_null() and removed from the core.object_refs table.
351 * (*) An exception to this are NULL ObjectRefs and anonymous ObjectRefs
352 * for objects without ID.
353 * It's unclear what the latter are needed for and their use is problematic
354 * since we lose control over the ref and the contained pointer.
357 void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
359 SCRIPTAPI_PRECHECKHEADER
360 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
362 // Create object on stack
363 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
364 int object = lua_gettop(L);
366 // Get core.object_refs table
367 lua_getglobal(L, "core");
368 lua_getfield(L, -1, "object_refs");
369 luaL_checktype(L, -1, LUA_TTABLE);
370 int objectstable = lua_gettop(L);
372 // object_refs[id] = object
373 lua_pushnumber(L, cobj->getId()); // Push id
374 lua_pushvalue(L, object); // Copy object to top of stack
375 lua_settable(L, objectstable);
378 void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
380 SCRIPTAPI_PRECHECKHEADER
381 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
383 // Get core.object_refs table
384 lua_getglobal(L, "core");
385 lua_getfield(L, -1, "object_refs");
386 luaL_checktype(L, -1, LUA_TTABLE);
387 int objectstable = lua_gettop(L);
389 // Get object_refs[id]
390 lua_pushnumber(L, cobj->getId()); // Push id
391 lua_gettable(L, objectstable);
392 // Set object reference to NULL
393 ObjectRef::set_null(L);
394 lua_pop(L, 1); // pop object
396 // Set object_refs[id] = nil
397 lua_pushnumber(L, cobj->getId()); // Push id
399 lua_settable(L, objectstable);
402 // Creates a new anonymous reference if cobj=NULL or id=0
403 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
404 ServerActiveObject *cobj)
406 if (cobj == NULL || cobj->getId() == 0) {
407 ObjectRef::create(L, cobj);
409 push_objectRef(L, cobj->getId());
411 warningstream << "ScriptApiBase::objectrefGetOrCreate(): "
412 << "Pushing ObjectRef to removed/deactivated object"
413 << ", this is probably a bug." << std::endl;
417 void ScriptApiBase::pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeReason &reason)
419 if (reason.hasLuaReference())
420 lua_rawgeti(L, LUA_REGISTRYINDEX, reason.lua_reference);
424 lua_getfield(L, -1, "type");
425 bool has_type = (bool)lua_isstring(L, -1);
428 lua_pushstring(L, reason.getTypeAsString().c_str());
429 lua_setfield(L, -2, "type");
432 lua_pushstring(L, reason.from_mod ? "mod" : "engine");
433 lua_setfield(L, -2, "from");
436 objectrefGetOrCreate(L, reason.object);
437 lua_setfield(L, -2, "object");
439 if (!reason.node.empty()) {
440 lua_pushstring(L, reason.node.c_str());
441 lua_setfield(L, -2, "node");
445 Server* ScriptApiBase::getServer()
447 return dynamic_cast<Server *>(m_gamedef);
450 Client* ScriptApiBase::getClient()
452 return dynamic_cast<Client *>(m_gamedef);