Embedded Lua - timing out rogue scripts (e.g. infinite loop) - an example anyone?

后端 未结 3 463
野的像风
野的像风 2021-01-14 03:31

I have embedded Lua in a C++ application. I need to be able to kill rogue (i.e. badly written scripts) from hogging resources.

I know I will not be able to cater for

3条回答
  •  走了就别回头了
    2021-01-14 04:20

    A very naive and simple, but all-lua, method of doing it, is

    -- Limit may be in the millions range depending on your needs
    setfenv(code,sandbox)
    pcall (function() debug.sethook(
      function() error ("Timeout!") end,"", limit)
      code() 
      debug.sethook() 
      end);
    

    I expect you can achieve the same through the C API.

    However, there's a good number of problems with this method. Set the limit too low, and it can't do its job. Too high, and it's not really effective. (Can the chunk get run repeatedly?) Allow the code to call a function that blocks for a significant amount of time, and the above is meaningless. Allow it to do any kind of pcall, and it can trap the error on its own. And whatever other problems I haven't thought of yet. Here I'm also plain ignoring the warnings against using the debug library for anything (besides debugging).

    Thus, if you want it reliable, you should probably go with RB's solution.

    I expect it will work quite well against accidental infinite loops, the kind that beginning lua programmers are so fond of :P

    For memory overuse, you could do the same with a function checking for increases in collectgarbage("count") at far smaller intervals; you'd have to merge them to get both.

提交回复
热议问题