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"
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 << lua_tostring(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 = lua_tostring(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 const std::string *init_filename = getClient()->getModFile(mod_name + ":init.lua");
201 const std::string display_filename = mod_name + ":init.lua";
202 if(init_filename == NULL)
203 throw ModError("Mod:\"" + mod_name + "\" lacks init.lua");
205 verbosestream << "Loading and running script " << display_filename << std::endl;
207 lua_State *L = getStack();
209 int error_handler = PUSH_ERROR_HANDLER(L);
211 bool ok = ScriptApiSecurity::safeLoadFile(L, init_filename->c_str(), display_filename.c_str());
213 ok = !lua_pcall(L, 0, 0, error_handler);
215 std::string error_msg = luaL_checkstring(L, -1);
216 lua_pop(L, 2); // Pop error message and error handler
217 throw ModError("Failed to load and run mod \"" +
218 mod_name + "\":\n" + error_msg);
220 lua_pop(L, 1); // Pop error handler
224 // Push the list of callbacks (a lua table).
225 // Then push nargs arguments.
226 // Then call this function, which
227 // - runs the callbacks
228 // - replaces the table and arguments with the return value,
229 // computed depending on mode
230 // This function must only be called with scriptlock held (i.e. inside of a
231 // code block with SCRIPTAPI_PRECHECKHEADER declared)
232 void ScriptApiBase::runCallbacksRaw(int nargs,
233 RunCallbacksMode mode, const char *fxn)
235 #ifdef SCRIPTAPI_LOCK_DEBUG
236 assert(m_lock_recursion_count > 0);
238 lua_State *L = getStack();
239 FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
241 // Insert error handler
242 PUSH_ERROR_HANDLER(L);
243 int error_handler = lua_gettop(L) - nargs - 1;
244 lua_insert(L, error_handler);
246 // Insert run_callbacks between error handler and table
247 lua_getglobal(L, "core");
248 lua_getfield(L, -1, "run_callbacks");
250 lua_insert(L, error_handler + 1);
252 // Insert mode after table
253 lua_pushnumber(L, (int)mode);
254 lua_insert(L, error_handler + 3);
256 // Stack now looks like this:
257 // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
259 int result = lua_pcall(L, nargs + 2, 1, error_handler);
261 scriptError(result, fxn);
263 lua_remove(L, error_handler);
266 void ScriptApiBase::realityCheck()
268 int top = lua_gettop(m_luastack);
270 dstream << "Stack is over 30:" << std::endl;
272 std::string traceback = script_get_backtrace(m_luastack);
273 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
277 void ScriptApiBase::scriptError(int result, const char *fxn)
279 script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
282 void ScriptApiBase::stackDump(std::ostream &o)
284 int top = lua_gettop(m_luastack);
285 for (int i = 1; i <= top; i++) { /* repeat for each level */
286 int t = lua_type(m_luastack, i);
288 case LUA_TSTRING: /* strings */
289 o << "\"" << lua_tostring(m_luastack, i) << "\"";
291 case LUA_TBOOLEAN: /* booleans */
292 o << (lua_toboolean(m_luastack, i) ? "true" : "false");
294 case LUA_TNUMBER: /* numbers */ {
296 snprintf(buf, 10, "%lf", lua_tonumber(m_luastack, i));
300 default: /* other values */
301 o << lua_typename(m_luastack, t);
309 void ScriptApiBase::setOriginDirect(const char *origin)
311 m_last_run_mod = origin ? origin : "??";
314 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
316 #ifdef SCRIPTAPI_DEBUG
317 lua_State *L = getStack();
319 m_last_run_mod = lua_istable(L, index) ?
320 getstringfield_default(L, index, "mod_origin", "") : "";
321 //printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str());
325 void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
327 SCRIPTAPI_PRECHECKHEADER
328 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
330 // Create object on stack
331 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
332 int object = lua_gettop(L);
334 // Get core.object_refs table
335 lua_getglobal(L, "core");
336 lua_getfield(L, -1, "object_refs");
337 luaL_checktype(L, -1, LUA_TTABLE);
338 int objectstable = lua_gettop(L);
340 // object_refs[id] = object
341 lua_pushnumber(L, cobj->getId()); // Push id
342 lua_pushvalue(L, object); // Copy object to top of stack
343 lua_settable(L, objectstable);
346 void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
348 SCRIPTAPI_PRECHECKHEADER
349 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
351 // Get core.object_refs table
352 lua_getglobal(L, "core");
353 lua_getfield(L, -1, "object_refs");
354 luaL_checktype(L, -1, LUA_TTABLE);
355 int objectstable = lua_gettop(L);
357 // Get object_refs[id]
358 lua_pushnumber(L, cobj->getId()); // Push id
359 lua_gettable(L, objectstable);
360 // Set object reference to NULL
361 ObjectRef::set_null(L);
362 lua_pop(L, 1); // pop object
364 // Set object_refs[id] = nil
365 lua_pushnumber(L, cobj->getId()); // Push id
367 lua_settable(L, objectstable);
370 // Creates a new anonymous reference if cobj=NULL or id=0
371 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
372 ServerActiveObject *cobj)
374 if (cobj == NULL || cobj->getId() == 0) {
375 ObjectRef::create(L, cobj);
377 push_objectRef(L, cobj->getId());
379 warningstream << "ScriptApiBase::objectrefGetOrCreate(): "
380 << "Pushing ObjectRef to removed/deactivated object"
381 << ", this is probably a bug." << std::endl;
385 void ScriptApiBase::pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeReason &reason)
387 if (reason.lua_reference >= 0) {
388 lua_rawgeti(L, LUA_REGISTRYINDEX, reason.lua_reference);
389 luaL_unref(L, LUA_REGISTRYINDEX, reason.lua_reference);
393 lua_pushstring(L, reason.getTypeAsString().c_str());
394 lua_setfield(L, -2, "type");
396 lua_pushstring(L, reason.from_mod ? "mod" : "engine");
397 lua_setfield(L, -2, "from");
400 objectrefGetOrCreate(L, reason.object);
401 lua_setfield(L, -2, "object");
405 Server* ScriptApiBase::getServer()
407 return dynamic_cast<Server *>(m_gamedef);
410 Client* ScriptApiBase::getClient()
412 return dynamic_cast<Client *>(m_gamedef);