Skip to content

Home › Pipeline

Sandboxed VM ​

Ouro provides two execution surfaces over the same pure-Luau v3–v14 register VM (experimental v100 class bytecode is rejected cleanly):

  • High-level sandboxes (Ouro.run and Ouro.sandbox): Safe by default, backed by explicit named presets ("strict", "balanced", "trusted"), reusable policies, :fork() per-script isolation, and pcall-style (ok, ...resultsOrErr) execution.
  • Low-level loaders (Ouro.load, VM.loadBytecode, VM.loadProto): Uncoupled primitives that isolate environments (inheritHost = false) and run on the unguarded @native dispatch loop unless budgets or hooks are explicitly configured.
text
Ouro.run / Ouro.sandbox (presets, :fork, :reset) ──┐
                                                   ▼
Ouro.load / VM.loadBytecode / VM.loadProto ────▶ Verifier + Predecoder (v3–v14)
                                                   │
                                                   ▼
                                                 ModuleContext (isGuarded?)
                                                   ├── false ─▶ Dispatch.luau (@native fast loop)
                                                   └── true  ─▶ DispatchGuarded.luau (budgets, hooks, ResourceLimits)

High-Level Execution (Ouro.run & Ouro.sandbox) ​

Use Ouro.run for one-shot sandboxed execution, or Ouro.sandbox to define a policy once and share it across scripts:

luau
--!strict
local Ouro = require("./ouro")

-- One-shot safe execution (defaults to preset = "balanced", mode = "text" for strings)
local ok, total = Ouro.run("local a, b = ...; return a + b", {
	preset = "strict",
}, 20, 22)
assert(ok and total == 42)

-- Reusable policy handle with custom host APIs
local policy = Ouro.sandbox({
	preset = "strict",
	globals = {
		round = math.round,
	},
})

-- Fork isolated per-script environments with independent PCG32 math.random state
local childA = policy:fork()
local childB = policy:fork()

local okA, valA = childA:run("x = math.random(1, 100); return x")
local okB, seenA, rounded = childB:run("return x, round(3.6)")
assert(okA and type(valA) == "number")
assert(okB and seenA == nil and rounded == 4)

-- Precompile once under the sandbox's compile policy, then load & reset budgets across runs
local bytecode = assert(policy:compile("local n = ...; return round(n * 1.5)"))
local fn = assert(childA:load(bytecode, { mode = "binary" }))
assert(fn(4) == 6)
childA:reset()
assert(fn(6) == 9)

Built-In Safety Presets (Ouro.PRESETS) ​

Every preset definition is frozen and inspectable at runtime via Ouro.PRESETS:

PresetLibrariesallowDirectivesinstructionLimitcallLimittimeoutmaxInstructionsresourceLimits
"strict"base, bit32, math, string, table, utf8, vectorfalse250,000640.05s100,00064 KiB str/buf, 4,096 tbl, 128 pat, 25k steps, 4 MiB mem
"balanced" (default)"strict" + buffer, coroutine, osfalse1,000,0001280.5s500,000VM.DEFAULT_RESOURCE_LIMITS (1 MiB str/buf, 65,536 tbl, 256 pat, 100k steps, 16 MiB mem)
"trusted"All standard libraries (nil)trueUnlimited (nil)VM ceiling (nil)Unlimited (nil)Compiler default (nil)Disabled (nil, zero wrapper overhead)

Pass any individual field in SandboxOptions or RunOptions to override the preset. Pass false for instructionLimit, callLimit, timeout, or resourceLimits to disable a preset cap explicitly.

Sandbox Handle Methods ​

MemberBehavior
sandbox.presetActive preset name ("strict", "balanced", or "trusted").
sandbox.envIsolated global environment table owned by this sandbox.
sandbox.readOnlytrue when guest global writes and sandbox:set are blocked.
sandbox.allowDirectivestrue when --!optimize/--!native/@native escalation is permitted.
sandbox:run(chunk, ...args)Loads and executes chunk (source, binary buffer, or ProtoModule) with ...args, returning (ok, ...resultsOrErr).
sandbox:load(chunk, options?)Loads chunk into a reusable callable closure (fn?, err?) with optional per-chunk overrides (SandboxLoadOptions).
sandbox:compile(source, options?)Compiles source or a ParseResult under the sandbox's compile policy (allowDirectives, maxInstructions), returning (bytecode?, err?).
sandbox:fork(overrides?)Creates a child Sandbox inheriting this policy and globals, backed by a fresh writable overlay and independent PCG32 math.random state.
sandbox:reset()Resets instruction, memory, and timeout budgets on closures loaded through this sandbox handle.
sandbox:get(name) / sandbox:set(name, value)Reads or writes a top-level global in sandbox.env (:set throws if readOnly = true).

Low-Level Fast Loading (Ouro.load) ​

Use Ouro.load, VM.loadBytecode, or VM.loadProto when you want direct closure loading without a Sandbox wrapper:

luau
--!strict
local Ouro = require("./ouro")

-- Load Luau source on the unguarded @native dispatch loop (isolated env by default)
local runSource = assert(Ouro.load("local n = ...; return n * n"))
assert(runSource(7) == 49)

-- Load precompiled binary bytecode directly without invoking the compiler
local bytecode = assert(Ouro.compile("return 'from bytecode'"))
local runBin = assert(Ouro.VM.loadBytecode(bytecode))
assert(runBin() == "from bytecode")

Low-level loaders have zero hidden coupling:

  • Default mode: Treats string inputs as "text" and buffer inputs as "binary". Pass mode = "binary" for binary bytecode strings or mode = "auto" to sniff headers.
  • No implicit wrappers or directive rewriting: Setting instructionLimit, callLimit, timeout, or interrupt on Ouro.load enables only the limits you specify. Opt into resourceLimits (for example Ouro.VM.DEFAULT_RESOURCE_LIMITS) and compile = { allowDirectives = false } explicitly, or use Ouro.run / Ouro.sandbox for curated presets.
  • Default safety ceilings: Even unguarded closures enforce safe recursion and stack ceilings (20,000 active call frames and 1,000,000 active stack slots).

Manual Environments (VM.createEnvironment & VM.forkEnvironment) ​

When options.env is omitted, Ouro.load creates a fresh pure-Luau VM.createEnvironment() table and never inherits outer thread globals. Share a frozen standard-library environment across chunks with VM.forkEnvironment(baseEnv, overrides?):

luau
--!strict
local Ouro = require("./ouro")

local sharedBase = Ouro.VM.createEnvironment({
	round = math.round,
}, {
	libraries = { "base", "math", "string", "table" },
	readOnly = true,
	resourceLimits = {
		maxStringLength = 16_384,
		maxTableSize = 1_000,
	},
})

-- Each fork gets isolated globals and its own 64-bit PCG32 math.random state
local chunkA = assert(Ouro.load("x = math.random(1, 100); return x", {
	env = Ouro.VM.forkEnvironment(sharedBase),
}))
local chunkB = assert(Ouro.load("return x, round(3.6)", {
	env = Ouro.VM.forkEnvironment(sharedBase),
}))

local a = chunkA()
local seenFromA, rounded = chunkB()
assert(type(a) == "number" and seenFromA == nil and rounded == 4)

Guest environments include guest-aware debug.traceback/info, collectgarbage("count" | "collect"), isolated per-environment PCG32 math.random state (keeping math.* fastcalls intact), and locked metatables. Writable and forked environments lock __metatable = "locked", while readOnly = true returns a flat frozen table (inheritHost = false) or a locked read-only proxy (inheritHost = true).

FieldTypeDefault / Behavior
inheritHostboolean?false. Enables non-standard host or Roblox globals (script and loadstring stay omitted; _G, getfenv, setfenv, debug, error, and xpcall remain sandboxed).
libraries{ string }?nil (all libraries). Allowlist any subset of "base", "bit32", "buffer", "coroutine", "debug", "math", "os", "string", "table", "utf8", "vector".
readOnlyboolean?false. Freezes the table when inheritHost = false, or returns a locked read-only proxy when inheritHost = true.
resourceLimitsResourceLimits?Optional caps (maxStringLength, maxTableSize, maxBufferSize, maxPatternLength, maxPatternSteps, maxMemoryBytes). Attached with zero overhead when omitted.

NOTE

Inside VM environments on both hosts, getmetatable("") returns "The metatable is locked". When "string" is omitted from libraries, VM dispatch also blocks string indexing and method calls (("abc"):upper(), ("").find).

Execution Guards & Global Hooks ​

Configure instruction budgets, call-depth caps, wall-clock deadlines, allocation limits, and global hooks on Ouro.sandbox, Ouro.run, or Ouro.load. Unguarded VM loops still run without guard overhead:

luau
--!strict
local Ouro = require("./ouro")

local globals: { [string]: any } = { bonus = 2 }
local env = Ouro.VM.forkEnvironment(Ouro.VM.createEnvironment(nil, { readOnly = true }))

local fn = assert(Ouro.load([[
	score = 38
	return score + bonus + math.max(1, 2)
]], {
	name = "=guarded",
	env = env,
	instructionLimit = 50_000,
	callLimit = 64,
	timeout = 0.25,
	interruptInterval = 1_024,
	safeEnv = true,
	resourceLimits = {
		maxStringLength = 65_536,
		maxTableSize = 10_000,
		maxPatternSteps = 100_000,
		maxMemoryBytes = 16_777_216,
	},
	getGlobal = function(name, currentEnv)
		return globals[name] or currentEnv[name]
	end,
	setGlobal = function(name, value, currentEnv)
		globals[name] = value
		currentEnv[name] = value
	end,
}))

assert(fn() == 42)

-- Reset instruction count, memory counter, and lazy timeout clock before reusing fn
Ouro.VM.resetBudget(fn)
assert(fn() == 42)

Same-context pcall, xpcall, and coroutine.resume cannot catch aborts from instructionLimit, timeout, interrupt, or maxMemoryBytes, so a runaway guest script cannot swallow its own cancellation.

FieldTypeBehavior
namestring?Chunk name in stack traces ([string "..."] for text, "=chunk" for binary/ProtoModule).
env{ [any]: any }?Global environment table (defaults to a fresh isolated VM.createEnvironment()).
compileCompileOptions?Compiler options when chunk is Luau source.
decoderBytecodeDecoder?Custom opcode decoder matching CompileOptions.encoder.
modeLoadMode?"text" | "binary" | "auto".
timeoutnumber?Wall-clock deadline in seconds (os.clock()), started lazily on the first call.
instructionLimitnumber?Maximum VM instructions before aborting execution.
callLimitnumber?Maximum active guest call frames across nested calls and coroutines.
interruptIntervalnumber?Instruction interval between interrupt and timeout checks (default 4,096).
interrupt(() -> boolean?)?Periodic hook; return false, yield, or error to stop execution.
getGlobal((name: string, env: { [any]: any }) -> any)?Intercepts global reads across GETGLOBAL, unresolved GETIMPORT, and string keys on _G.
setGlobal((name: string, value: any, env: { [any]: any }) -> ())?Intercepts global writes (SETGLOBAL and _G[k] = v).
safeEnvboolean?Keeps unmodified built-in roots present in env on fast FASTCALL and GETIMPORT paths alongside getGlobal.
resourceLimits(ResourceLimits | false)?Opt-in stdlib, pattern, and memory caps (false disables caps inherited from env).
onCall((info: DebugFrameInfo) -> ())?Fires when entering a VM closure frame.
onReturn((info: DebugFrameInfo) -> ())?Fires before returning from a VM closure frame.
onLine((line: number, info: DebugFrameInfo) -> ())?Fires when execution moves to a new source line.
onBreak((line: number, info: DebugFrameInfo) -> ())?Fires on LOP_BREAK instructions.

Precompiled Loading, Coverage & Debugging ​

Ouro.VM exposes direct loaders that skip the compiler alongside line coverage, debugger callbacks, and closure/upvalue inspection. VM.cloneFunction(fn, newEnv?, loadOptions?) merges partial loadOptions over the source closure's context and tightens resourceLimits against newEnv:

luau
--!strict
local Ouro = require("./ouro")
local VM = Ouro.VM

-- Load binary bytecode without touching Ouro.Compiler at runtime
local bin = assert(Ouro.compile("local k = ...\nreturn function(n) return n + k end", {
	coverageLevel = 1,
}))
local linesSeen = 0
local makeAdder = assert(VM.loadBytecode(bin, {
	onLine = function(_line, _info)
		linesSeen += 1
	end,
}))

local addTen = makeAdder(10)
assert(addTen(32) == 42)
assert(linesSeen > 0)

-- Inspect line hit counts (`coverageLevel` 1 or 2)
local cov = VM.getCoverage(makeAdder)
assert(cov ~= nil and #cov > 0)

-- Read or mutate 1-based upvalues and clone closures into a new environment
local upvals = VM.getUpvalues(addTen)
assert(upvals ~= nil and #upvals == 1 and upvals[1].value == 10)
assert(VM.setUpvalue(addTen, 1, 20))
assert(addTen(22) == 42)

local cloned = assert(VM.cloneFunction(addTen, VM.createEnvironment()))
assert(cloned(22) == 42)

VM.loadProto(protoModule, options?) instantiates closures directly from an in-memory ProtoModule, caching decoded templates on deeply frozen modules while snapshotting mutable ones.

See Security & Sandbox for sandbox threat mitigations and Debugging, Tracing & Coverage for full recipes.