simplification
Download
242 lines 10.2 KiBMoonScriptModified 2026-11-09 raw
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
-- This file runs code with limits on how many Lua instructions it can run, how much CPU
-- time it can use, and how much memory it can use:
--     run_limited({instructions: 1e7, seconds: 1, memory: 64*1024}, fn, ...)
-- A debug hook checks the limits every CHECK_INTERVAL instructions, and functions that
-- can make big strings in one call (like Text.rep) check the memory limit too. When code
-- goes over a limit, it's stopped with a limit signal, which (like an exit signal) can't
-- be caught by (try), pcall(), or coroutines.
-- The memory limit is approximate: memory is measured for the whole Lua state, a few
-- instructions between checks can use a lot of memory, and on Lua 5.5, which doesn't
-- count some strings, only the text that each call makes is counted for those strings.
-- On LuaJIT, hooks don't run in compiled code, so the JIT is off while limited code runs.
Errhand = require "error_handling"
Text = require "text"
unpack or= table.unpack


CHECK_INTERVAL = 1000

-- The limits of the code that's running now, or nil if there aren't any
local active

-- Sentinel value for when code exceeds the budget for try_with_budget()
OVER_BUDGET = {}

stop = (reason)->
    active.signal = setmetatable({limit: reason}, Errhand.ExitSignal)
    error(active.signal, 0)

-- Check the memory limit, if `extra_bytes` more bytes were used
check_memory = (extra_bytes=0)->
    return unless active and active.limits.memory
    error(active.signal, 0) if active.signal
    used = -> collectgarbage("count") + extra_bytes/1024 - active.start_memory
    if used! > active.limits.memory
        -- Some of the memory may just be garbage
        collectgarbage!
        stop("memory") if used! > active.limits.memory

check = ->
    return unless active
    -- The hook can also run in the code that started the limited run (after the limited
    -- code stops, but before the run is over), since LuaJIT's hook is global, and a
    -- nested run's host has the outer run's hook. That code mustn't be stopped, or the
    -- run would never finish and the limits would stay active
    return if coroutine.running! == active.host
    error(active.signal, 0) if active.signal
    active.instructions += CHECK_INTERVAL
    -- This comes before the limit checks, so a budget can be all of the remaining
    -- instructions, and running out of it won't count as running out of instructions
    error(OVER_BUDGET, 0) if active.soft_limit and active.instructions > active.soft_limit
    {:instructions, :seconds} = active.limits
    stop("instructions") if instructions and active.instructions > instructions
    stop("time") if seconds and os.clock! - active.start_time > seconds
    check_memory!

-- Coroutines in Lua 5.x each need their own hook, so coroutines get the hook when
-- they're resumed. (On LuaJIT, the hook is global.)
hook_coroutine = (co)->
    -- (debug.sethook(nil, ...) would remove the hook from the code that's running)
    debug.sethook(co, check, "", CHECK_INTERVAL) if active and not jit and type(co) == 'thread'

-- If the code ran out of a limit while it was in pcall(), coroutine.resume(), etc.,
-- keep stopping it
keep_stopping = (...)->
    error(active.signal, 0) if active and active.signal
    return ...

limited_pcall = (...)-> keep_stopping(pcall(...))
limited_xpcall = (...)-> keep_stopping(xpcall(...))
limited_resume = (co, ...)->
    hook_coroutine(co)
    return keep_stopping(coroutine.resume(co, ...))
limited_wrap = (fn)->
    co = coroutine.create(fn)
    finish = (ok, ...)->
        error((...), 0) unless ok
        return ...
    return (...)-> finish(limited_resume(co, ...))

-- Functions that can make a lot of text in one call
string_rep = string.rep
limited_rep = (s, n, sep)->
    if active and type(n) == 'number'
        check_memory(#tostring(s) * n + (sep and #tostring(sep) * n or 0))
    return string_rep(s, n, sep)
-- Lua 5.5 doesn't count strings made with Lua's C string buffers (like the results of
-- string.rep() and table.concat()) in collectgarbage("count"), so the size of the text
-- these functions return is added to the memory that's used
buffer_strings_are_counted = do
    before = collectgarbage("count")
    s = string_rep("x", 100000)
    collectgarbage("count") - before > 50
-- Lua's pattern matcher runs in C, where the instruction hook can't interrupt it, so a
-- pattern with several quantifiers (like "a-a-a-a-a-b") on a long subject can backtrack
-- for a very long time. Before matching, this estimates the worst case and stops if it's
-- too big. It's conservative (it only catches clearly catastrophic cases) and best-effort,
-- like the memory limit; for a hard guarantee, run untrusted code in a separate process.
PATTERN_BUDGET = 1e8
log = math.log
count_quantifiers = (patt)->
    n = 0
    i, len = 1, #patt
    in_class = false
    while i <= len
        c = string.sub(patt, i, i)
        if c == '%'
            i += 2
            continue
        if in_class
            in_class = false if c == ']'
        elseif c == '['
            in_class = true
        elseif c == '*' or c == '+' or c == '-'
            n += 1
        i += 1
    return n

check_pattern = (subject, patt, plain)->
    return unless active
    return if plain
    q = count_quantifiers(tostring(patt))
    return if q < 2
    subject_length = #tostring(subject)
    return if subject_length < 2
    -- Estimate subject_length^q in log space, to avoid making a huge number
    if q * log(subject_length) > log(PATTERN_BUDGET)
        stop("instructions")

checking_memory_after = (fn)->
    after = (...)->
        if active and active.limits.memory
            extra_bytes = 0
            unless buffer_strings_are_counted
                for i=1,select("#", ...)
                    value = select(i, ...)
                    extra_bytes += #value if type(value) == 'string'
            check_memory(extra_bytes)
        return ...
    return (...)-> after(fn(...))

-- Functions that take (subject, pattern, ...) check the pattern first
checking_pattern = (fn)-> (s, patt, ...)->
    check_pattern(s, patt)
    return fn(s, patt, ...)
-- (find(subject, pattern, init, plain) doesn't need to check plain text searches)
checking_find_pattern = (fn)-> (s, patt, init, plain, ...)->
    check_pattern(s, patt, plain)
    return fn(s, patt, init, plain, ...)

-- Nomsu's text methods that match patterns or make a lot of text check the limits.
-- (Lua's own names for these, like Text.match, are left alone, since Nomsu uses them on
-- large inputs, like a whole file, while running limited code.)
for name in *{"matches", "matching", "matching_groups", "all_matches_of", "split", "isplit"}
    Text[name] = checking_pattern(Text[name])
for name in *{"position_of", "position_of_1_after"}
    Text[name] = checking_find_pattern(Text[name])
with_replacement = Text.as_lua_id("with 1 ->")
Text[with_replacement] = checking_memory_after(checking_pattern(Text[with_replacement]))
Text.rep = limited_rep
Text.gsub = checking_memory_after(Text.gsub)
Text.format = checking_memory_after(Text.format)

-- A copy of Lua's string library for limited code, without string.dump
limited_string_library = ->
    lib = {k,v for k,v in pairs(string) when k != "dump"}
    lib.match, lib.gmatch = checking_pattern(string.match), checking_pattern(string.gmatch)
    lib.find = checking_find_pattern(string.find)
    lib.gsub = checking_memory_after(checking_pattern(string.gsub))
    lib.rep, lib.format = limited_rep, Text.format
    return lib

-- Run fn(...) with limits, returning what it returns, or false and a limit signal if it
-- ran out of a limit. Limited code that runs more limited code only has the outer limits.
run_limited = (limits, fn, ...)->
    return fn(...) if active or not limits
    active = {
        :limits, instructions: 0, start_time: os.clock!,
        start_memory: collectgarbage("count"), host: coroutine.running!
    }
    co = coroutine.create(fn)
    local jit_was_on, old_hook
    if jit
        jit_was_on = jit.status!
        jit.off!
        old_hook = {debug.gethook!}
        debug.sethook(check, "", CHECK_INTERVAL)
    else
        debug.sethook(co, check, "", CHECK_INTERVAL)
    results = {n: 0}
    collect = (...)-> results = {n: select("#", ...), ...}
    collect coroutine.resume(co, ...)
    signal = active.signal
    active = nil
    if jit
        if old_hook[1] then debug.sethook(unpack(old_hook)) else debug.sethook!
        jit.on! if jit_was_on
    -- If the code ran out of a limit while handling an error, it might not have
    -- returned the limit signal
    return false, signal if signal
    unless results[1]
        error(results[2], 0)
    if coroutine.status(co) != "dead"
        error("Code can't yield outside of a coroutine.", 0)
    return unpack(results, 2, results.n)

-- Run trusted code (like code that builds a sandbox) without counting it against the
-- limits of the code that's running. Limited runs inside it get limits of their own. CPU
-- time still passes for the code that's running, so its time limit still applies.
run_unlimited = (fn, ...)->
    outer = active
    active = nil
    finish = (ok, ...)->
        active = outer
        error((...), 0) unless ok
        return ...
    return finish(pcall(fn, ...))

-- How many more instructions the code that's running can use
remaining_instructions = ->
    limit = active and active.limits.instructions
    return limit and limit - active.instructions or math.huge

-- Run optional trusted work (like finding suggestions for an error message) on a budget
-- of instructions, which count against the limits of the code that's running. This
-- returns true and fn's results, or false if fn went over its budget. Budgets can be
-- nested. fn is always called from pcall, so it's at the same stack depth with or
-- without limits.
try_with_budget = (budget, fn, ...)->
    outer = active and active.soft_limit
    active.soft_limit = math.min(outer or math.huge, active.instructions + budget) if active
    finish = (ok, ...)->
        active.soft_limit = outer if active
        return false if not ok and (...) == OVER_BUDGET
        error((...), 0) unless ok
        return true, ...
    return finish(pcall(fn, ...))

return {
    :run_limited, :run_unlimited, :try_with_budget, :remaining_instructions,
    :checking_memory_after, :limited_string_library,
    pcall: limited_pcall, xpcall: limited_xpcall, resume: limited_resume, wrap: limited_wrap
}