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"
47 #include "script/common/c_content.h"
56 ModNameStorer(lua_State *L_, const std::string &mod_name):
59 // Store current mod name in registry
60 lua_pushstring(L, mod_name.c_str());
61 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
65 // Clear current mod name from registry
67 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
76 ScriptApiBase::ScriptApiBase(ScriptingType type):
79 #ifdef SCRIPTAPI_LOCK_DEBUG
80 m_lock_recursion_count = 0;
83 m_luastack = luaL_newstate();
84 FATAL_ERROR_IF(!m_luastack, "luaL_newstate() failed");
86 lua_atpanic(m_luastack, &luaPanic);
88 if (m_type == ScriptingType::Client)
89 clientOpenLibs(m_luastack);
91 luaL_openlibs(m_luastack);
94 lua_pushcfunction(m_luastack, luaopen_bit);
95 lua_pushstring(m_luastack, LUA_BITLIBNAME);
96 lua_call(m_luastack, 1, 0);
98 // Make the ScriptApiBase* accessible to ModApiBase
99 #if INDIRECT_SCRIPTAPI_RIDX
100 *(void **)(lua_newuserdata(m_luastack, sizeof(void *))) = this;
102 lua_pushlightuserdata(m_luastack, this);
104 lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
106 // Add and save an error handler
107 lua_getglobal(m_luastack, "debug");
108 lua_getfield(m_luastack, -1, "traceback");
109 lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_BACKTRACE);
110 lua_pop(m_luastack, 1); // pop debug
112 // Add a C++ wrapper function to catch exceptions thrown in Lua -> C++ calls
114 lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper);
115 luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
116 lua_pop(m_luastack, 1);
118 // (This is a custom API from the bundled Lua.)
119 lua_atccall(m_luastack, script_exception_wrapper);
125 lua_newtable(m_luastack);
126 // Populate with some internal functions which will be removed in Lua:
127 lua_pushcfunction(m_luastack, [](lua_State *L) -> int {
128 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_READ_VECTOR);
131 lua_setfield(m_luastack, -2, "set_read_vector");
132 lua_pushcfunction(m_luastack, [](lua_State *L) -> int {
133 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_PUSH_VECTOR);
136 lua_setfield(m_luastack, -2, "set_push_vector");
137 lua_pushcfunction(m_luastack, [](lua_State *L) -> int {
138 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_READ_NODE);
141 lua_setfield(m_luastack, -2, "set_read_node");
142 lua_pushcfunction(m_luastack, [](lua_State *L) -> int {
143 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_PUSH_NODE);
146 lua_setfield(m_luastack, -2, "set_push_node");
147 // Finally, put the table into the global environment:
148 lua_setglobal(m_luastack, "core");
150 if (m_type == ScriptingType::Client)
151 lua_pushstring(m_luastack, "/");
153 lua_pushstring(m_luastack, DIR_DELIM);
154 lua_setglobal(m_luastack, "DIR_DELIM");
156 lua_pushstring(m_luastack, porting::getPlatformName());
157 lua_setglobal(m_luastack, "PLATFORM");
159 // Make sure Lua uses the right locale
160 setlocale(LC_NUMERIC, "C");
163 ScriptApiBase::~ScriptApiBase()
165 lua_close(m_luastack);
168 int ScriptApiBase::luaPanic(lua_State *L)
170 std::ostringstream oss;
171 oss << "LUA PANIC: unprotected error in call to Lua API ("
172 << readParam<std::string>(L, -1) << ")";
173 FATAL_ERROR(oss.str().c_str());
178 void ScriptApiBase::clientOpenLibs(lua_State *L)
180 static const std::vector<std::pair<std::string, lua_CFunction>> m_libs = {
181 { "", luaopen_base },
182 { LUA_TABLIBNAME, luaopen_table },
183 { LUA_OSLIBNAME, luaopen_os },
184 { LUA_STRLIBNAME, luaopen_string },
185 { LUA_MATHLIBNAME, luaopen_math },
186 { LUA_DBLIBNAME, luaopen_debug },
188 { LUA_JITLIBNAME, luaopen_jit },
192 for (const auto &lib : m_libs) {
193 lua_pushcfunction(L, lib.second);
194 lua_pushstring(L, lib.first.c_str());
199 void ScriptApiBase::checkSetByBuiltin()
201 lua_State *L = getStack();
204 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_READ_VECTOR);
205 FATAL_ERROR_IF(lua_type(L, -1) != LUA_TFUNCTION, "missing read_vector");
208 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_PUSH_VECTOR);
209 FATAL_ERROR_IF(lua_type(L, -1) != LUA_TFUNCTION, "missing push_vector");
212 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_READ_NODE);
213 FATAL_ERROR_IF(lua_type(L, -1) != LUA_TFUNCTION, "missing read_node");
216 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_PUSH_NODE);
217 FATAL_ERROR_IF(lua_type(L, -1) != LUA_TFUNCTION, "missing push_node");
222 void ScriptApiBase::loadMod(const std::string &script_path,
223 const std::string &mod_name)
225 ModNameStorer mod_name_storer(getStack(), mod_name);
227 loadScript(script_path);
230 void ScriptApiBase::loadScript(const std::string &script_path)
232 verbosestream << "Loading and running script from " << script_path << std::endl;
234 lua_State *L = getStack();
236 int error_handler = PUSH_ERROR_HANDLER(L);
240 ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
242 ok = !luaL_loadfile(L, script_path.c_str());
244 ok = ok && !lua_pcall(L, 0, 0, error_handler);
246 const char *error_msg = lua_tostring(L, -1);
248 error_msg = "(error object is not a string)";
249 lua_pop(L, 2); // Pop error message and error handler
250 throw ModError("Failed to load and run script from " +
251 script_path + ":\n" + error_msg);
253 lua_pop(L, 1); // Pop error handler
257 void ScriptApiBase::loadModFromMemory(const std::string &mod_name)
259 ModNameStorer mod_name_storer(getStack(), mod_name);
261 sanity_check(m_type == ScriptingType::Client);
263 const std::string init_filename = mod_name + ":init.lua";
264 const std::string chunk_name = "@" + init_filename;
266 const std::string *contents = getClient()->getModFile(init_filename);
268 throw ModError("Mod \"" + mod_name + "\" lacks init.lua");
270 verbosestream << "Loading and running script " << chunk_name << std::endl;
272 lua_State *L = getStack();
274 int error_handler = PUSH_ERROR_HANDLER(L);
276 bool ok = ScriptApiSecurity::safeLoadString(L, *contents, chunk_name.c_str());
278 ok = !lua_pcall(L, 0, 0, error_handler);
280 const char *error_msg = lua_tostring(L, -1);
282 error_msg = "(error object is not a string)";
283 lua_pop(L, 2); // Pop error message and error handler
284 throw ModError("Failed to load and run mod \"" +
285 mod_name + "\":\n" + error_msg);
287 lua_pop(L, 1); // Pop error handler
291 // Push the list of callbacks (a lua table).
292 // Then push nargs arguments.
293 // Then call this function, which
294 // - runs the callbacks
295 // - replaces the table and arguments with the return value,
296 // computed depending on mode
297 // This function must only be called with scriptlock held (i.e. inside of a
298 // code block with SCRIPTAPI_PRECHECKHEADER declared)
299 void ScriptApiBase::runCallbacksRaw(int nargs,
300 RunCallbacksMode mode, const char *fxn)
303 // Hard fail for bad guarded callbacks
304 // Only run callbacks when the scripting enviroment is loaded
305 FATAL_ERROR_IF(m_type == ScriptingType::Client &&
306 !getClient()->modsLoaded(), fxn);
309 #ifdef SCRIPTAPI_LOCK_DEBUG
310 assert(m_lock_recursion_count > 0);
312 lua_State *L = getStack();
313 FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
315 // Insert error handler
316 PUSH_ERROR_HANDLER(L);
317 int error_handler = lua_gettop(L) - nargs - 1;
318 lua_insert(L, error_handler);
320 // Insert run_callbacks between error handler and table
321 lua_getglobal(L, "core");
322 lua_getfield(L, -1, "run_callbacks");
324 lua_insert(L, error_handler + 1);
326 // Insert mode after table
327 lua_pushnumber(L, (int)mode);
328 lua_insert(L, error_handler + 3);
330 // Stack now looks like this:
331 // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
333 int result = lua_pcall(L, nargs + 2, 1, error_handler);
335 scriptError(result, fxn);
337 lua_remove(L, error_handler);
340 void ScriptApiBase::realityCheck()
342 int top = lua_gettop(m_luastack);
344 dstream << "Stack is over 30:" << std::endl;
346 std::string traceback = script_get_backtrace(m_luastack);
347 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
351 void ScriptApiBase::scriptError(int result, const char *fxn)
353 script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
356 void ScriptApiBase::stackDump(std::ostream &o)
358 int top = lua_gettop(m_luastack);
359 for (int i = 1; i <= top; i++) { /* repeat for each level */
360 int t = lua_type(m_luastack, i);
362 case LUA_TSTRING: /* strings */
363 o << "\"" << readParam<std::string>(m_luastack, i) << "\"";
365 case LUA_TBOOLEAN: /* booleans */
366 o << (readParam<bool>(m_luastack, i) ? "true" : "false");
368 case LUA_TNUMBER: /* numbers */ {
370 porting::mt_snprintf(buf, sizeof(buf), "%lf", lua_tonumber(m_luastack, i));
374 default: /* other values */
375 o << lua_typename(m_luastack, t);
383 void ScriptApiBase::setOriginDirect(const char *origin)
385 m_last_run_mod = origin ? origin : "??";
388 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
390 lua_State *L = getStack();
391 m_last_run_mod = lua_istable(L, index) ?
392 getstringfield_default(L, index, "mod_origin", "") : "";
396 * How ObjectRefs are handled in Lua:
397 * When an active object is created, an ObjectRef is created on the Lua side
398 * and stored in core.object_refs[id].
399 * Methods that require an ObjectRef to a certain object retrieve it from that
400 * table instead of creating their own.(*)
401 * When an active object is removed, the existing ObjectRef is invalidated
402 * using ::set_null() and removed from the core.object_refs table.
403 * (*) An exception to this are NULL ObjectRefs and anonymous ObjectRefs
404 * for objects without ID.
405 * It's unclear what the latter are needed for and their use is problematic
406 * since we lose control over the ref and the contained pointer.
409 void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
411 SCRIPTAPI_PRECHECKHEADER
412 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
414 // Create object on stack
415 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
416 int object = lua_gettop(L);
418 // Get core.object_refs table
419 lua_getglobal(L, "core");
420 lua_getfield(L, -1, "object_refs");
421 luaL_checktype(L, -1, LUA_TTABLE);
422 int objectstable = lua_gettop(L);
424 // object_refs[id] = object
425 lua_pushnumber(L, cobj->getId()); // Push id
426 lua_pushvalue(L, object); // Copy object to top of stack
427 lua_settable(L, objectstable);
430 void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
432 SCRIPTAPI_PRECHECKHEADER
433 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
435 // Get core.object_refs table
436 lua_getglobal(L, "core");
437 lua_getfield(L, -1, "object_refs");
438 luaL_checktype(L, -1, LUA_TTABLE);
439 int objectstable = lua_gettop(L);
441 // Get object_refs[id]
442 lua_pushnumber(L, cobj->getId()); // Push id
443 lua_gettable(L, objectstable);
444 // Set object reference to NULL
445 ObjectRef::set_null(L);
446 lua_pop(L, 1); // pop object
448 // Set object_refs[id] = nil
449 lua_pushnumber(L, cobj->getId()); // Push id
451 lua_settable(L, objectstable);
454 // Creates a new anonymous reference if cobj=NULL or id=0
455 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
456 ServerActiveObject *cobj)
458 if (cobj == NULL || cobj->getId() == 0) {
459 ObjectRef::create(L, cobj);
461 push_objectRef(L, cobj->getId());
463 warningstream << "ScriptApiBase::objectrefGetOrCreate(): "
464 << "Pushing ObjectRef to removed/deactivated object"
465 << ", this is probably a bug." << std::endl;
469 void ScriptApiBase::pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeReason &reason)
471 if (reason.hasLuaReference())
472 lua_rawgeti(L, LUA_REGISTRYINDEX, reason.lua_reference);
476 lua_getfield(L, -1, "type");
477 bool has_type = (bool)lua_isstring(L, -1);
480 lua_pushstring(L, reason.getTypeAsString().c_str());
481 lua_setfield(L, -2, "type");
484 lua_pushstring(L, reason.from_mod ? "mod" : "engine");
485 lua_setfield(L, -2, "from");
488 objectrefGetOrCreate(L, reason.object);
489 lua_setfield(L, -2, "object");
491 if (!reason.node.empty()) {
492 lua_pushstring(L, reason.node.c_str());
493 lua_setfield(L, -2, "node");
497 Server* ScriptApiBase::getServer()
499 return dynamic_cast<Server *>(m_gamedef);
502 Client* ScriptApiBase::getClient()
504 return dynamic_cast<Client *>(m_gamedef);