]> git.lizzy.rs Git - minetest.git/blob - src/script/cpp_api/s_base.cpp
Move `setlocale` from Lua to C++.
[minetest.git] / src / script / cpp_api / s_base.cpp
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 "serverobject.h"
26 #include "filesys.h"
27 #include "mods.h"
28 #include "porting.h"
29 #include "util/string.h"
30 #include "server.h"
31 #ifndef SERVER
32 #include "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:
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         }
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
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         lua_pushlightuserdata(m_luastack, this);
93         lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
94
95         // Add and save an error handler
96         lua_getglobal(m_luastack, "debug");
97         lua_getfield(m_luastack, -1, "traceback");
98         lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_BACKTRACE);
99         lua_pop(m_luastack, 1); // pop debug
100
101         // If we are using LuaJIT add a C++ wrapper function to catch
102         // exceptions thrown in Lua -> C++ calls
103 #if USE_LUAJIT
104         lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper);
105         luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
106         lua_pop(m_luastack, 1);
107 #endif
108
109         // Add basic globals
110         lua_newtable(m_luastack);
111         lua_setglobal(m_luastack, "core");
112
113         if (m_type == ScriptingType::Client)
114                 lua_pushstring(m_luastack, "/");
115         else
116                 lua_pushstring(m_luastack, DIR_DELIM);
117         lua_setglobal(m_luastack, "DIR_DELIM");
118
119         lua_pushstring(m_luastack, porting::getPlatformName());
120         lua_setglobal(m_luastack, "PLATFORM");
121
122         // Make sure Lua uses the right locale
123         setlocale(LC_NUMERIC, "C");
124 }
125
126 ScriptApiBase::~ScriptApiBase()
127 {
128         lua_close(m_luastack);
129 }
130
131 int ScriptApiBase::luaPanic(lua_State *L)
132 {
133         std::ostringstream oss;
134         oss << "LUA PANIC: unprotected error in call to Lua API ("
135                 << lua_tostring(L, -1) << ")";
136         FATAL_ERROR(oss.str().c_str());
137         // NOTREACHED
138         return 0;
139 }
140
141 void ScriptApiBase::clientOpenLibs(lua_State *L)
142 {
143         static const std::vector<std::pair<std::string, lua_CFunction>> m_libs = {
144                 { "", luaopen_base },
145                 { LUA_TABLIBNAME,  luaopen_table   },
146                 { LUA_OSLIBNAME,   luaopen_os      },
147                 { LUA_STRLIBNAME,  luaopen_string  },
148                 { LUA_MATHLIBNAME, luaopen_math    },
149                 { LUA_DBLIBNAME,   luaopen_debug   },
150 #if USE_LUAJIT
151                 { LUA_JITLIBNAME,  luaopen_jit     },
152 #endif
153         };
154         
155         for (const std::pair<std::string, lua_CFunction> &lib : m_libs) {
156             lua_pushcfunction(L, lib.second);
157             lua_pushstring(L, lib.first.c_str());
158             lua_call(L, 1, 0);
159         }
160 }
161
162 void ScriptApiBase::loadMod(const std::string &script_path,
163                 const std::string &mod_name)
164 {
165         ModNameStorer mod_name_storer(getStack(), mod_name);
166
167         loadScript(script_path);
168 }
169
170 void ScriptApiBase::loadScript(const std::string &script_path)
171 {
172         verbosestream << "Loading and running script from " << script_path << std::endl;
173
174         lua_State *L = getStack();
175
176         int error_handler = PUSH_ERROR_HANDLER(L);
177
178         bool ok;
179         if (m_secure) {
180                 ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
181         } else {
182                 ok = !luaL_loadfile(L, script_path.c_str());
183         }
184         ok = ok && !lua_pcall(L, 0, 0, error_handler);
185         if (!ok) {
186                 std::string error_msg = lua_tostring(L, -1);
187                 lua_pop(L, 2); // Pop error message and error handler
188                 throw ModError("Failed to load and run script from " +
189                                 script_path + ":\n" + error_msg);
190         }
191         lua_pop(L, 1); // Pop error handler
192 }
193
194 #ifndef SERVER
195 void ScriptApiBase::loadModFromMemory(const std::string &mod_name)
196 {
197         ModNameStorer mod_name_storer(getStack(), mod_name);
198
199         const std::string *init_filename = getClient()->getModFile(mod_name + ":init.lua");
200         const std::string display_filename = mod_name + ":init.lua";
201         if(init_filename == NULL)
202                 throw ModError("Mod:\"" + mod_name + "\" lacks init.lua");
203
204         verbosestream << "Loading and running script " << display_filename << std::endl;
205
206         lua_State *L = getStack();
207
208         int error_handler = PUSH_ERROR_HANDLER(L);
209
210         bool ok = ScriptApiSecurity::safeLoadFile(L, init_filename->c_str(), display_filename.c_str());
211         if (ok)
212                 ok = !lua_pcall(L, 0, 0, error_handler);
213         if (!ok) {
214                 std::string error_msg = luaL_checkstring(L, -1);
215                 lua_pop(L, 2); // Pop error message and error handler
216                 throw ModError("Failed to load and run mod \"" +
217                                 mod_name + "\":\n" + error_msg);
218         }
219         lua_pop(L, 1); // Pop error handler
220 }
221 #endif
222
223 // Push the list of callbacks (a lua table).
224 // Then push nargs arguments.
225 // Then call this function, which
226 // - runs the callbacks
227 // - replaces the table and arguments with the return value,
228 //     computed depending on mode
229 // This function must only be called with scriptlock held (i.e. inside of a
230 // code block with SCRIPTAPI_PRECHECKHEADER declared)
231 void ScriptApiBase::runCallbacksRaw(int nargs,
232                 RunCallbacksMode mode, const char *fxn)
233 {
234 #ifdef SCRIPTAPI_LOCK_DEBUG
235         assert(m_lock_recursion_count > 0);
236 #endif
237         lua_State *L = getStack();
238         FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
239
240         // Insert error handler
241         PUSH_ERROR_HANDLER(L);
242         int error_handler = lua_gettop(L) - nargs - 1;
243         lua_insert(L, error_handler);
244
245         // Insert run_callbacks between error handler and table
246         lua_getglobal(L, "core");
247         lua_getfield(L, -1, "run_callbacks");
248         lua_remove(L, -2);
249         lua_insert(L, error_handler + 1);
250
251         // Insert mode after table
252         lua_pushnumber(L, (int)mode);
253         lua_insert(L, error_handler + 3);
254
255         // Stack now looks like this:
256         // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
257
258         int result = lua_pcall(L, nargs + 2, 1, error_handler);
259         if (result != 0)
260                 scriptError(result, fxn);
261
262         lua_remove(L, error_handler);
263 }
264
265 void ScriptApiBase::realityCheck()
266 {
267         int top = lua_gettop(m_luastack);
268         if (top >= 30) {
269                 dstream << "Stack is over 30:" << std::endl;
270                 stackDump(dstream);
271                 std::string traceback = script_get_backtrace(m_luastack);
272                 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
273         }
274 }
275
276 void ScriptApiBase::scriptError(int result, const char *fxn)
277 {
278         script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
279 }
280
281 void ScriptApiBase::stackDump(std::ostream &o)
282 {
283         int top = lua_gettop(m_luastack);
284         for (int i = 1; i <= top; i++) {  /* repeat for each level */
285                 int t = lua_type(m_luastack, i);
286                 switch (t) {
287                         case LUA_TSTRING:  /* strings */
288                                 o << "\"" << lua_tostring(m_luastack, i) << "\"";
289                                 break;
290                         case LUA_TBOOLEAN:  /* booleans */
291                                 o << (lua_toboolean(m_luastack, i) ? "true" : "false");
292                                 break;
293                         case LUA_TNUMBER:  /* numbers */ {
294                                 char buf[10];
295                                 snprintf(buf, 10, "%lf", lua_tonumber(m_luastack, i));
296                                 o << buf;
297                                 break;
298                         }
299                         default:  /* other values */
300                                 o << lua_typename(m_luastack, t);
301                                 break;
302                 }
303                 o << " ";
304         }
305         o << std::endl;
306 }
307
308 void ScriptApiBase::setOriginDirect(const char *origin)
309 {
310         m_last_run_mod = origin ? origin : "??";
311 }
312
313 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
314 {
315 #ifdef SCRIPTAPI_DEBUG
316         lua_State *L = getStack();
317
318         m_last_run_mod = lua_istable(L, index) ?
319                 getstringfield_default(L, index, "mod_origin", "") : "";
320         //printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str());
321 #endif
322 }
323
324 void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
325 {
326         SCRIPTAPI_PRECHECKHEADER
327         //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
328
329         // Create object on stack
330         ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
331         int object = lua_gettop(L);
332
333         // Get core.object_refs table
334         lua_getglobal(L, "core");
335         lua_getfield(L, -1, "object_refs");
336         luaL_checktype(L, -1, LUA_TTABLE);
337         int objectstable = lua_gettop(L);
338
339         // object_refs[id] = object
340         lua_pushnumber(L, cobj->getId()); // Push id
341         lua_pushvalue(L, object); // Copy object to top of stack
342         lua_settable(L, objectstable);
343 }
344
345 void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
346 {
347         SCRIPTAPI_PRECHECKHEADER
348         //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
349
350         // Get core.object_refs table
351         lua_getglobal(L, "core");
352         lua_getfield(L, -1, "object_refs");
353         luaL_checktype(L, -1, LUA_TTABLE);
354         int objectstable = lua_gettop(L);
355
356         // Get object_refs[id]
357         lua_pushnumber(L, cobj->getId()); // Push id
358         lua_gettable(L, objectstable);
359         // Set object reference to NULL
360         ObjectRef::set_null(L);
361         lua_pop(L, 1); // pop object
362
363         // Set object_refs[id] = nil
364         lua_pushnumber(L, cobj->getId()); // Push id
365         lua_pushnil(L);
366         lua_settable(L, objectstable);
367 }
368
369 // Creates a new anonymous reference if cobj=NULL or id=0
370 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
371                 ServerActiveObject *cobj)
372 {
373         if (cobj == NULL || cobj->getId() == 0) {
374                 ObjectRef::create(L, cobj);
375         } else {
376                 push_objectRef(L, cobj->getId());
377                 if (cobj->isGone())
378                         warningstream << "ScriptApiBase::objectrefGetOrCreate(): "
379                                         << "Pushing ObjectRef to removed/deactivated object"
380                                         << ", this is probably a bug." << std::endl;
381         }
382 }
383
384 Server* ScriptApiBase::getServer()
385 {
386         return dynamic_cast<Server *>(m_gamedef);
387 }
388 #ifndef SERVER
389 Client* ScriptApiBase::getClient()
390 {
391         return dynamic_cast<Client *>(m_gamedef);
392 }
393 #endif