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"
48 #include "script/common/c_content.h"
57 ModNameStorer(lua_State *L_, const std::string &mod_name):
60 // Store current mod name in registry
61 lua_pushstring(L, mod_name.c_str());
62 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
66 // Clear current mod name from registry
68 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
77 ScriptApiBase::ScriptApiBase(ScriptingType type):
80 #ifdef SCRIPTAPI_LOCK_DEBUG
81 m_lock_recursion_count = 0;
84 m_luastack = luaL_newstate();
85 FATAL_ERROR_IF(!m_luastack, "luaL_newstate() failed");
87 lua_atpanic(m_luastack, &luaPanic);
89 /*if (m_type == ScriptingType::Client)
90 clientOpenLibs(m_luastack);
92 luaL_openlibs(m_luastack);
95 lua_pushcfunction(m_luastack, luaopen_bit);
96 lua_pushstring(m_luastack, LUA_BITLIBNAME);
97 lua_call(m_luastack, 1, 0);
99 // Make the ScriptApiBase* accessible to ModApiBase
100 #if INDIRECT_SCRIPTAPI_RIDX
101 *(void **)(lua_newuserdata(m_luastack, sizeof(void *))) = this;
103 lua_pushlightuserdata(m_luastack, this);
105 lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
107 // Add and save an error handler
108 lua_getglobal(m_luastack, "debug");
109 lua_getfield(m_luastack, -1, "traceback");
110 lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_BACKTRACE);
111 lua_pop(m_luastack, 1); // pop debug
113 // If we are using LuaJIT add a C++ wrapper function to catch
114 // exceptions thrown in Lua -> C++ calls
116 lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper);
117 luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
118 lua_pop(m_luastack, 1);
122 lua_newtable(m_luastack);
123 lua_setglobal(m_luastack, "core");
125 // vector.metatable is stored in the registry for quick access from C++.
126 lua_newtable(m_luastack);
127 lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_VECTOR_METATABLE);
128 lua_newtable(m_luastack);
129 lua_rawgeti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_VECTOR_METATABLE);
130 lua_setfield(m_luastack, -2, "metatable");
131 lua_setglobal(m_luastack, "vector");
133 if (m_type == ScriptingType::Client)
134 lua_pushstring(m_luastack, "/");
136 lua_pushstring(m_luastack, DIR_DELIM);
137 lua_setglobal(m_luastack, "DIR_DELIM");
139 lua_pushstring(m_luastack, porting::getPlatformName());
140 lua_setglobal(m_luastack, "PLATFORM");
142 // Make sure Lua uses the right locale
143 setlocale(LC_NUMERIC, "C");
146 ScriptApiBase::~ScriptApiBase()
148 lua_close(m_luastack);
151 int ScriptApiBase::luaPanic(lua_State *L)
153 std::ostringstream oss;
154 oss << "LUA PANIC: unprotected error in call to Lua API ("
155 << readParam<std::string>(L, -1) << ")";
156 FATAL_ERROR(oss.str().c_str());
161 void ScriptApiBase::clientOpenLibs(lua_State *L)
163 static const std::vector<std::pair<std::string, lua_CFunction>> m_libs = {
164 { "", luaopen_base },
165 { LUA_TABLIBNAME, luaopen_table },
166 { LUA_OSLIBNAME, luaopen_os },
167 { LUA_STRLIBNAME, luaopen_string },
168 { LUA_MATHLIBNAME, luaopen_math },
169 { LUA_DBLIBNAME, luaopen_debug },
171 { LUA_JITLIBNAME, luaopen_jit },
175 for (const std::pair<std::string, lua_CFunction> &lib : m_libs) {
176 lua_pushcfunction(L, lib.second);
177 lua_pushstring(L, lib.first.c_str());
182 void ScriptApiBase::loadMod(const std::string &script_path,
183 const std::string &mod_name)
185 ModNameStorer mod_name_storer(getStack(), mod_name);
187 loadScript(script_path);
190 void ScriptApiBase::loadScript(const std::string &script_path)
192 verbosestream << "Loading and running script from " << script_path << std::endl;
194 lua_State *L = getStack();
196 int error_handler = PUSH_ERROR_HANDLER(L);
200 ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
202 ok = !luaL_loadfile(L, script_path.c_str());
204 ok = ok && !lua_pcall(L, 0, 0, error_handler);
206 const char *error_msg = lua_tostring(L, -1);
208 error_msg = "(error object is not a string)";
209 lua_pop(L, 2); // Pop error message and error handler
210 throw ModError("Failed to load and run script from " +
211 script_path + ":\n" + error_msg);
213 lua_pop(L, 1); // Pop error handler
217 void ScriptApiBase::loadModFromMemory(const std::string &mod_name)
219 ModNameStorer mod_name_storer(getStack(), mod_name);
221 sanity_check(m_type == ScriptingType::Client);
223 const std::string init_filename = mod_name + ":init.lua";
224 const std::string chunk_name = "@" + init_filename;
226 const std::string *contents = getClient()->getModFile(init_filename);
228 throw ModError("Mod \"" + mod_name + "\" lacks init.lua");
230 verbosestream << "Loading and running script " << chunk_name << std::endl;
232 lua_State *L = getStack();
234 int error_handler = PUSH_ERROR_HANDLER(L);
236 bool ok = ScriptApiSecurity::safeLoadString(L, *contents, chunk_name.c_str());
238 ok = !lua_pcall(L, 0, 0, error_handler);
240 const char *error_msg = lua_tostring(L, -1);
242 error_msg = "(error object is not a string)";
243 lua_pop(L, 2); // Pop error message and error handler
244 throw ModError("Failed to load and run mod \"" +
245 mod_name + "\":\n" + error_msg);
247 lua_pop(L, 1); // Pop error handler
251 // Push the list of callbacks (a lua table).
252 // Then push nargs arguments.
253 // Then call this function, which
254 // - runs the callbacks
255 // - replaces the table and arguments with the return value,
256 // computed depending on mode
257 // This function must only be called with scriptlock held (i.e. inside of a
258 // code block with SCRIPTAPI_PRECHECKHEADER declared)
259 void ScriptApiBase::runCallbacksRaw(int nargs,
260 RunCallbacksMode mode, const char *fxn)
263 // Hard fail for bad guarded callbacks
264 // Only run callbacks when the scripting enviroment is loaded
265 FATAL_ERROR_IF(m_type == ScriptingType::Client &&
266 !getClient()->modsLoaded(), fxn);
269 #ifdef SCRIPTAPI_LOCK_DEBUG
270 assert(m_lock_recursion_count > 0);
272 lua_State *L = getStack();
273 FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
275 // Insert error handler
276 PUSH_ERROR_HANDLER(L);
277 int error_handler = lua_gettop(L) - nargs - 1;
278 lua_insert(L, error_handler);
280 // Insert run_callbacks between error handler and table
281 lua_getglobal(L, "core");
282 lua_getfield(L, -1, "run_callbacks");
284 lua_insert(L, error_handler + 1);
286 // Insert mode after table
287 lua_pushnumber(L, (int)mode);
288 lua_insert(L, error_handler + 3);
290 // Stack now looks like this:
291 // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
293 int result = lua_pcall(L, nargs + 2, 1, error_handler);
295 scriptError(result, fxn);
297 lua_remove(L, error_handler);
300 void ScriptApiBase::realityCheck()
302 int top = lua_gettop(m_luastack);
304 dstream << "Stack is over 30:" << std::endl;
306 std::string traceback = script_get_backtrace(m_luastack);
307 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
311 void ScriptApiBase::scriptError(int result, const char *fxn)
313 script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
316 void ScriptApiBase::stackDump(std::ostream &o)
318 int top = lua_gettop(m_luastack);
319 for (int i = 1; i <= top; i++) { /* repeat for each level */
320 int t = lua_type(m_luastack, i);
322 case LUA_TSTRING: /* strings */
323 o << "\"" << readParam<std::string>(m_luastack, i) << "\"";
325 case LUA_TBOOLEAN: /* booleans */
326 o << (readParam<bool>(m_luastack, i) ? "true" : "false");
328 case LUA_TNUMBER: /* numbers */ {
330 porting::mt_snprintf(buf, sizeof(buf), "%lf", lua_tonumber(m_luastack, i));
334 default: /* other values */
335 o << lua_typename(m_luastack, t);
343 void ScriptApiBase::setOriginDirect(const char *origin)
345 m_last_run_mod = origin ? origin : "??";
348 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
350 lua_State *L = getStack();
351 m_last_run_mod = lua_istable(L, index) ?
352 getstringfield_default(L, index, "mod_origin", "") : "";
356 * How ObjectRefs are handled in Lua:
357 * When an active object is created, an ObjectRef is created on the Lua side
358 * and stored in core.object_refs[id].
359 * Methods that require an ObjectRef to a certain object retrieve it from that
360 * table instead of creating their own.(*)
361 * When an active object is removed, the existing ObjectRef is invalidated
362 * using ::set_null() and removed from the core.object_refs table.
363 * (*) An exception to this are NULL ObjectRefs and anonymous ObjectRefs
364 * for objects without ID.
365 * It's unclear what the latter are needed for and their use is problematic
366 * since we lose control over the ref and the contained pointer.
369 void ScriptApiBase::addObjectReference(ActiveObject *cobj)
371 SCRIPTAPI_PRECHECKHEADER
372 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
374 // Create object on stack
376 if (m_type == ScriptingType::Client)
377 ClientObjectRef::create(L, dynamic_cast<ClientActiveObject *>(cobj));
380 ObjectRef::create(L, dynamic_cast<ServerActiveObject *>(cobj)); // Puts ObjectRef (as userdata) on stack
381 int object = lua_gettop(L);
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 // object_refs[id] = object
390 lua_pushnumber(L, cobj->getId()); // Push id
391 lua_pushvalue(L, object); // Copy object to top of stack
392 lua_settable(L, objectstable);
395 void ScriptApiBase::removeObjectReference(ActiveObject *cobj)
397 SCRIPTAPI_PRECHECKHEADER
398 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
400 // Get core.object_refs table
401 lua_getglobal(L, "core");
402 lua_getfield(L, -1, "object_refs");
403 luaL_checktype(L, -1, LUA_TTABLE);
404 int objectstable = lua_gettop(L);
406 // Get object_refs[id]
407 lua_pushnumber(L, cobj->getId()); // Push id
408 lua_gettable(L, objectstable);
409 // Set object reference to NULL
411 if (m_type == ScriptingType::Client)
412 ClientObjectRef::set_null(L);
415 ObjectRef::set_null(L);
416 lua_pop(L, 1); // pop object
418 // Set object_refs[id] = nil
419 lua_pushnumber(L, cobj->getId()); // Push id
421 lua_settable(L, objectstable);
424 // Creates a new anonymous reference if cobj=NULL or id=0
425 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
426 ServerActiveObject *cobj)
428 if (cobj == NULL || cobj->getId() == 0) {
429 ObjectRef::create(L, cobj);
431 push_objectRef(L, cobj->getId());
433 warningstream << "ScriptApiBase::objectrefGetOrCreate(): "
434 << "Pushing ObjectRef to removed/deactivated object"
435 << ", this is probably a bug." << std::endl;
438 void ScriptApiBase::pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeReason &reason)
440 if (reason.hasLuaReference())
441 lua_rawgeti(L, LUA_REGISTRYINDEX, reason.lua_reference);
445 lua_getfield(L, -1, "type");
446 bool has_type = (bool)lua_isstring(L, -1);
449 lua_pushstring(L, reason.getTypeAsString().c_str());
450 lua_setfield(L, -2, "type");
453 lua_pushstring(L, reason.from_mod ? "mod" : "engine");
454 lua_setfield(L, -2, "from");
457 objectrefGetOrCreate(L, reason.object);
458 lua_setfield(L, -2, "object");
460 if (!reason.node.empty()) {
461 lua_pushstring(L, reason.node.c_str());
462 lua_setfield(L, -2, "node");
466 Server* ScriptApiBase::getServer()
468 return dynamic_cast<Server *>(m_gamedef);
471 Client* ScriptApiBase::getClient()
473 return dynamic_cast<Client *>(m_gamedef);