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 "serverobject.h"
27 #include "content/mods.h"
29 #include "util/string.h"
32 #include "client/client.h"
45 #include "script/common/c_content.h"
46 #include "content_sao.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 lua_pushlightuserdata(m_luastack, this);
94 lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
96 // Add and save an error handler
97 lua_getglobal(m_luastack, "debug");
98 lua_getfield(m_luastack, -1, "traceback");
99 lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_BACKTRACE);
100 lua_pop(m_luastack, 1); // pop debug
102 // If we are using LuaJIT add a C++ wrapper function to catch
103 // exceptions thrown in Lua -> C++ calls
105 lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper);
106 luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
107 lua_pop(m_luastack, 1);
111 lua_newtable(m_luastack);
112 lua_setglobal(m_luastack, "core");
114 if (m_type == ScriptingType::Client)
115 lua_pushstring(m_luastack, "/");
117 lua_pushstring(m_luastack, DIR_DELIM);
118 lua_setglobal(m_luastack, "DIR_DELIM");
120 lua_pushstring(m_luastack, porting::getPlatformName());
121 lua_setglobal(m_luastack, "PLATFORM");
123 // Make sure Lua uses the right locale
124 setlocale(LC_NUMERIC, "C");
127 ScriptApiBase::~ScriptApiBase()
129 lua_close(m_luastack);
132 int ScriptApiBase::luaPanic(lua_State *L)
134 std::ostringstream oss;
135 oss << "LUA PANIC: unprotected error in call to Lua API ("
136 << readParam<std::string>(L, -1) << ")";
137 FATAL_ERROR(oss.str().c_str());
142 void ScriptApiBase::clientOpenLibs(lua_State *L)
144 static const std::vector<std::pair<std::string, lua_CFunction>> m_libs = {
145 { "", luaopen_base },
146 { LUA_TABLIBNAME, luaopen_table },
147 { LUA_OSLIBNAME, luaopen_os },
148 { LUA_STRLIBNAME, luaopen_string },
149 { LUA_MATHLIBNAME, luaopen_math },
150 { LUA_DBLIBNAME, luaopen_debug },
152 { LUA_JITLIBNAME, luaopen_jit },
156 for (const std::pair<std::string, lua_CFunction> &lib : m_libs) {
157 lua_pushcfunction(L, lib.second);
158 lua_pushstring(L, lib.first.c_str());
163 void ScriptApiBase::loadMod(const std::string &script_path,
164 const std::string &mod_name)
166 ModNameStorer mod_name_storer(getStack(), mod_name);
168 loadScript(script_path);
171 void ScriptApiBase::loadScript(const std::string &script_path)
173 verbosestream << "Loading and running script from " << script_path << std::endl;
175 lua_State *L = getStack();
177 int error_handler = PUSH_ERROR_HANDLER(L);
181 ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
183 ok = !luaL_loadfile(L, script_path.c_str());
185 ok = ok && !lua_pcall(L, 0, 0, error_handler);
187 std::string error_msg = readParam<std::string>(L, -1);
188 lua_pop(L, 2); // Pop error message and error handler
189 throw ModError("Failed to load and run script from " +
190 script_path + ":\n" + error_msg);
192 lua_pop(L, 1); // Pop error handler
196 void ScriptApiBase::loadModFromMemory(const std::string &mod_name)
198 ModNameStorer mod_name_storer(getStack(), mod_name);
200 sanity_check(m_type == ScriptingType::Client);
202 const std::string init_filename = mod_name + ":init.lua";
203 const std::string chunk_name = "@" + init_filename;
205 const std::string *contents = getClient()->getModFile(init_filename);
207 throw ModError("Mod \"" + mod_name + "\" lacks init.lua");
209 verbosestream << "Loading and running script " << chunk_name << std::endl;
211 lua_State *L = getStack();
213 int error_handler = PUSH_ERROR_HANDLER(L);
215 bool ok = ScriptApiSecurity::safeLoadString(L, *contents, chunk_name.c_str());
217 ok = !lua_pcall(L, 0, 0, error_handler);
219 std::string error_msg = luaL_checkstring(L, -1);
220 lua_pop(L, 2); // Pop error message and error handler
221 throw ModError("Failed to load and run mod \"" +
222 mod_name + "\":\n" + error_msg);
224 lua_pop(L, 1); // Pop error handler
228 // Push the list of callbacks (a lua table).
229 // Then push nargs arguments.
230 // Then call this function, which
231 // - runs the callbacks
232 // - replaces the table and arguments with the return value,
233 // computed depending on mode
234 // This function must only be called with scriptlock held (i.e. inside of a
235 // code block with SCRIPTAPI_PRECHECKHEADER declared)
236 void ScriptApiBase::runCallbacksRaw(int nargs,
237 RunCallbacksMode mode, const char *fxn)
240 // Hard fail for bad guarded callbacks
241 // Only run callbacks when the scripting enviroment is loaded
242 FATAL_ERROR_IF(m_type == ScriptingType::Client &&
243 !getClient()->modsLoaded(), fxn);
246 #ifdef SCRIPTAPI_LOCK_DEBUG
247 assert(m_lock_recursion_count > 0);
249 lua_State *L = getStack();
250 FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
252 // Insert error handler
253 PUSH_ERROR_HANDLER(L);
254 int error_handler = lua_gettop(L) - nargs - 1;
255 lua_insert(L, error_handler);
257 // Insert run_callbacks between error handler and table
258 lua_getglobal(L, "core");
259 lua_getfield(L, -1, "run_callbacks");
261 lua_insert(L, error_handler + 1);
263 // Insert mode after table
264 lua_pushnumber(L, (int)mode);
265 lua_insert(L, error_handler + 3);
267 // Stack now looks like this:
268 // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
270 int result = lua_pcall(L, nargs + 2, 1, error_handler);
272 scriptError(result, fxn);
274 lua_remove(L, error_handler);
277 void ScriptApiBase::realityCheck()
279 int top = lua_gettop(m_luastack);
281 dstream << "Stack is over 30:" << std::endl;
283 std::string traceback = script_get_backtrace(m_luastack);
284 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
288 void ScriptApiBase::scriptError(int result, const char *fxn)
290 script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
293 void ScriptApiBase::stackDump(std::ostream &o)
295 int top = lua_gettop(m_luastack);
296 for (int i = 1; i <= top; i++) { /* repeat for each level */
297 int t = lua_type(m_luastack, i);
299 case LUA_TSTRING: /* strings */
300 o << "\"" << readParam<std::string>(m_luastack, i) << "\"";
302 case LUA_TBOOLEAN: /* booleans */
303 o << (readParam<bool>(m_luastack, i) ? "true" : "false");
305 case LUA_TNUMBER: /* numbers */ {
307 porting::mt_snprintf(buf, sizeof(buf), "%lf", lua_tonumber(m_luastack, i));
311 default: /* other values */
312 o << lua_typename(m_luastack, t);
320 void ScriptApiBase::setOriginDirect(const char *origin)
322 m_last_run_mod = origin ? origin : "??";
325 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
327 #ifdef SCRIPTAPI_DEBUG
328 lua_State *L = getStack();
330 m_last_run_mod = lua_istable(L, index) ?
331 getstringfield_default(L, index, "mod_origin", "") : "";
332 //printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str());
336 void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
338 SCRIPTAPI_PRECHECKHEADER
339 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
341 // Create object on stack
342 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
343 int object = lua_gettop(L);
345 // Get core.object_refs table
346 lua_getglobal(L, "core");
347 lua_getfield(L, -1, "object_refs");
348 luaL_checktype(L, -1, LUA_TTABLE);
349 int objectstable = lua_gettop(L);
351 // object_refs[id] = object
352 lua_pushnumber(L, cobj->getId()); // Push id
353 lua_pushvalue(L, object); // Copy object to top of stack
354 lua_settable(L, objectstable);
357 void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
359 SCRIPTAPI_PRECHECKHEADER
360 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
362 // Get core.object_refs table
363 lua_getglobal(L, "core");
364 lua_getfield(L, -1, "object_refs");
365 luaL_checktype(L, -1, LUA_TTABLE);
366 int objectstable = lua_gettop(L);
368 // Get object_refs[id]
369 lua_pushnumber(L, cobj->getId()); // Push id
370 lua_gettable(L, objectstable);
371 // Set object reference to NULL
372 ObjectRef::set_null(L);
373 lua_pop(L, 1); // pop object
375 // Set object_refs[id] = nil
376 lua_pushnumber(L, cobj->getId()); // Push id
378 lua_settable(L, objectstable);
381 // Creates a new anonymous reference if cobj=NULL or id=0
382 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
383 ServerActiveObject *cobj)
385 if (cobj == NULL || cobj->getId() == 0) {
386 ObjectRef::create(L, cobj);
388 push_objectRef(L, cobj->getId());
390 warningstream << "ScriptApiBase::objectrefGetOrCreate(): "
391 << "Pushing ObjectRef to removed/deactivated object"
392 << ", this is probably a bug." << std::endl;
396 void ScriptApiBase::pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeReason &reason)
398 if (reason.hasLuaReference())
399 lua_rawgeti(L, LUA_REGISTRYINDEX, reason.lua_reference);
403 lua_getfield(L, -1, "type");
404 bool has_type = (bool)lua_isstring(L, -1);
407 lua_pushstring(L, reason.getTypeAsString().c_str());
408 lua_setfield(L, -2, "type");
411 lua_pushstring(L, reason.from_mod ? "mod" : "engine");
412 lua_setfield(L, -2, "from");
415 objectrefGetOrCreate(L, reason.object);
416 lua_setfield(L, -2, "object");
418 if (!reason.node.empty()) {
419 lua_pushstring(L, reason.node.c_str());
420 lua_setfield(L, -2, "node");
424 Server* ScriptApiBase::getServer()
426 return dynamic_cast<Server *>(m_gamedef);
429 Client* ScriptApiBase::getClient()
431 return dynamic_cast<Client *>(m_gamedef);