Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 616
AlfredoVR Avatar asked Oct 18 '25 22:10

AlfredoVR


2 Answers

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)
like image 149
furq Avatar answered Oct 22 '25 03:10

furq


If you don't call out to C functions in your scripts you can use the count hook with a large count value and raise an error inside the hook:

local function f() error"timeout!" end
debug.sethook(f,"count",1e6)
while true do end

In your application, set the count hook before calling dofile.

The count hook is called every n Lua VM instructions. However, there is not way to account for the time taken in C functions, hence my caveat above.

like image 44
lhf Avatar answered Oct 22 '25 04:10

lhf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!