Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Module 14: Versions, sandboxes, and hosts

Objectives: LO-14.1, LO-14.2, LO-14.3
Prerequisites: Module 6, Module 9, and Module 10
Time: about 10 hours: 3 for this reading, 2 for Lab 14, 2 for the practice, and 3 for Self-test 2, which follows this module

Most Lua code doesn’t run in the standalone lua. It runs inside a host: an editor, a database, a document converter, or a game. The host chooses which Lua runs your code, what your code can reach, and when it runs. This module covers the three consequences. Your code may meet a Lua other than 5.4, so it detects what it can use. A host that runs other people’s code must limit what that code can do. And code written for a host is shaped by that host’s API, which tests replace with a stand-in.

The Luas you will meet

Four Luas are in wide use, and the course’s notebook environment has all four: %%lua --version 5.1, --version luajit, and --version 5.5 run a cell on the others.

The differences that matter most, measured in the course’s notebook environment:

Feature5.1LuaJIT 2.15.45.5
Integers: 10 / 2 prints5 (no integers)5 (no integers)5.05.0
7 // 2 and 6 & 3Syntax errorsSyntax errors (the bit library instead)3 and 23 and 2
gotoSyntax errorYesYesYes
<const> and <close>Syntax errorSyntax errorYesYes
Unpacking a listunpackunpacktable.unpacktable.unpack
table.pack, utf8, math.typeNoneNoneAllAll
load with a string, a mode, and an environmentNo: loadstring and setfenvYesYesYes
_ENVNo: setfenvNo: setfenvYesYes
The ffi libraryNoYesNoNo
string.format("%d", 3.5)33Error: no integer representationSame error
tostring(0.1 + 0.2)0.30.30.30.30000000000000004

Earlier versions print a float with 14 significant digits. The notebook environment’s Lua 5.5 printed 17 whenever 14 didn’t give back the same number: 1/3 as 0.33333333333333331, and 100 * 1.1 as 110.00000000000001. The manual doesn’t list this among the incompatibilities, but a test that compares printed output fails on it.

What Lua 5.5 changes

Section 8 of the Lua 5.5 Reference Manual lists the changes that can break 5.4 code:

Detect features, not versions

Code that must run on several Luas asks for each feature it needs, instead of reading the version. _VERSION is "Lua 5.1" in LuaJIT, which nonetheless has goto and the newer load; a test of the version gets both wrong.

-- A missing function: use the one that exists.
local unpack = table.unpack or unpack

-- Count code points in text already known to be valid UTF-8.
local function utf8_len(s)
  if utf8 then return utf8.len(s) end
  return select(2, s:gsub("[^\128-\191]", ""))  -- count the bytes that start a character
end

-- Missing syntax: try to compile it. On 5.1 and LuaJIT, the chunk doesn't compile, and the
-- fallback gives the same result, because every number there is a float.
local chunk = (loadstring or load)("return function(a, b) return a // b end")
local idiv = chunk and chunk() or function(a, b) return math.floor(a / b) end

The last example can’t write a // b directly: a file that contains it fails to compile on 5.1 before any line runs. Code that must compile everywhere keeps newer syntax inside a string and compiles it only where it works. math.type, jit (a global table that only LuaJIT has), and pcall(load, "return 1", "=probe", "t", {}), which fails on 5.1, are other useful probes.

The 5.1 and LuaJIT builds in the lab use double-precision numbers. Above 253, consecutive integers can round to the same value. To keep a large database ID exact across these versions, read it as a string and keep it as text. For arithmetic, choose a representation with the required range. The course’s Lua 5.4 build has 64-bit integers, and LuaJIT offers 64-bit C integer types through the library described next.

LuaJIT’s FFI

LuaJIT has an extension that the other Luas lack: the FFI library (foreign function interface). It lets Lua code declare C types and functions in C’s own syntax, call C functions directly, and allocate C data. It does the job of Module 13’s C modules without writing or compiling any C:

local ffi = require("ffi")
ffi.cdef[[
size_t strlen(const char *s);
int abs(int n);
]]
print(ffi.C.strlen("hello"), ffi.C.abs(-7))   --> 5ULL  7

ffi.cdef reads C declarations, here of two functions from the C standard library. ffi.C is the namespace of the C library the program already uses, so ffi.C.strlen calls C’s own strlen. Each result comes back by its C type. An int becomes a Lua number. A size_t is a 64-bit integer, which LuaJIT’s numbers can’t always hold exactly, so it stays a cdata, a C value that Lua holds, and prints as 5ULL; tonumber turns it into a number.

ffi.new allocates C data, filled with zeros, which the garbage collector frees once nothing refers to it. A C array is indexed from 0, not 1:

local squares = ffi.new("double[?]", 4)   -- four doubles; the ? takes its size from the 4
for i = 0, 3 do squares[i] = (i + 1) ^ 2 end
print(squares[3], ffi.sizeof(squares))     --> 16  32

The FFI trades safety for speed. LuaJIT’s documentation says that calls to C functions can be inlined in JIT-compiled code (built into the machine code that LuaJIT generates, with no stack in between), unlike calls to functions bound through the classic C API. It also says that the FFI does nothing to stop you from accessing arrays out of bounds or misdeclaring C functions. So squares[10] reads whatever memory lies past the end, without an error, and a wrong cdef can crash the whole process. LuaJIT does check conversions: squares[0] = "x" raises cannot convert 'string' to 'double'. And a C array isn’t a table: #squares and ipairs(squares) raise errors.

Only LuaJIT has the FFI, so portable code detects it, as the previous section does for other features, and keeps a plain-Lua path:

local has_ffi, ffi = pcall(require, "ffi")

-- The sum of the first n squares: in a C array on LuaJIT, in a Lua table elsewhere.
local function sum_of_squares(n)
  local total = 0
  if has_ffi then
    local a = ffi.new("double[?]", n)   -- indexed from 0
    for i = 0, n - 1 do a[i] = (i + 1) ^ 2 end
    for i = 0, n - 1 do total = total + a[i] end
  else
    local a = {}                        -- indexed from 1
    for i = 1, n do a[i] = i ^ 2 end
    for i = 1, n do total = total + a[i] end
  end
  return total
end

print(sum_of_squares(4))   --> 30 on LuaJIT and 5.1, and 30.0 on 5.4

The two branches index differently, which is the commonest bug in code that uses the FFI. Keep C arrays behind a function like this one, so the rest of the program never sees an array that starts at 0 and has no bounds.

Sandboxes

A sandbox runs code you don’t trust, such as a plugin or a user’s script, so that it can do only what you allow. Lua has no sandbox built in, but it has the parts to build one, each covering one way the code could do harm:

ThreatPartWhere the course covers it
Reaching the file system, the OS, or the host’s globalsAn environment built from an allowlistModules 6 and 10
Running bytecode that crashes the interpreterload in text modeModule 10
Running foreverAn instruction-count hook, in the plugin’s own coroutineThis module; coroutines in Module 9
Using all the memoryA memory check in the same hookThis module; collectgarbage("count") in Module 12

The environment

Every global name goes through a table. In Lua 5.4, the compiler turns each name that isn’t a local into a field of _ENV, a variable that every chunk has from its start: x = 1 compiles to _ENV.x = 1, and print(x) to _ENV.print(_ENV.x). _ENV starts as the global table, _G, which is why every chunk shares the same globals. A block can declare an _ENV of its own:

local print = print            -- keep print: inside the block, globals come from the new table
do
  local _ENV = { x = 10 }
  y = x * 2                    -- reads and writes the table, not the globals
  print(x, y)                  --> 10  20
end
print(y)                       --> nil: the global table has no y

Lua 5.1 and LuaJIT have no _ENV. There, local _ENV = {} is an ordinary local that changes nothing, and setfenv(f, env) sets a function’s environment instead.

load’s fourth argument does for a whole chunk what local _ENV does for a block: it becomes the chunk’s _ENV. So load(code, "=plugin", "t", env) compiles the plugin with env as its globals, and the plugin sees only what env holds. Build env from an allowlist, a list of what plugins may use, never by copying _G and deleting what looks dangerous: a list of what to remove misses whatever you didn’t think of, and whatever a later version adds. A typical allowlist holds assert, error, ipairs, next, pairs, print, select, tonumber, tostring, and type, and copies of the string, table, and math tables, so that a plugin that changes string.upper changes only its own copy.

Each function left out has a reason:

String methods stay reachable even so: ("x"):rep(3) works with an empty environment, because it goes through the string metatable, not through a global. That is safe as long as the plugin can’t get the metatable itself.

Text mode

The "t" in load(code, name, "t", env) refuses precompiled bytecode with attempt to load a binary chunk (mode is 't'). Lua checks that a binary chunk is well formed, but not that its instructions make sense, and the manual warns that maliciously crafted bytecode can crash the interpreter. On Lua 5.1, loadstring has no mode: it accepted a chunk made with string.dump and ran it, so a 5.1 sandbox must refuse a chunk whose first byte is 27, the escape character that every binary chunk starts with.

Time and memory

The debug library, which a host keeps for itself, can set a hook: a function that Lua calls when certain events happen. debug.sethook(co, hook, "", n) calls hook after every n instructions that the coroutine co runs; the empty string asks for no other events. A sandbox runs the plugin in a coroutine of its own and sets the hook there, because a hook belongs to one coroutine: a coroutine created later has none, so a plugin given coroutine could escape a hook set on the main one. The hook adds n to a count of instructions used, checks collectgarbage("count") against the memory the sandbox started with, and raises an error when either goes over its limit.

One error isn’t enough, because the plugin can catch it. If plugins get pcall, this one survives the first error and keeps going:

while true do
  pcall(function() while true do end end)
end

So once the limit is reached, the hook switches to every instruction, with debug.sethook(co, stop, "", 1), and raises the error each time. The plugin’s code between pcalls then fails too, and the error reaches the top of the coroutine, where coroutine.resume returns it to the sandbox. Lab 14 builds this sandbox.

A second escape is harder to see. Lua limits how deeply C calls can nest (about 200 levels in Lua 5.4), and calling a hook written in Lua is a C call, so a plugin that recurses through pcall until the C stack is nearly full leaves no room to call the hook:

local function f() while true do pcall(f) end end
f()

The hook fails with C stack overflow before its first line runs, and the plugin’s pcall catches that error too. In a test with the standalone lua, the instruction limit never stopped this plugin; the memory check happened to stop it after 13.6 seconds. In the notebook environment’s Lua 5.4, a sandbox without a memory check was still running when it was killed after two minutes. The fix is to give plugins a pcall that catches ordinary errors but passes the sandbox’s own, and stack overflows, on to its caller; Lab 14 has you write it. With it, the same plugin stopped at once with C stack overflow.

What a sandbox in Lua can’t stop

The hook runs between Lua instructions, and the manual says the count event happens only while Lua runs a Lua function. Work done inside one C function call is invisible to it:

The remedies are outside Lua. The C API’s lua_newstate takes an allocator function, which can refuse to allocate past a limit; lupa offers the same as LuaRuntime(max_memory=…), and with a limit of 50 MB, pcall(string.rep, "x", 2e8) returned false and not enough memory. A time limit that holds whatever the plugin does needs a second thread or process that can stop the first: a plugin in its own OS process can be killed. A sandbox’s documentation should list these gaps, as the final project’s sandbox track asks in its THREATS.md.

Writing for a host

A host decides three things that shape your code:

Keep the host in a thin layer

Code that calls the host’s API directly can be tested only inside the host. Split it: put the logic in functions that take and return plain values, and the calls to the host in a thin layer that does nothing else. Here is a Neovim plugin that removes the spaces and tabs at the ends of a buffer’s lines:

local trim = {}

-- The logic, which never touches the host: the trimmed lines, and how many changed.
function trim.lines(lines)
  local out, changed = {}, 0
  for i, line in ipairs(lines) do
    out[i] = line:gsub("[ \t]+$", "")
    if out[i] ~= line then changed = changed + 1 end
  end
  return out, changed
end

-- The thin layer: reads the buffer through the host's API, and writes it only if a line changed.
function trim.buffer(api, buf)
  local lines = api.nvim_buf_get_lines(buf, 0, -1, false)
  local out, changed = trim.lines(lines)
  if changed > 0 then api.nvim_buf_set_lines(buf, 0, -1, false, out) end
  return changed
end

Neovim’s API counts lines from 0, ends ranges before their last index, and reads -1 as “after the last line”, so 0, -1 is the whole buffer. false turns off strict indexing, which would make an out-of-range index an error instead of clamping it to the buffer.

trim.buffer takes api as an argument instead of reading the global vim.api, so a test can pass a stand-in: a table with the same functions, which keeps the lines in a list and records each call. The test then checks the records, for example that the plugin read the buffer once and didn’t write it when no line changed. Lab 14 builds this stand-in, adds a version of the plugin that waits for vim.schedule, and runs the tests on LuaJIT, which Neovim’s documentation recommends building it with, as well as on 5.4. A stand-in shows that your code uses the API the way you meant; it can’t show that you understood the API correctly, so try the plugin in the real host too.

Common misconceptions

BeliefWhat is trueExample that breaks it
FFI arrays work like Lua tablesThey start at 0, have no bounds checks, and aren’t tablessquares[10] reads past the end without an error; #squares raises one
A global variable is a variable of its ownIt is a field of _ENV, which is the global table unless a block or load gives anotherAfter local _ENV = {}, even print is nil
_VERSION tells you what you can useLuaJIT reports Lua 5.1 and has features 5.1 lacksgoto works on LuaJIT
A file can test for // before using itA file with // doesn’t compile on 5.1 at allCompile newer syntax from a string with load
Removing os and io from _G makes a sandboxWhatever you didn’t think of staysload("return os")()
An empty environment hides the string libraryString methods come through the string metatable("x"):rep(3)
One error from the hook stops a pluginThe plugin’s pcall catches itwhile true do pcall(f) end
The count hook bounds a plugin’s timeIt runs only between Lua instructions("a"):rep(1000):find(".-.-b")
A test with a stand-in proves the plugin works in the hostIt proves the plugin calls the stand-in as you meantTry it in the real host too

Summary

Self-check

  1. A function uses table.unpack and math.type. Which of the four Luas can run it unchanged, and how would you make it run on the others?

    Answer

    Lua 5.4 and 5.5. On 5.1 and LuaJIT, use local unpack = table.unpack or unpack, and replace math.type(x) == "integer" with a check that makes sense where every number is a float, such as x == math.floor(x), which accepts 3.0 as well.

  2. Why does a sandbox run the plugin in a coroutine of its own, instead of setting the hook on the coroutine the host runs in?

    Answer

    A hook belongs to one coroutine, so setting it on the plugin’s coroutine limits the plugin without slowing the host. It also lets the hook keep raising errors at every instruction after a limit is reached: the host’s own code, which runs on another coroutine, isn’t affected.

  3. A sandbox’s allowlist includes setmetatable. What can a plugin do with it that runs outside the sandbox’s time limit?

    Answer

    Attach a __gc finalizer to a table: setmetatable({}, { __gc = function() while true do end end }). The collector runs finalizers with hooks turned off, whichever coroutine is running: in a test, a finalizer that looped for 2 seconds inside the plugin’s own coroutine never triggered its hook. This loop would run forever, at the next collection after the table becomes garbage, which may be long after the plugin returned.

  4. A Neovim plugin works in its tests, which use a stand-in for vim.api, but in Neovim it fails when called from a timer callback. What is the likely cause, and the fix?

    Answer

    Timer callbacks come from vim.uv, where most API functions aren’t allowed. Wrap the work in vim.schedule, so it runs on the main loop’s next turn. The stand-in didn’t enforce that rule; a stand-in only checks what you built into it.

Further reading