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 // If we are using LuaJIT add a C++ wrapper function to catch
113 // exceptions thrown in Lua -> C++ calls
115 lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper);
116 luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
117 lua_pop(m_luastack, 1);
121 lua_newtable(m_luastack);
122 lua_setglobal(m_luastack, "core");
124 // vector.metatable is stored in the registry for quick access from C++.
125 lua_newtable(m_luastack);
126 lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_VECTOR_METATABLE);
127 lua_newtable(m_luastack);
128 lua_rawgeti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_VECTOR_METATABLE);
129 lua_setfield(m_luastack, -2, "metatable");
130 lua_setglobal(m_luastack, "vector");
132 if (m_type == ScriptingType::Client)
133 lua_pushstring(m_luastack, "/");
135 lua_pushstring(m_luastack, DIR_DELIM);
136 lua_setglobal(m_luastack, "DIR_DELIM");
138 lua_pushstring(m_luastack, porting::getPlatformName());
139 lua_setglobal(m_luastack, "PLATFORM");
141 // Make sure Lua uses the right locale
142 setlocale(LC_NUMERIC, "C");
145 ScriptApiBase::~ScriptApiBase()
147 lua_close(m_luastack);
150 int ScriptApiBase::luaPanic(lua_State *L)
152 std::ostringstream oss;
153 oss << "LUA PANIC: unprotected error in call to Lua API ("
154 << readParam<std::string>(L, -1) << ")";
155 FATAL_ERROR(oss.str().c_str());
160 void ScriptApiBase::clientOpenLibs(lua_State *L)
162 static const std::vector<std::pair<std::string, lua_CFunction>> m_libs = {
163 { "", luaopen_base },
164 { LUA_TABLIBNAME, luaopen_table },
165 { LUA_OSLIBNAME, luaopen_os },
166 { LUA_STRLIBNAME, luaopen_string },
167 { LUA_MATHLIBNAME, luaopen_math },
168 { LUA_DBLIBNAME, luaopen_debug },
170 { LUA_JITLIBNAME, luaopen_jit },
174 for (const std::pair<std::string, lua_CFunction> &lib : m_libs) {
175 lua_pushcfunction(L, lib.second);
176 lua_pushstring(L, lib.first.c_str());
181 void ScriptApiBase::loadMod(const std::string &script_path,
182 const std::string &mod_name)
184 ModNameStorer mod_name_storer(getStack(), mod_name);
186 loadScript(script_path);
189 void ScriptApiBase::loadScript(const std::string &script_path)
191 verbosestream << "Loading and running script from " << script_path << std::endl;
193 lua_State *L = getStack();
195 int error_handler = PUSH_ERROR_HANDLER(L);
199 ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
201 ok = !luaL_loadfile(L, script_path.c_str());
203 ok = ok && !lua_pcall(L, 0, 0, error_handler);
205 const char *error_msg = lua_tostring(L, -1);
207 error_msg = "(error object is not a string)";
208 lua_pop(L, 2); // Pop error message and error handler
209 throw ModError("Failed to load and run script from " +
210 script_path + ":\n" + error_msg);
212 lua_pop(L, 1); // Pop error handler
216 void ScriptApiBase::loadModFromMemory(const std::string &mod_name)
218 ModNameStorer mod_name_storer(getStack(), mod_name);
220 sanity_check(m_type == ScriptingType::Client);
222 const std::string init_filename = mod_name + ":init.lua";
223 const std::string chunk_name = "@" + init_filename;
225 const std::string *contents = getClient()->getModFile(init_filename);
227 throw ModError("Mod \"" + mod_name + "\" lacks init.lua");
229 verbosestream << "Loading and running script " << chunk_name << std::endl;
231 lua_State *L = getStack();
233 int error_handler = PUSH_ERROR_HANDLER(L);
235 bool ok = ScriptApiSecurity::safeLoadString(L, *contents, chunk_name.c_str());
237 ok = !lua_pcall(L, 0, 0, error_handler);
239 const char *error_msg = lua_tostring(L, -1);
241 error_msg = "(error object is not a string)";
242 lua_pop(L, 2); // Pop error message and error handler
243 throw ModError("Failed to load and run mod \"" +
244 mod_name + "\":\n" + error_msg);
246 lua_pop(L, 1); // Pop error handler
250 // Push the list of callbacks (a lua table).
251 // Then push nargs arguments.
252 // Then call this function, which
253 // - runs the callbacks
254 // - replaces the table and arguments with the return value,
255 // computed depending on mode
256 // This function must only be called with scriptlock held (i.e. inside of a
257 // code block with SCRIPTAPI_PRECHECKHEADER declared)
258 void ScriptApiBase::runCallbacksRaw(int nargs,
259 RunCallbacksMode mode, const char *fxn)
262 // Hard fail for bad guarded callbacks
263 // Only run callbacks when the scripting enviroment is loaded
264 FATAL_ERROR_IF(m_type == ScriptingType::Client &&
265 !getClient()->modsLoaded(), fxn);
268 #ifdef SCRIPTAPI_LOCK_DEBUG
269 assert(m_lock_recursion_count > 0);
271 lua_State *L = getStack();
272 FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
274 // Insert error handler
275 PUSH_ERROR_HANDLER(L);
276 int error_handler = lua_gettop(L) - nargs - 1;
277 lua_insert(L, error_handler);
279 // Insert run_callbacks between error handler and table
280 lua_getglobal(L, "core");
281 lua_getfield(L, -1, "run_callbacks");
283 lua_insert(L, error_handler + 1);
285 // Insert mode after table
286 lua_pushnumber(L, (int)mode);
287 lua_insert(L, error_handler + 3);
289 // Stack now looks like this:
290 // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
292 int result = lua_pcall(L, nargs + 2, 1, error_handler);
294 scriptError(result, fxn);
296 lua_remove(L, error_handler);
299 void ScriptApiBase::realityCheck()
301 int top = lua_gettop(m_luastack);
303 dstream << "Stack is over 30:" << std::endl;
305 std::string traceback = script_get_backtrace(m_luastack);
306 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
310 void ScriptApiBase::scriptError(int result, const char *fxn)
312 script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
315 void ScriptApiBase::stackDump(std::ostream &o)
317 int top = lua_gettop(m_luastack);
318 for (int i = 1; i <= top; i++) { /* repeat for each level */
319 int t = lua_type(m_luastack, i);
321 case LUA_TSTRING: /* strings */
322 o << "\"" << readParam<std::string>(m_luastack, i) << "\"";
324 case LUA_TBOOLEAN: /* booleans */
325 o << (readParam<bool>(m_luastack, i) ? "true" : "false");
327 case LUA_TNUMBER: /* numbers */ {
329 porting::mt_snprintf(buf, sizeof(buf), "%lf", lua_tonumber(m_luastack, i));
333 default: /* other values */
334 o << lua_typename(m_luastack, t);
342 void ScriptApiBase::setOriginDirect(const char *origin)
344 m_last_run_mod = origin ? origin : "??";
347 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
349 lua_State *L = getStack();
350 m_last_run_mod = lua_istable(L, index) ?
351 getstringfield_default(L, index, "mod_origin", "") : "";
355 * How ObjectRefs are handled in Lua:
356 * When an active object is created, an ObjectRef is created on the Lua side
357 * and stored in core.object_refs[id].
358 * Methods that require an ObjectRef to a certain object retrieve it from that
359 * table instead of creating their own.(*)
360 * When an active object is removed, the existing ObjectRef is invalidated
361 * using ::set_null() and removed from the core.object_refs table.
362 * (*) An exception to this are NULL ObjectRefs and anonymous ObjectRefs
363 * for objects without ID.
364 * It's unclear what the latter are needed for and their use is problematic
365 * since we lose control over the ref and the contained pointer.
368 void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
370 SCRIPTAPI_PRECHECKHEADER
371 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
373 // Create object on stack
374 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
375 int object = lua_gettop(L);
377 // Get core.object_refs table
378 lua_getglobal(L, "core");
379 lua_getfield(L, -1, "object_refs");
380 luaL_checktype(L, -1, LUA_TTABLE);
381 int objectstable = lua_gettop(L);
383 // object_refs[id] = object
384 lua_pushnumber(L, cobj->getId()); // Push id
385 lua_pushvalue(L, object); // Copy object to top of stack
386 lua_settable(L, objectstable);
389 void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
391 SCRIPTAPI_PRECHECKHEADER
392 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
394 // Get core.object_refs table
395 lua_getglobal(L, "core");
396 lua_getfield(L, -1, "object_refs");
397 luaL_checktype(L, -1, LUA_TTABLE);
398 int objectstable = lua_gettop(L);
400 // Get object_refs[id]
401 lua_pushnumber(L, cobj->getId()); // Push id
402 lua_gettable(L, objectstable);
403 // Set object reference to NULL
404 ObjectRef::set_null(L);
405 lua_pop(L, 1); // pop object
407 // Set object_refs[id] = nil
408 lua_pushnumber(L, cobj->getId()); // Push id
410 lua_settable(L, objectstable);
413 // Creates a new anonymous reference if cobj=NULL or id=0
414 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
415 ServerActiveObject *cobj)
417 if (cobj == NULL || cobj->getId() == 0) {
418 ObjectRef::create(L, cobj);
420 push_objectRef(L, cobj->getId());
422 warningstream << "ScriptApiBase::objectrefGetOrCreate(): "
423 << "Pushing ObjectRef to removed/deactivated object"
424 << ", this is probably a bug." << std::endl;
428 void ScriptApiBase::pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeReason &reason)
430 if (reason.hasLuaReference())
431 lua_rawgeti(L, LUA_REGISTRYINDEX, reason.lua_reference);
435 lua_getfield(L, -1, "type");
436 bool has_type = (bool)lua_isstring(L, -1);
439 lua_pushstring(L, reason.getTypeAsString().c_str());
440 lua_setfield(L, -2, "type");
443 lua_pushstring(L, reason.from_mod ? "mod" : "engine");
444 lua_setfield(L, -2, "from");
447 objectrefGetOrCreate(L, reason.object);
448 lua_setfield(L, -2, "object");
450 if (!reason.node.empty()) {
451 lua_pushstring(L, reason.node.c_str());
452 lua_setfield(L, -2, "node");
456 Server* ScriptApiBase::getServer()
458 return dynamic_cast<Server *>(m_gamedef);
461 Client* ScriptApiBase::getClient()
463 return dynamic_cast<Client *>(m_gamedef);