Search code examples
luatimeoutsandbox

How to enforce Lua scripts runtime limit?


Running an almost trivial script in lua with dofile, 10000 times, takes about 52 seconds in this machine, but if i run 10000 times "lua52 script.lua", it takes 3 or 4 times more. I'm aware that there's more system calls involved and other overhead, but what i try to achieve is running scripts with a timeout of let's say 3 seconds, and print out the output. My problem is scripts with infinite loops, intentional or not, for example:

while(true) do
end

Can i make a timeout for a dofile from within Lua? Is my only option to call the interpreter each time with timeout(3)?


Solution

  • It feels a bit wrong for a novice like me to be correcting lhf on Lua matters, but here goes; passing "count" to debug.sethook is the same as passing "c" or "call", the correct mask to pass to fire the associated function after n VM instructions is "".

    As such, to restrict the runtime of code loaded from dofile(), use something like the following:

    local f = function() error("timeout") end
    local x,y = xpcall(function()
      debug.sethook(f, "", 1e8)
      local ret = dofile("script.lua")
      debug.sethook()
      return ret
    end, debug.traceback)