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 lua_pushcfunction(m_luastack, script_error_handler);
107 lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_ERROR_HANDLER);
109 // Add a C++ wrapper function to catch exceptions thrown in Lua -> C++ calls
111 lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper);
112 luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
113 lua_pop(m_luastack, 1);
115 // (This is a custom API from the bundled Lua.)
116 lua_atccall(m_luastack, script_exception_wrapper);
122 lua_newtable(m_luastack);
123 // Populate with some internal functions which will be removed in Lua:
124 lua_pushcfunction(m_luastack, [](lua_State *L) -> int {
125 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_READ_VECTOR);
128 lua_setfield(m_luastack, -2, "set_read_vector");
129 lua_pushcfunction(m_luastack, [](lua_State *L) -> int {
130 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_PUSH_VECTOR);
133 lua_setfield(m_luastack, -2, "set_push_vector");
134 lua_pushcfunction(m_luastack, [](lua_State *L) -> int {
135 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_READ_NODE);
138 lua_setfield(m_luastack, -2, "set_read_node");
139 lua_pushcfunction(m_luastack, [](lua_State *L) -> int {
140 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_PUSH_NODE);
143 lua_setfield(m_luastack, -2, "set_push_node");
144 // Finally, put the table into the global environment:
145 lua_setglobal(m_luastack, "core");
147 if (m_type == ScriptingType::Client)
148 lua_pushstring(m_luastack, "/");
150 lua_pushstring(m_luastack, DIR_DELIM);
151 lua_setglobal(m_luastack, "DIR_DELIM");
153 lua_pushstring(m_luastack, porting::getPlatformName());
154 lua_setglobal(m_luastack, "PLATFORM");
156 // Make sure Lua uses the right locale
157 setlocale(LC_NUMERIC, "C");
160 ScriptApiBase::~ScriptApiBase()
162 lua_close(m_luastack);
165 int ScriptApiBase::luaPanic(lua_State *L)
167 std::ostringstream oss;
168 oss << "LUA PANIC: unprotected error in call to Lua API ("
169 << readParam<std::string>(L, -1) << ")";
170 FATAL_ERROR(oss.str().c_str());
175 void ScriptApiBase::clientOpenLibs(lua_State *L)
177 static const std::vector<std::pair<std::string, lua_CFunction>> m_libs = {
178 { "", luaopen_base },
179 { LUA_TABLIBNAME, luaopen_table },
180 { LUA_OSLIBNAME, luaopen_os },
181 { LUA_STRLIBNAME, luaopen_string },
182 { LUA_MATHLIBNAME, luaopen_math },
183 { LUA_DBLIBNAME, luaopen_debug },
185 { LUA_JITLIBNAME, luaopen_jit },
189 for (const auto &lib : m_libs) {
190 lua_pushcfunction(L, lib.second);
191 lua_pushstring(L, lib.first.c_str());
196 void ScriptApiBase::checkSetByBuiltin()
198 lua_State *L = getStack();
201 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_READ_VECTOR);
202 FATAL_ERROR_IF(lua_type(L, -1) != LUA_TFUNCTION, "missing read_vector");
205 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_PUSH_VECTOR);
206 FATAL_ERROR_IF(lua_type(L, -1) != LUA_TFUNCTION, "missing push_vector");
209 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_READ_NODE);
210 FATAL_ERROR_IF(lua_type(L, -1) != LUA_TFUNCTION, "missing read_node");
213 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_PUSH_NODE);
214 FATAL_ERROR_IF(lua_type(L, -1) != LUA_TFUNCTION, "missing push_node");
219 void ScriptApiBase::loadMod(const std::string &script_path,
220 const std::string &mod_name)
222 ModNameStorer mod_name_storer(getStack(), mod_name);
224 loadScript(script_path);
227 void ScriptApiBase::loadScript(const std::string &script_path)
229 verbosestream << "Loading and running script from " << script_path << std::endl;
231 lua_State *L = getStack();
233 int error_handler = PUSH_ERROR_HANDLER(L);
237 ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
239 ok = !luaL_loadfile(L, script_path.c_str());
241 ok = ok && !lua_pcall(L, 0, 0, error_handler);
243 const char *error_msg = lua_tostring(L, -1);
245 error_msg = "(error object is not a string)";
246 lua_pop(L, 2); // Pop error message and error handler
247 throw ModError("Failed to load and run script from " +
248 script_path + ":\n" + error_msg);
250 lua_pop(L, 1); // Pop error handler
254 void ScriptApiBase::loadModFromMemory(const std::string &mod_name)
256 ModNameStorer mod_name_storer(getStack(), mod_name);
258 sanity_check(m_type == ScriptingType::Client);
260 const std::string init_filename = mod_name + ":init.lua";
261 const std::string chunk_name = "@" + init_filename;
263 const std::string *contents = getClient()->getModFile(init_filename);
265 throw ModError("Mod \"" + mod_name + "\" lacks init.lua");
267 verbosestream << "Loading and running script " << chunk_name << std::endl;
269 lua_State *L = getStack();
271 int error_handler = PUSH_ERROR_HANDLER(L);
273 bool ok = ScriptApiSecurity::safeLoadString(L, *contents, chunk_name.c_str());
275 ok = !lua_pcall(L, 0, 0, error_handler);
277 const char *error_msg = lua_tostring(L, -1);
279 error_msg = "(error object is not a string)";
280 lua_pop(L, 2); // Pop error message and error handler
281 throw ModError("Failed to load and run mod \"" +
282 mod_name + "\":\n" + error_msg);
284 lua_pop(L, 1); // Pop error handler
288 // Push the list of callbacks (a lua table).
289 // Then push nargs arguments.
290 // Then call this function, which
291 // - runs the callbacks
292 // - replaces the table and arguments with the return value,
293 // computed depending on mode
294 // This function must only be called with scriptlock held (i.e. inside of a
295 // code block with SCRIPTAPI_PRECHECKHEADER declared)
296 void ScriptApiBase::runCallbacksRaw(int nargs,
297 RunCallbacksMode mode, const char *fxn)
300 // Hard fail for bad guarded callbacks
301 // Only run callbacks when the scripting enviroment is loaded
302 FATAL_ERROR_IF(m_type == ScriptingType::Client &&
303 !getClient()->modsLoaded(), fxn);
306 #ifdef SCRIPTAPI_LOCK_DEBUG
307 assert(m_lock_recursion_count > 0);
309 lua_State *L = getStack();
310 FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
312 // Insert error handler
313 PUSH_ERROR_HANDLER(L);
314 int error_handler = lua_gettop(L) - nargs - 1;
315 lua_insert(L, error_handler);
317 // Insert run_callbacks between error handler and table
318 lua_getglobal(L, "core");
319 lua_getfield(L, -1, "run_callbacks");
321 lua_insert(L, error_handler + 1);
323 // Insert mode after table
324 lua_pushnumber(L, (int)mode);
325 lua_insert(L, error_handler + 3);
327 // Stack now looks like this:
328 // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
330 int result = lua_pcall(L, nargs + 2, 1, error_handler);
332 scriptError(result, fxn);
334 lua_remove(L, error_handler);
337 void ScriptApiBase::realityCheck()
339 int top = lua_gettop(m_luastack);
341 dstream << "Stack is over 30:" << std::endl;
343 std::string traceback = script_get_backtrace(m_luastack);
344 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
348 void ScriptApiBase::scriptError(int result, const char *fxn)
350 script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
353 void ScriptApiBase::stackDump(std::ostream &o)
355 int top = lua_gettop(m_luastack);
356 for (int i = 1; i <= top; i++) { /* repeat for each level */
357 int t = lua_type(m_luastack, i);
359 case LUA_TSTRING: /* strings */
360 o << "\"" << readParam<std::string>(m_luastack, i) << "\"";
362 case LUA_TBOOLEAN: /* booleans */
363 o << (readParam<bool>(m_luastack, i) ? "true" : "false");
365 case LUA_TNUMBER: /* numbers */ {
367 porting::mt_snprintf(buf, sizeof(buf), "%lf", lua_tonumber(m_luastack, i));
371 default: /* other values */
372 o << lua_typename(m_luastack, t);
380 void ScriptApiBase::setOriginDirect(const char *origin)
382 m_last_run_mod = origin ? origin : "??";
385 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
387 lua_State *L = getStack();
388 m_last_run_mod = lua_istable(L, index) ?
389 getstringfield_default(L, index, "mod_origin", "") : "";
393 * How ObjectRefs are handled in Lua:
394 * When an active object is created, an ObjectRef is created on the Lua side
395 * and stored in core.object_refs[id].
396 * Methods that require an ObjectRef to a certain object retrieve it from that
397 * table instead of creating their own.(*)
398 * When an active object is removed, the existing ObjectRef is invalidated
399 * using ::set_null() and removed from the core.object_refs table.
400 * (*) An exception to this are NULL ObjectRefs and anonymous ObjectRefs
401 * for objects without ID.
402 * It's unclear what the latter are needed for and their use is problematic
403 * since we lose control over the ref and the contained pointer.
406 void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
408 SCRIPTAPI_PRECHECKHEADER
409 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
411 // Create object on stack
412 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
413 int object = lua_gettop(L);
415 // Get core.object_refs table
416 lua_getglobal(L, "core");
417 lua_getfield(L, -1, "object_refs");
418 luaL_checktype(L, -1, LUA_TTABLE);
419 int objectstable = lua_gettop(L);
421 // object_refs[id] = object
422 lua_pushnumber(L, cobj->getId()); // Push id
423 lua_pushvalue(L, object); // Copy object to top of stack
424 lua_settable(L, objectstable);
427 void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
429 SCRIPTAPI_PRECHECKHEADER
430 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
432 // Get core.object_refs table
433 lua_getglobal(L, "core");
434 lua_getfield(L, -1, "object_refs");
435 luaL_checktype(L, -1, LUA_TTABLE);
436 int objectstable = lua_gettop(L);
438 // Get object_refs[id]
439 lua_pushnumber(L, cobj->getId()); // Push id
440 lua_gettable(L, objectstable);
441 // Set object reference to NULL
442 ObjectRef::set_null(L);
443 lua_pop(L, 1); // pop object
445 // Set object_refs[id] = nil
446 lua_pushnumber(L, cobj->getId()); // Push id
448 lua_settable(L, objectstable);
451 // Creates a new anonymous reference if cobj=NULL or id=0
452 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
453 ServerActiveObject *cobj)
455 if (cobj == NULL || cobj->getId() == 0) {
456 ObjectRef::create(L, cobj);
458 push_objectRef(L, cobj->getId());
460 warningstream << "ScriptApiBase::objectrefGetOrCreate(): "
461 << "Pushing ObjectRef to removed/deactivated object"
462 << ", this is probably a bug." << std::endl;
466 void ScriptApiBase::pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeReason &reason)
468 if (reason.hasLuaReference())
469 lua_rawgeti(L, LUA_REGISTRYINDEX, reason.lua_reference);
473 lua_getfield(L, -1, "type");
474 bool has_type = (bool)lua_isstring(L, -1);
477 lua_pushstring(L, reason.getTypeAsString().c_str());
478 lua_setfield(L, -2, "type");
481 lua_pushstring(L, reason.from_mod ? "mod" : "engine");
482 lua_setfield(L, -2, "from");
485 objectrefGetOrCreate(L, reason.object);
486 lua_setfield(L, -2, "object");
488 if (!reason.node.empty()) {
489 lua_pushstring(L, reason.node.c_str());
490 lua_setfield(L, -2, "node");
494 Server* ScriptApiBase::getServer()
496 return dynamic_cast<Server *>(m_gamedef);
499 Client* ScriptApiBase::getClient()
501 return dynamic_cast<Client *>(m_gamedef);