luaL_loadfile(mState, path.c_str());
lua_pcall(mState, 0, 0, 0);
Is there a way to put an execution time limit (say 10-20 seconds) for those two C++ statements, that load and then execute a lua file?
Since the Lua file is untrusted I don’t want a malicious user to hang the program indefinitely with an infinite loop in the Lua code.
Tagging C because the Lua API is C, tagging C++ because I’m using C++
There’s lua_sethook which can be used to tell the interpreter to call a hook after every ‘count’ instructions executed. This way you can monitor the user script and terminate it if it eats up its quota:
This can also be used from Lua:
If you use the techniques from http://lua-users.org/wiki/SandBoxes then you can set up a safe execution environment with
sethook()and friends entirely from Lua and then switch to sandbox mode while executing the user script. I’ve tried that here, just for you to get started:This should print values of fib() for 5 seconds and then show an error.