Skip to content

Commit

Permalink
SAPI: Track last executed mod and include in error messages
Browse files Browse the repository at this point in the history
  • Loading branch information
kwolekr committed Aug 13, 2015
1 parent 738fbc6 commit 2b04ab8
Show file tree
Hide file tree
Showing 19 changed files with 231 additions and 45 deletions.
1 change: 1 addition & 0 deletions builtin/game/auth.lua
Expand Up @@ -171,6 +171,7 @@ function core.register_authentication_handler(handler)
end
core.registered_auth_handler = handler
core.registered_auth_handler_modname = core.get_current_modname()
handler.mod_origin = core.registered_auth_handler_modname
end

function core.get_auth_handler()
Expand Down
2 changes: 2 additions & 0 deletions builtin/game/chatcommands.lua
Expand Up @@ -10,6 +10,7 @@ function core.register_chatcommand(cmd, def)
def.params = def.params or ""
def.description = def.description or ""
def.privs = def.privs or {}
def.mod_origin = core.get_current_modname() or "??"
core.chatcommands[cmd] = def
end

Expand Down Expand Up @@ -37,6 +38,7 @@ core.register_on_chat_message(function(name, message)
end
local has_privs, missing_privs = core.check_player_privs(name, cmd_def.privs)
if has_privs then
core.set_last_run_mod(cmd_def.mod_origin)
local success, message = cmd_def.func(name, param)
if message then
core.chat_send_player(name, message)
Expand Down
1 change: 1 addition & 0 deletions builtin/game/detached_inventory.lua
Expand Up @@ -13,6 +13,7 @@ function core.create_detached_inventory(name, callbacks)
stuff.on_put = callbacks.on_put
stuff.on_take = callbacks.on_take
end
stuff.mod_origin = core.get_current_modname() or "??"
core.detached_inventories[name] = stuff
return core.create_detached_inventory_raw(name)
end
Expand Down
9 changes: 9 additions & 0 deletions builtin/game/item.lua
Expand Up @@ -479,6 +479,15 @@ function core.node_dig(pos, node, digger)
-- Run script hook
local _, callback
for _, callback in ipairs(core.registered_on_dignodes) do
local origin = core.callback_origins[callback]
if origin then
core.set_last_run_mod(origin.mod)
--print("Running " .. tostring(callback) ..
-- " (a " .. origin.name .. " callback in " .. origin.mod .. ")")
else
--print("No data associated with callback")
end

-- Copy pos and node because callback can modify them
local pos_copy = {x=pos.x, y=pos.y, z=pos.z}
local node_copy = {name=node.name, param1=node.param1, param2=node.param2}
Expand Down
15 changes: 13 additions & 2 deletions builtin/game/misc.lua
Expand Up @@ -14,6 +14,7 @@ local function update_timers(delay)
local timer = timers[index]
timer.time = timer.time - delay
if timer.time <= 0 then
core.set_last_run_mod(timer.mod_origin)
timer.func(unpack(timer.args or {}))
table.remove(timers, index)
sub = sub + 1
Expand Down Expand Up @@ -55,12 +56,22 @@ function core.after(time, func, ...)
"Invalid core.after invocation")
if not mintime then
mintime = time
timers_to_add = {{time=time+delay, func=func, args={...}}}
timers_to_add = {{
time = time+delay,
func = func,
args = {...},
mod_origin = core.get_last_run_mod(),
}}
return
end
mintime = math.min(mintime, time)
timers_to_add = timers_to_add or {}
timers_to_add[#timers_to_add+1] = {time=time+delay, func=func, args={...}}
timers_to_add[#timers_to_add+1] = {
time = time+delay,
func = func,
args = {...},
mod_origin = core.get_last_run_mod(),
}
end

function core.check_player_privs(name, privs)
Expand Down
40 changes: 38 additions & 2 deletions builtin/game/register.lua
Expand Up @@ -72,6 +72,7 @@ end
function core.register_abm(spec)
-- Add to core.registered_abms
core.registered_abms[#core.registered_abms+1] = spec
spec.mod_origin = core.get_current_modname() or "??"
end

function core.register_entity(name, prototype)
Expand All @@ -86,6 +87,7 @@ function core.register_entity(name, prototype)

-- Add to core.registered_entities
core.registered_entities[name] = prototype
prototype.mod_origin = core.get_current_modname() or "??"
end

function core.register_item(name, itemdef)
Expand Down Expand Up @@ -147,6 +149,8 @@ function core.register_item(name, itemdef)
end
-- END Legacy stuff

itemdef.mod_origin = core.get_current_modname() or "??"

-- Disable all further modifications
getmetatable(itemdef).__newindex = {}

Expand Down Expand Up @@ -326,6 +330,8 @@ function core.override_item(name, redefinition)
end


core.callback_origins = {}

function core.run_callbacks(callbacks, mode, ...)
assert(type(callbacks) == "table")
local cb_len = #callbacks
Expand All @@ -338,6 +344,14 @@ function core.run_callbacks(callbacks, mode, ...)
end
local ret = nil
for i = 1, cb_len do
local origin = core.callback_origins[callbacks[i]]
if origin then
core.set_last_run_mod(origin.mod)
--print("Running " .. tostring(callbacks[i]) ..
-- " (a " .. origin.name .. " callback in " .. origin.mod .. ")")
else
--print("No data associated with callback")
end
local cb_ret = callbacks[i](...)

if mode == 0 and i == 1 then
Expand Down Expand Up @@ -370,13 +384,29 @@ end

local function make_registration()
local t = {}
local registerfunc = function(func) table.insert(t, func) end
local registerfunc = function(func)
table.insert(t, func)
core.callback_origins[func] = {
mod = core.get_current_modname() or "??",
name = debug.getinfo(1, "n").name or "??"
}
--local origin = core.callback_origins[func]
--print(origin.name .. ": " .. origin.mod .. " registering cbk " .. tostring(func))
end
return t, registerfunc
end

local function make_registration_reverse()
local t = {}
local registerfunc = function(func) table.insert(t, 1, func) end
local registerfunc = function(func)
table.insert(t, 1, func)
core.callback_origins[func] = {
mod = core.get_current_modname() or "??",
name = debug.getinfo(1, "n").name or "??"
}
--local origin = core.callback_origins[func]
--print(origin.name .. ": " .. origin.mod .. " registering cbk " .. tostring(func))
end
return t, registerfunc
end

Expand Down Expand Up @@ -408,6 +438,7 @@ local function make_registration_wrap(reg_fn_name, clear_fn_name)
end

core.registered_on_player_hpchanges = { modifiers = { }, loggers = { } }

function core.registered_on_player_hpchange(player, hp_change)
local last = false
for i = #core.registered_on_player_hpchanges.modifiers, 1, -1 do
Expand All @@ -427,12 +458,17 @@ function core.registered_on_player_hpchange(player, hp_change)
end
return hp_change
end

function core.register_on_player_hpchange(func, modifier)
if modifier then
table.insert(core.registered_on_player_hpchanges.modifiers, func)
else
table.insert(core.registered_on_player_hpchanges.loggers, func)
end
core.callback_origins[func] = {
mod = core.get_current_modname() or "??",
name = debug.getinfo(1, "n").name or "??"
}
end

core.registered_biomes = make_registration_wrap("register_biome", "clear_registered_biomes")
Expand Down
25 changes: 14 additions & 11 deletions src/script/common/c_internal.cpp
Expand Up @@ -79,7 +79,7 @@ int script_exception_wrapper(lua_State *L, lua_CFunction f)
* to gather a coherent backtrace. Realistically, the best we can do here is
* print which C function performed the failing pcall.
*/
void script_error(lua_State *L, int pcall_result, const char *fxn)
void script_error(lua_State *L, int pcall_result, const char *mod, const char *fxn)
{
if (pcall_result == 0)
return;
Expand All @@ -99,18 +99,21 @@ void script_error(lua_State *L, int pcall_result, const char *fxn)
err_type = "Unknown";
}

if (!mod)
mod = "??";

if (!fxn)
fxn = "??";

const char *err_descr = lua_tostring(L, -1);
if (!err_descr)
err_descr = "<no description>";

std::string err_msg(err_type);
if (fxn) {
err_msg += " error in ";
err_msg += fxn;
err_msg += "(): ";
} else {
err_msg += " error: ";
}
char buf[256];
snprintf(buf, sizeof(buf), "%s error from mod '%s' in callback %s(): ",
err_type, mod, fxn);

std::string err_msg(buf);
err_msg += err_descr;

if (pcall_result == LUA_ERRMEM) {
Expand Down Expand Up @@ -152,7 +155,7 @@ void script_run_callbacks_f(lua_State *L, int nargs,

int result = lua_pcall(L, nargs + 2, 1, errorhandler);
if (result != 0)
script_error(L, result, fxn);
script_error(L, result, NULL, fxn);

lua_remove(L, -2); // Remove error handler
}
Expand All @@ -176,7 +179,7 @@ void log_deprecated(lua_State *L, const std::string &message)

if (doerror) {
if (L != NULL) {
script_error(L, LUA_ERRRUN, NULL);
script_error(L, LUA_ERRRUN, NULL, NULL);
} else {
FATAL_ERROR("Can't do a scripterror for this deprecated message, "
"so exit completely!");
Expand Down
12 changes: 6 additions & 6 deletions src/script/common/c_internal.h
Expand Up @@ -34,11 +34,11 @@ extern "C" {

#include "common/c_types.h"

#define PCALL_RESL(L, RES) do { \
int result_ = (RES); \
if (result_ != 0) { \
script_error((L), result_, __FUNCTION__); \
} \
#define PCALL_RESL(L, RES) do { \
int result_ = (RES); \
if (result_ != 0) { \
script_error((L), result_, NULL, __FUNCTION__); \
} \
} while (0)

#define script_run_callbacks(L, nargs, mode) \
Expand Down Expand Up @@ -77,7 +77,7 @@ enum RunCallbacksMode
std::string script_get_backtrace(lua_State *L);
int script_error_handler(lua_State *L);
int script_exception_wrapper(lua_State *L, lua_CFunction f);
void script_error(lua_State *L, int pcall_result, const char *fxn);
void script_error(lua_State *L, int pcall_result, const char *mod, const char *fxn);
void script_run_callbacks_f(lua_State *L, int nargs,
RunCallbacksMode mode, const char *fxn);
void log_deprecated(lua_State *L, const std::string &message);
Expand Down
60 changes: 57 additions & 3 deletions src/script/cpp_api/s_base.cpp
Expand Up @@ -21,6 +21,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "cpp_api/s_internal.h"
#include "cpp_api/s_security.h"
#include "lua_api/l_object.h"
#include "common/c_converter.h"
#include "serverobject.h"
#include "debug.h"
#include "filesys.h"
Expand Down Expand Up @@ -68,9 +69,9 @@ class ModNameStorer

ScriptApiBase::ScriptApiBase()
{
#ifdef SCRIPTAPI_LOCK_DEBUG
#ifdef SCRIPTAPI_LOCK_DEBUG
m_locked = false;
#endif
#endif

m_luastack = luaL_newstate();
FATAL_ERROR_IF(!m_luastack, "luaL_newstate() failed");
Expand Down Expand Up @@ -154,6 +155,43 @@ bool ScriptApiBase::loadScript(const std::string &script_path, std::string *erro
return true;
}

// Push the list of callbacks (a lua table).
// Then push nargs arguments.
// Then call this function, which
// - runs the callbacks
// - replaces the table and arguments with the return value,
// computed depending on mode
void ScriptApiBase::runCallbacksRaw(int nargs,
RunCallbacksMode mode, const char *fxn)
{
lua_State *L = getStack();
FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");

// Insert error handler
lua_pushcfunction(L, script_error_handler);
int errorhandler = lua_gettop(L) - nargs - 1;
lua_insert(L, errorhandler);

// Insert run_callbacks between error handler and table
lua_getglobal(L, "core");
lua_getfield(L, -1, "run_callbacks");
lua_remove(L, -2);
lua_insert(L, errorhandler + 1);

// Insert mode after table
lua_pushnumber(L, (int)mode);
lua_insert(L, errorhandler + 3);

// Stack now looks like this:
// ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>

int result = lua_pcall(L, nargs + 2, 1, errorhandler);
if (result != 0)
scriptError(result, fxn);

lua_remove(L, -2); // Remove error handler
}

void ScriptApiBase::realityCheck()
{
int top = lua_gettop(m_luastack);
Expand All @@ -167,7 +205,7 @@ void ScriptApiBase::realityCheck()

void ScriptApiBase::scriptError(int result, const char *fxn)
{
script_error(getStack(), result, fxn);
script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
}

void ScriptApiBase::stackDump(std::ostream &o)
Expand Down Expand Up @@ -197,6 +235,22 @@ void ScriptApiBase::stackDump(std::ostream &o)
o << std::endl;
}

void ScriptApiBase::setOriginDirect(const char *origin)
{
m_last_run_mod = origin ? origin : "??";
}

void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
{
#ifdef SCRIPTAPI_DEBUG
lua_State *L = getStack();

m_last_run_mod = lua_istable(L, index) ?
getstringfield_default(L, index, "mod_origin", "") : "";
//printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str());
#endif
}

void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
{
SCRIPTAPI_PRECHECKHEADER
Expand Down

0 comments on commit 2b04ab8

Please sign in to comment.