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 "lua_api/l_clientobject.h"
25 #include "common/c_converter.h"
26 #include "server/player_sao.h"
28 #include "content/mods.h"
30 #include "util/string.h"
33 #include "client/client.h"
46 #include "script/common/c_content.h"
55 ModNameStorer(lua_State *L_, const std::string &mod_name):
58 // Store current mod name in registry
59 lua_pushstring(L, mod_name.c_str());
60 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
64 // Clear current mod name from registry
66 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
75 ScriptApiBase::ScriptApiBase(ScriptingType type):
78 #ifdef SCRIPTAPI_LOCK_DEBUG
79 m_lock_recursion_count = 0;
82 m_luastack = luaL_newstate();
83 FATAL_ERROR_IF(!m_luastack, "luaL_newstate() failed");
85 lua_atpanic(m_luastack, &luaPanic);
87 /*if (m_type == ScriptingType::Client)
88 clientOpenLibs(m_luastack);
90 luaL_openlibs(m_luastack);
92 // Make the ScriptApiBase* accessible to ModApiBase
93 #if INDIRECT_SCRIPTAPI_RIDX
94 *(void **)(lua_newuserdata(m_luastack, sizeof(void *))) = this;
96 lua_pushlightuserdata(m_luastack, this);
98 lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
100 // Add and save an error handler
101 lua_getglobal(m_luastack, "debug");
102 lua_getfield(m_luastack, -1, "traceback");
103 lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_BACKTRACE);
104 lua_pop(m_luastack, 1); // pop debug
106 // If we are using LuaJIT add a C++ wrapper function to catch
107 // exceptions thrown in Lua -> C++ calls
109 lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper);
110 luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
111 lua_pop(m_luastack, 1);
115 lua_newtable(m_luastack);
116 lua_setglobal(m_luastack, "core");
118 if (m_type == ScriptingType::Client)
119 lua_pushstring(m_luastack, "/");
121 lua_pushstring(m_luastack, DIR_DELIM);
122 lua_setglobal(m_luastack, "DIR_DELIM");
124 lua_pushstring(m_luastack, porting::getPlatformName());
125 lua_setglobal(m_luastack, "PLATFORM");
127 // Make sure Lua uses the right locale
128 setlocale(LC_NUMERIC, "C");
131 ScriptApiBase::~ScriptApiBase()
133 lua_close(m_luastack);
136 int ScriptApiBase::luaPanic(lua_State *L)
138 std::ostringstream oss;
139 oss << "LUA PANIC: unprotected error in call to Lua API ("
140 << readParam<std::string>(L, -1) << ")";
141 FATAL_ERROR(oss.str().c_str());
146 void ScriptApiBase::clientOpenLibs(lua_State *L)
148 static const std::vector<std::pair<std::string, lua_CFunction>> m_libs = {
149 { "", luaopen_base },
150 { LUA_TABLIBNAME, luaopen_table },
151 { LUA_OSLIBNAME, luaopen_os },
152 { LUA_STRLIBNAME, luaopen_string },
153 { LUA_MATHLIBNAME, luaopen_math },
154 { LUA_DBLIBNAME, luaopen_debug },
156 { LUA_JITLIBNAME, luaopen_jit },
160 for (const std::pair<std::string, lua_CFunction> &lib : m_libs) {
161 lua_pushcfunction(L, lib.second);
162 lua_pushstring(L, lib.first.c_str());
167 void ScriptApiBase::loadMod(const std::string &script_path,
168 const std::string &mod_name)
170 ModNameStorer mod_name_storer(getStack(), mod_name);
172 loadScript(script_path);
175 void ScriptApiBase::loadScript(const std::string &script_path)
177 verbosestream << "Loading and running script from " << script_path << std::endl;
179 lua_State *L = getStack();
181 int error_handler = PUSH_ERROR_HANDLER(L);
185 ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
187 ok = !luaL_loadfile(L, script_path.c_str());
189 ok = ok && !lua_pcall(L, 0, 0, error_handler);
191 const char *error_msg = lua_tostring(L, -1);
193 error_msg = "(error object is not a string)";
194 lua_pop(L, 2); // Pop error message and error handler
195 throw ModError("Failed to load and run script from " +
196 script_path + ":\n" + error_msg);
198 lua_pop(L, 1); // Pop error handler
202 void ScriptApiBase::loadModFromMemory(const std::string &mod_name)
204 ModNameStorer mod_name_storer(getStack(), mod_name);
206 sanity_check(m_type == ScriptingType::Client);
208 const std::string init_filename = mod_name + ":init.lua";
209 const std::string chunk_name = "@" + init_filename;
211 const std::string *contents = getClient()->getModFile(init_filename);
213 throw ModError("Mod \"" + mod_name + "\" lacks init.lua");
215 verbosestream << "Loading and running script " << chunk_name << std::endl;
217 lua_State *L = getStack();
219 int error_handler = PUSH_ERROR_HANDLER(L);
221 bool ok = ScriptApiSecurity::safeLoadString(L, *contents, chunk_name.c_str());
223 ok = !lua_pcall(L, 0, 0, error_handler);
225 const char *error_msg = lua_tostring(L, -1);
227 error_msg = "(error object is not a string)";
228 lua_pop(L, 2); // Pop error message and error handler
229 throw ModError("Failed to load and run mod \"" +
230 mod_name + "\":\n" + error_msg);
232 lua_pop(L, 1); // Pop error handler
236 // Push the list of callbacks (a lua table).
237 // Then push nargs arguments.
238 // Then call this function, which
239 // - runs the callbacks
240 // - replaces the table and arguments with the return value,
241 // computed depending on mode
242 // This function must only be called with scriptlock held (i.e. inside of a
243 // code block with SCRIPTAPI_PRECHECKHEADER declared)
244 void ScriptApiBase::runCallbacksRaw(int nargs,
245 RunCallbacksMode mode, const char *fxn)
248 // Hard fail for bad guarded callbacks
249 // Only run callbacks when the scripting enviroment is loaded
250 FATAL_ERROR_IF(m_type == ScriptingType::Client &&
251 !getClient()->modsLoaded(), fxn);
254 #ifdef SCRIPTAPI_LOCK_DEBUG
255 assert(m_lock_recursion_count > 0);
257 lua_State *L = getStack();
258 FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
260 // Insert error handler
261 PUSH_ERROR_HANDLER(L);
262 int error_handler = lua_gettop(L) - nargs - 1;
263 lua_insert(L, error_handler);
265 // Insert run_callbacks between error handler and table
266 lua_getglobal(L, "core");
267 lua_getfield(L, -1, "run_callbacks");
269 lua_insert(L, error_handler + 1);
271 // Insert mode after table
272 lua_pushnumber(L, (int)mode);
273 lua_insert(L, error_handler + 3);
275 // Stack now looks like this:
276 // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
278 int result = lua_pcall(L, nargs + 2, 1, error_handler);
280 scriptError(result, fxn);
282 lua_remove(L, error_handler);
285 void ScriptApiBase::realityCheck()
287 int top = lua_gettop(m_luastack);
289 dstream << "Stack is over 30:" << std::endl;
291 std::string traceback = script_get_backtrace(m_luastack);
292 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
296 void ScriptApiBase::scriptError(int result, const char *fxn)
298 script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
301 void ScriptApiBase::stackDump(std::ostream &o)
303 int top = lua_gettop(m_luastack);
304 for (int i = 1; i <= top; i++) { /* repeat for each level */
305 int t = lua_type(m_luastack, i);
307 case LUA_TSTRING: /* strings */
308 o << "\"" << readParam<std::string>(m_luastack, i) << "\"";
310 case LUA_TBOOLEAN: /* booleans */
311 o << (readParam<bool>(m_luastack, i) ? "true" : "false");
313 case LUA_TNUMBER: /* numbers */ {
315 porting::mt_snprintf(buf, sizeof(buf), "%lf", lua_tonumber(m_luastack, i));
319 default: /* other values */
320 o << lua_typename(m_luastack, t);
328 void ScriptApiBase::setOriginDirect(const char *origin)
330 m_last_run_mod = origin ? origin : "??";
333 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
335 lua_State *L = getStack();
336 m_last_run_mod = lua_istable(L, index) ?
337 getstringfield_default(L, index, "mod_origin", "") : "";
341 * How ObjectRefs are handled in Lua:
342 * When an active object is created, an ObjectRef is created on the Lua side
343 * and stored in core.object_refs[id].
344 * Methods that require an ObjectRef to a certain object retrieve it from that
345 * table instead of creating their own.(*)
346 * When an active object is removed, the existing ObjectRef is invalidated
347 * using ::set_null() and removed from the core.object_refs table.
348 * (*) An exception to this are NULL ObjectRefs and anonymous ObjectRefs
349 * for objects without ID.
350 * It's unclear what the latter are needed for and their use is problematic
351 * since we lose control over the ref and the contained pointer.
354 void ScriptApiBase::addObjectReference(ActiveObject *cobj)
356 SCRIPTAPI_PRECHECKHEADER
357 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
359 // Create object on stack
361 if (m_type == ScriptingType::Client)
362 ClientObjectRef::create(L, dynamic_cast<ClientActiveObject *>(cobj));
365 ObjectRef::create(L, dynamic_cast<ServerActiveObject *>(cobj)); // Puts ObjectRef (as userdata) on stack
366 int object = lua_gettop(L);
368 // Get core.object_refs table
369 lua_getglobal(L, "core");
370 lua_getfield(L, -1, "object_refs");
371 luaL_checktype(L, -1, LUA_TTABLE);
372 int objectstable = lua_gettop(L);
374 // object_refs[id] = object
375 lua_pushnumber(L, cobj->getId()); // Push id
376 lua_pushvalue(L, object); // Copy object to top of stack
377 lua_settable(L, objectstable);
380 void ScriptApiBase::removeObjectReference(ActiveObject *cobj)
382 SCRIPTAPI_PRECHECKHEADER
383 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
385 // Get core.object_refs table
386 lua_getglobal(L, "core");
387 lua_getfield(L, -1, "object_refs");
388 luaL_checktype(L, -1, LUA_TTABLE);
389 int objectstable = lua_gettop(L);
391 // Get object_refs[id]
392 lua_pushnumber(L, cobj->getId()); // Push id
393 lua_gettable(L, objectstable);
394 // Set object reference to NULL
396 if (m_type == ScriptingType::Client)
397 ClientObjectRef::set_null(L);
400 ObjectRef::set_null(L);
401 lua_pop(L, 1); // pop object
403 // Set object_refs[id] = nil
404 lua_pushnumber(L, cobj->getId()); // Push id
406 lua_settable(L, objectstable);
409 // Creates a new anonymous reference if cobj=NULL or id=0
410 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
411 ServerActiveObject *cobj)
413 if (cobj == NULL || cobj->getId() == 0) {
414 ObjectRef::create(L, cobj);
416 push_objectRef(L, cobj->getId());
418 warningstream << "ScriptApiBase::objectrefGetOrCreate(): "
419 << "Pushing ObjectRef to removed/deactivated object"
420 << ", this is probably a bug." << std::endl;
423 void ScriptApiBase::pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeReason &reason)
425 if (reason.hasLuaReference())
426 lua_rawgeti(L, LUA_REGISTRYINDEX, reason.lua_reference);
430 lua_getfield(L, -1, "type");
431 bool has_type = (bool)lua_isstring(L, -1);
434 lua_pushstring(L, reason.getTypeAsString().c_str());
435 lua_setfield(L, -2, "type");
438 lua_pushstring(L, reason.from_mod ? "mod" : "engine");
439 lua_setfield(L, -2, "from");
442 objectrefGetOrCreate(L, reason.object);
443 lua_setfield(L, -2, "object");
445 if (!reason.node.empty()) {
446 lua_pushstring(L, reason.node.c_str());
447 lua_setfield(L, -2, "node");
451 Server* ScriptApiBase::getServer()
453 return dynamic_cast<Server *>(m_gamedef);
456 Client* ScriptApiBase::getClient()
458 return dynamic_cast<Client *>(m_gamedef);