1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
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"
26 #include "filesys.h"
27 #include "content/mods.h"
28 #include "porting.h"
29 #include "util/string.h"
30 #include "server.h"
31 #ifndef SERVER
32 #include "client/client.h"
33 #endif
34
35
36 extern "C" {
37 #include "lualib.h"
38 #if USE_LUAJIT
39 #include "luajit.h"
40 #endif
41 }
42
43 #include <cstdio>
44 #include <cstdarg>
45 #include "script/common/c_content.h"
46 #include <sstream>
47
48
49 class ModNameStorer
50 {
51 private:
52 lua_State *L;
53 public:
ModNameStorer(lua_State * L_,const std::string & mod_name)54 ModNameStorer(lua_State *L_, const std::string &mod_name):
55 L(L_)
56 {
57 // Store current mod name in registry
58 lua_pushstring(L, mod_name.c_str());
59 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
60 }
~ModNameStorer()61 ~ModNameStorer()
62 {
63 // Clear current mod name from registry
64 lua_pushnil(L);
65 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
66 }
67 };
68
69
70 /*
71 ScriptApiBase
72 */
73
ScriptApiBase(ScriptingType type)74 ScriptApiBase::ScriptApiBase(ScriptingType type):
75 m_type(type)
76 {
77 #ifdef SCRIPTAPI_LOCK_DEBUG
78 m_lock_recursion_count = 0;
79 #endif
80
81 m_luastack = luaL_newstate();
82 FATAL_ERROR_IF(!m_luastack, "luaL_newstate() failed");
83
84 lua_atpanic(m_luastack, &luaPanic);
85
86 if (m_type == ScriptingType::Client)
87 clientOpenLibs(m_luastack);
88 else
89 luaL_openlibs(m_luastack);
90
91 // Make the ScriptApiBase* accessible to ModApiBase
92 #if INDIRECT_SCRIPTAPI_RIDX
93 *(void **)(lua_newuserdata(m_luastack, sizeof(void *))) = this;
94 #else
95 lua_pushlightuserdata(m_luastack, this);
96 #endif
97 lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
98
99 // Add and save an error handler
100 lua_getglobal(m_luastack, "debug");
101 lua_getfield(m_luastack, -1, "traceback");
102 lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_BACKTRACE);
103 lua_pop(m_luastack, 1); // pop debug
104
105 // If we are using LuaJIT add a C++ wrapper function to catch
106 // exceptions thrown in Lua -> C++ calls
107 #if USE_LUAJIT
108 lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper);
109 luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
110 lua_pop(m_luastack, 1);
111 #endif
112
113 // Add basic globals
114 lua_newtable(m_luastack);
115 lua_setglobal(m_luastack, "core");
116
117 if (m_type == ScriptingType::Client)
118 lua_pushstring(m_luastack, "/");
119 else
120 lua_pushstring(m_luastack, DIR_DELIM);
121 lua_setglobal(m_luastack, "DIR_DELIM");
122
123 lua_pushstring(m_luastack, porting::getPlatformName());
124 lua_setglobal(m_luastack, "PLATFORM");
125
126 // Make sure Lua uses the right locale
127 setlocale(LC_NUMERIC, "C");
128 }
129
~ScriptApiBase()130 ScriptApiBase::~ScriptApiBase()
131 {
132 lua_close(m_luastack);
133 }
134
luaPanic(lua_State * L)135 int ScriptApiBase::luaPanic(lua_State *L)
136 {
137 std::ostringstream oss;
138 oss << "LUA PANIC: unprotected error in call to Lua API ("
139 << readParam<std::string>(L, -1) << ")";
140 FATAL_ERROR(oss.str().c_str());
141 // NOTREACHED
142 return 0;
143 }
144
clientOpenLibs(lua_State * L)145 void ScriptApiBase::clientOpenLibs(lua_State *L)
146 {
147 static const std::vector<std::pair<std::string, lua_CFunction>> m_libs = {
148 { "", luaopen_base },
149 { LUA_TABLIBNAME, luaopen_table },
150 { LUA_OSLIBNAME, luaopen_os },
151 { LUA_STRLIBNAME, luaopen_string },
152 { LUA_MATHLIBNAME, luaopen_math },
153 { LUA_DBLIBNAME, luaopen_debug },
154 #if USE_LUAJIT
155 { LUA_JITLIBNAME, luaopen_jit },
156 #endif
157 };
158
159 for (const std::pair<std::string, lua_CFunction> &lib : m_libs) {
160 lua_pushcfunction(L, lib.second);
161 lua_pushstring(L, lib.first.c_str());
162 lua_call(L, 1, 0);
163 }
164 }
165
loadMod(const std::string & script_path,const std::string & mod_name)166 void ScriptApiBase::loadMod(const std::string &script_path,
167 const std::string &mod_name)
168 {
169 ModNameStorer mod_name_storer(getStack(), mod_name);
170
171 loadScript(script_path);
172 }
173
loadScript(const std::string & script_path)174 void ScriptApiBase::loadScript(const std::string &script_path)
175 {
176 verbosestream << "Loading and running script from " << script_path << std::endl;
177
178 lua_State *L = getStack();
179
180 int error_handler = PUSH_ERROR_HANDLER(L);
181
182 bool ok;
183 if (m_secure) {
184 ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
185 } else {
186 ok = !luaL_loadfile(L, script_path.c_str());
187 }
188 ok = ok && !lua_pcall(L, 0, 0, error_handler);
189 if (!ok) {
190 const char *error_msg = lua_tostring(L, -1);
191 if (!error_msg)
192 error_msg = "(error object is not a string)";
193 lua_pop(L, 2); // Pop error message and error handler
194 throw ModError("Failed to load and run script from " +
195 script_path + ":\n" + error_msg);
196 }
197 lua_pop(L, 1); // Pop error handler
198 }
199
200 #ifndef SERVER
loadModFromMemory(const std::string & mod_name)201 void ScriptApiBase::loadModFromMemory(const std::string &mod_name)
202 {
203 ModNameStorer mod_name_storer(getStack(), mod_name);
204
205 sanity_check(m_type == ScriptingType::Client);
206
207 const std::string init_filename = mod_name + ":init.lua";
208 const std::string chunk_name = "@" + init_filename;
209
210 const std::string *contents = getClient()->getModFile(init_filename);
211 if (!contents)
212 throw ModError("Mod \"" + mod_name + "\" lacks init.lua");
213
214 verbosestream << "Loading and running script " << chunk_name << std::endl;
215
216 lua_State *L = getStack();
217
218 int error_handler = PUSH_ERROR_HANDLER(L);
219
220 bool ok = ScriptApiSecurity::safeLoadString(L, *contents, chunk_name.c_str());
221 if (ok)
222 ok = !lua_pcall(L, 0, 0, error_handler);
223 if (!ok) {
224 const char *error_msg = lua_tostring(L, -1);
225 if (!error_msg)
226 error_msg = "(error object is not a string)";
227 lua_pop(L, 2); // Pop error message and error handler
228 throw ModError("Failed to load and run mod \"" +
229 mod_name + "\":\n" + error_msg);
230 }
231 lua_pop(L, 1); // Pop error handler
232 }
233 #endif
234
235 // Push the list of callbacks (a lua table).
236 // Then push nargs arguments.
237 // Then call this function, which
238 // - runs the callbacks
239 // - replaces the table and arguments with the return value,
240 // computed depending on mode
241 // This function must only be called with scriptlock held (i.e. inside of a
242 // code block with SCRIPTAPI_PRECHECKHEADER declared)
runCallbacksRaw(int nargs,RunCallbacksMode mode,const char * fxn)243 void ScriptApiBase::runCallbacksRaw(int nargs,
244 RunCallbacksMode mode, const char *fxn)
245 {
246 #ifndef SERVER
247 // Hard fail for bad guarded callbacks
248 // Only run callbacks when the scripting enviroment is loaded
249 FATAL_ERROR_IF(m_type == ScriptingType::Client &&
250 !getClient()->modsLoaded(), fxn);
251 #endif
252
253 #ifdef SCRIPTAPI_LOCK_DEBUG
254 assert(m_lock_recursion_count > 0);
255 #endif
256 lua_State *L = getStack();
257 FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
258
259 // Insert error handler
260 PUSH_ERROR_HANDLER(L);
261 int error_handler = lua_gettop(L) - nargs - 1;
262 lua_insert(L, error_handler);
263
264 // Insert run_callbacks between error handler and table
265 lua_getglobal(L, "core");
266 lua_getfield(L, -1, "run_callbacks");
267 lua_remove(L, -2);
268 lua_insert(L, error_handler + 1);
269
270 // Insert mode after table
271 lua_pushnumber(L, (int)mode);
272 lua_insert(L, error_handler + 3);
273
274 // Stack now looks like this:
275 // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
276
277 int result = lua_pcall(L, nargs + 2, 1, error_handler);
278 if (result != 0)
279 scriptError(result, fxn);
280
281 lua_remove(L, error_handler);
282 }
283
realityCheck()284 void ScriptApiBase::realityCheck()
285 {
286 int top = lua_gettop(m_luastack);
287 if (top >= 30) {
288 dstream << "Stack is over 30:" << std::endl;
289 stackDump(dstream);
290 std::string traceback = script_get_backtrace(m_luastack);
291 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
292 }
293 }
294
scriptError(int result,const char * fxn)295 void ScriptApiBase::scriptError(int result, const char *fxn)
296 {
297 script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
298 }
299
stackDump(std::ostream & o)300 void ScriptApiBase::stackDump(std::ostream &o)
301 {
302 int top = lua_gettop(m_luastack);
303 for (int i = 1; i <= top; i++) { /* repeat for each level */
304 int t = lua_type(m_luastack, i);
305 switch (t) {
306 case LUA_TSTRING: /* strings */
307 o << "\"" << readParam<std::string>(m_luastack, i) << "\"";
308 break;
309 case LUA_TBOOLEAN: /* booleans */
310 o << (readParam<bool>(m_luastack, i) ? "true" : "false");
311 break;
312 case LUA_TNUMBER: /* numbers */ {
313 char buf[10];
314 porting::mt_snprintf(buf, sizeof(buf), "%lf", lua_tonumber(m_luastack, i));
315 o << buf;
316 break;
317 }
318 default: /* other values */
319 o << lua_typename(m_luastack, t);
320 break;
321 }
322 o << " ";
323 }
324 o << std::endl;
325 }
326
setOriginDirect(const char * origin)327 void ScriptApiBase::setOriginDirect(const char *origin)
328 {
329 m_last_run_mod = origin ? origin : "??";
330 }
331
setOriginFromTableRaw(int index,const char * fxn)332 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
333 {
334 #ifdef SCRIPTAPI_DEBUG
335 lua_State *L = getStack();
336
337 m_last_run_mod = lua_istable(L, index) ?
338 getstringfield_default(L, index, "mod_origin", "") : "";
339 //printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str());
340 #endif
341 }
342
343 /*
344 * How ObjectRefs are handled in Lua:
345 * When an active object is created, an ObjectRef is created on the Lua side
346 * and stored in core.object_refs[id].
347 * Methods that require an ObjectRef to a certain object retrieve it from that
348 * table instead of creating their own.(*)
349 * When an active object is removed, the existing ObjectRef is invalidated
350 * using ::set_null() and removed from the core.object_refs table.
351 * (*) An exception to this are NULL ObjectRefs and anonymous ObjectRefs
352 * for objects without ID.
353 * It's unclear what the latter are needed for and their use is problematic
354 * since we lose control over the ref and the contained pointer.
355 */
356
addObjectReference(ServerActiveObject * cobj)357 void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
358 {
359 SCRIPTAPI_PRECHECKHEADER
360 //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
361
362 // Create object on stack
363 ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
364 int object = lua_gettop(L);
365
366 // Get core.object_refs table
367 lua_getglobal(L, "core");
368 lua_getfield(L, -1, "object_refs");
369 luaL_checktype(L, -1, LUA_TTABLE);
370 int objectstable = lua_gettop(L);
371
372 // object_refs[id] = object
373 lua_pushnumber(L, cobj->getId()); // Push id
374 lua_pushvalue(L, object); // Copy object to top of stack
375 lua_settable(L, objectstable);
376 }
377
removeObjectReference(ServerActiveObject * cobj)378 void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
379 {
380 SCRIPTAPI_PRECHECKHEADER
381 //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
382
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);
388
389 // Get object_refs[id]
390 lua_pushnumber(L, cobj->getId()); // Push id
391 lua_gettable(L, objectstable);
392 // Set object reference to NULL
393 ObjectRef::set_null(L);
394 lua_pop(L, 1); // pop object
395
396 // Set object_refs[id] = nil
397 lua_pushnumber(L, cobj->getId()); // Push id
398 lua_pushnil(L);
399 lua_settable(L, objectstable);
400 }
401
402 // Creates a new anonymous reference if cobj=NULL or id=0
objectrefGetOrCreate(lua_State * L,ServerActiveObject * cobj)403 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
404 ServerActiveObject *cobj)
405 {
406 if (cobj == NULL || cobj->getId() == 0) {
407 ObjectRef::create(L, cobj);
408 } else {
409 push_objectRef(L, cobj->getId());
410 if (cobj->isGone())
411 warningstream << "ScriptApiBase::objectrefGetOrCreate(): "
412 << "Pushing ObjectRef to removed/deactivated object"
413 << ", this is probably a bug." << std::endl;
414 }
415 }
416
pushPlayerHPChangeReason(lua_State * L,const PlayerHPChangeReason & reason)417 void ScriptApiBase::pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeReason &reason)
418 {
419 if (reason.hasLuaReference())
420 lua_rawgeti(L, LUA_REGISTRYINDEX, reason.lua_reference);
421 else
422 lua_newtable(L);
423
424 lua_getfield(L, -1, "type");
425 bool has_type = (bool)lua_isstring(L, -1);
426 lua_pop(L, 1);
427 if (!has_type) {
428 lua_pushstring(L, reason.getTypeAsString().c_str());
429 lua_setfield(L, -2, "type");
430 }
431
432 lua_pushstring(L, reason.from_mod ? "mod" : "engine");
433 lua_setfield(L, -2, "from");
434
435 if (reason.object) {
436 objectrefGetOrCreate(L, reason.object);
437 lua_setfield(L, -2, "object");
438 }
439 if (!reason.node.empty()) {
440 lua_pushstring(L, reason.node.c_str());
441 lua_setfield(L, -2, "node");
442 }
443 }
444
getServer()445 Server* ScriptApiBase::getServer()
446 {
447 return dynamic_cast<Server *>(m_gamedef);
448 }
449 #ifndef SERVER
getClient()450 Client* ScriptApiBase::getClient()
451 {
452 return dynamic_cast<Client *>(m_gamedef);
453 }
454 #endif
455