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.

Lab 14: Versions, sandboxes, and hosts

Objectives: LO-14.1, LO-14.2, LO-14.3
Prerequisites: the Module 14 reading and Lab 10
Time: about 2 hours

You will write one module that runs unchanged on Lua 5.1, LuaJIT, Lua 5.4, and Lua 5.5; build a sandbox and attack it until it holds; see what no sandbox written in Lua can stop; and write a Neovim plugin whose tests replace Neovim with a stand-in. Each exercise writes a Lua file into the lab’s scratch folder. As in the earlier labs, each check cell prints passed or fails with a message.

Setup

The first cell loads %%lua and defines on_every_lua, which runs Lua code on each of the four Luas and says which one failed. The sandbox’s attacks run in the standalone lua, in a process of their own with a time limit, so that a plugin the sandbox fails to stop can’t freeze the notebook.

1. One module, four Luas

Before you run the next cell, predict what each Lua prints for 10 / 2, and which of them have table.unpack and utf8.

LuaJIT calls itself Lua 5.1, though it has features that 5.1 lacks, such as goto. Change the code in the cell to try others: 7 // 2, math.type(3), #"héllo", or string.format("%d", 3.5). Expressions with // don’t compile at all on 5.1 and LuaJIT, so the cell fails there; that is the point of the next exercise.

Exercise L14.1 (LO-14.1, ★★, about 25 minutes)

Write compat.lua, so that the same file runs on all four Luas:

  • compat.unpack(list) returns the items of list, as table.unpack does.

  • compat.idiv(a, b) returns a // b, rounded down: idiv(-7, 2) is -4. Where Lua has integers, two integers give an integer.

  • compat.load_text(code, name, env) compiles code as text, never as a binary chunk, with env as its globals. It returns the function, or nil and a message.

  • compat.utf8_len(s) returns the number of UTF-8 characters in s.

Detect each feature; don’t test _VERSION. Run the cell to write the file, then run the check, which loads the file on each Lua in turn.

Hint

The file can’t contain //, or it won’t compile on 5.1. Compile a function that uses // from a string, with (loadstring or load), and use math.floor(a / b) where that fails. On 5.1, loadstring(code, name) compiles and setfenv(fn, env) sets the globals, but loadstring also accepts binary chunks, which start with the byte 27.

2. A sandbox

The sandbox is two files. guard.lua holds the start of every message the sandbox uses to stop a plugin, and the pcall it gives plugins; for now that is the real pcall, and Exercise L14.3 changes it. attack.lua runs the plugin in plugin.txt in the sandbox and prints what happened, for the Python function attack. Run the next three cells.

Exercise L14.2 (LO-14.2, ★★★, about 35 minutes)

Write the two functions of sandbox.lua:

  • sandbox.env() returns a new table holding the functions named in sandbox.SAFE, copies of the tables named in sandbox.LIBRARIES, and pcall set to guard.wrap(pcall).

  • sandbox.run(code, limits) compiles code in text mode, with the chunk name "=plugin" and a new sandbox.env(), and runs it in a coroutine of its own. A hook on that coroutine, called every 1,000 instructions, stops the plugin when it has run more than limits.instructions instructions (default 1e6), or when collectgarbage("count") has grown by more than limits.memory_kb kilobytes since the start (default 10,240). To stop it, the hook raises guard.STOPPED .. ": instruction limit" or guard.STOPPED .. ": memory limit", and from then on raises the same error at every instruction. run returns true and all of the plugin’s results, or false and a message, as a string, for any error.

Hint

coroutine.resume returns what pcall would: true and the results, or false and the error. Pack them with table.pack, so that nil results aren’t lost. Inside the hook, debug.sethook(co, raise, "", 1) replaces the hook with one that runs at every instruction.

The check attacks the sandbox. Each plugin must give the result shown in its message.

Now an attack that passes the instruction limit, which the reading explains: the plugin recurses through pcall until the C stack is nearly full, where Lua can’t call the hook. Run the next cell, which gives the plugin 5 seconds.

Exercise L14.3 (LO-14.2, ★★, about 20 minutes)

Change guard.wrap so that the pcall it returns catches errors as pcall does, except two kinds, which it raises again, unchanged, with error(message, 0): the sandbox’s own errors, which contain guard.STOPPED, and stack overflows, whose message contains stack overflow or error in error handling. Errors that aren’t strings are never of those kinds. Then run the cell above again: the plugin should now stop at once.

3. What the sandbox can’t stop

The hook runs between Lua instructions, so work done inside one C function call is invisible to it. Before you run each cell, predict whether the sandbox stops the plugin. The first builds a 100 MB string in one call to string.rep; the second runs a pattern that backtracks.

Both finished, under limits of 10 MB and a million instructions. The memory one can be stopped from outside Lua, by an allocator that refuses to allocate past a limit. lupa offers one for each Lua it runs; with a limit of 50 MB, the same call fails with not enough memory, which Lua can catch like any other error:

LuaJIT adds a gap of its own: its compiler turns a hot loop into machine code, and compiled code doesn’t call the count hook. The next cell runs an endless loop under a hook on LuaJIT twice, in a new Python process each time, with 5 seconds to finish: once with the compiler on, and once after jit.off().

4. A plugin for a host

fake.lua is a stand-in for the parts of Neovim’s vim that the next exercise uses. It keeps one buffer’s lines, records every call to vim.api, and queues the functions given to vim.schedule until a test calls run_queue, as Neovim’s event loop would on its next turn. Run the cell to write it.

Exercise L14.4 (LO-14.3, LO-14.1, ★★, about 25 minutes)

Write the three functions of trim.lua, a plugin that removes the spaces and tabs at the ends of a buffer’s lines:

  • trim.lines(lines) returns a new list of the lines, each without its trailing spaces and tabs, and the number of lines that changed. It never touches the host.

  • trim.buffer(api, buf) reads every line of buffer buf with api.nvim_buf_get_lines(buf, 0, -1, false), trims them, writes them back with api.nvim_buf_set_lines(buf, 0, -1, false, lines) only if a line changed, and returns the number that changed.

  • trim.later(vim, buf) does what trim.buffer(vim.api, buf) does, but on the event loop’s next turn, through vim.schedule, so it is safe to call from a callback where Neovim forbids changing a buffer.

Neovim runs plugins on LuaJIT, so the check runs your file there, and on Lua 5.4.

Summary

  • One file ran on four Luas by detecting each feature: table.unpack or unpack, // compiled from a string, setfenv where load takes no environment, and a byte check where loadstring takes binary chunks.

  • The sandbox stopped endless loops, loops that catch its errors, and memory growth, once its hook raised an error at every instruction and its pcall let no limit or stack overflow through.

  • It couldn’t stop work inside one C call, or compiled LuaJIT code; an allocator limit, and a separate process for time, cover what Lua can’t.

  • The plugin’s logic needed no host at all, and a stand-in that records calls tested the thin layer and the event loop’s timing, on the Lua that Neovim runs.

Next, do the Module 14 practice, and finish the final project.