「count」命令が実行されるたびにフックを呼び出すようにインタープリターに指示するために使用できる lua_sethook があります。このようにして、ユーザー スクリプトを監視し、クォータを使い果たした場合は終了できます。
int lua_sethook (lua_State *L, lua_Hook f, int mask, int count);
これは Lua からも使用できます。
debug.sethook(function() print("That's enough for today"); os.exit(0); end, "", 10000)
for i=1,10000 do end
http://lua-users.org/wiki/SandBoxesのテクニックを使用すると、安全な実行環境をsethook()
Lua から完全に設定し、ユーザー スクリプトの実行中にサンドボックス モードに切り替えることができます。あなたが始めるためだけに、私はここでそれを試しました:
-- set an execution quota
local function set_quota(secs)
local st=os.clock()
function check()
if os.clock()-st > secs then
debug.sethook() -- disable hooks
error("quota exceeded")
end
end
debug.sethook(check,"",100000);
end
-- these are the global objects, the user can use:
local env = {print=print}
-- The user code is allowed to run for 5 seconds.
set_quota(5)
-- run code under environment:
local function run(untrusted_code)
local untrusted_function, message = loadstring(untrusted_code)
if not untrusted_function then return nil, message end
setfenv(untrusted_function, env)
return pcall(untrusted_function)
end
-- here is the user code:
local userscript=[[
function fib(n)
if n<2 then return n
else return fib(n-2)+fib(n-1)
end
end
for n=1,42 do print(n,fib(n)) end
]]
-- call it:
local r,m=run(userscript)
print(r,m)
これにより、fib() の値が 5 秒間出力され、エラーが表示されます。