Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Is there an alternative to debug.sethook()?

Asked by 5 years ago

I'm trying to add a little extra safety to a sandbox I've created. On top of doing all the ENV changes, I want to limit CPU and memory usage.

This is some quick and simple Lua code that (mostly) accomplishes that:

local stepLimit = 50 --Maximum instructions
local memLimit = 1000 --Max memory in KB
local count = 0 --Counter for the steps


local function checkMem()
    if collectgarbage("count")>memLimit then --If too much mem usage
        error("uses too much memory")
    end
end

local function step()
    checkMem() --check mem usage
    count = count+1
    if count>stepLimit then -- if too much CPU usage
        error("uses too much CPU")
    end
end

local code = loadstring("while wait(1) do print('hi') end") --load a chunk
debug.sethook(step, "", 100) --setup this bit of sandboxy stuff
code() --run

However, Roblox uses a modified version of Lua 5.1.4, which lacks debug.sethook() as a function.

Running this code simply gives: attempt to call field 'sethook' (a nil value) (Commenting out the debug.sethook() line makes the code run, everything else is fine)

So if I cannot use this, how else can I manage memory and CPU?

1 answer

Log in to vote
0
Answered by 5 years ago

Thank you to "howmanysmall" on the Lua Learning Discord

Well, rather than be able to set a hook, I can create a thread alongside it.

spawn(function()
    while wait() do
        local MemUsage = collectgarbage("count")/1000 --(/1000 makes it MB which I prefer)
        --print("memUsage:", MemUsage, "(in MB)")
        if (MemUsage) > MemLimit then
            error('{Code abortion}-"Using too much memory"')
        end
    end
end)

Not the best (or even close to it), but it does help.

Still no clue how to handle overusing CPU!

Ad

Answer this question