Skip to main content

luaur_rt/
luau_ext.rs

1//! Luau-specific `Lua` extensions: sandboxing, safeenv, fflags, and the
2//! per-VM compiler. Mirrors the Luau-only parts of mlua's `Lua` surface.
3
4use std::cell::RefCell;
5use std::collections::HashMap;
6
7use crate::compiler::Compiler;
8use crate::error::{Error, Result};
9use crate::state::Lua;
10use crate::sys::*;
11use crate::table::Table;
12use crate::thread::Thread;
13
14thread_local! {
15    /// Per-VM compiler installed via `Lua::set_compiler`, keyed by global state.
16    static VM_COMPILERS: RefCell<HashMap<*mut core::ffi::c_void, Compiler>> =
17        RefCell::new(HashMap::new());
18
19    /// Per-VM `catch_rust_panics` option (recorded from `LuaOptions`), keyed by
20    /// global state. Currently recorded for parity; see `set_catch_rust_panics`.
21    static VM_CATCH_PANICS: RefCell<HashMap<*mut core::ffi::c_void, bool>> =
22        RefCell::new(HashMap::new());
23
24    /// Per-VM "is sandboxed" flag, keyed by global state. Mirrors mlua's
25    /// `extra.sandboxed`; consulted by `Lua::set_globals`.
26    static VM_SANDBOXED: RefCell<HashMap<*mut core::ffi::c_void, bool>> =
27        RefCell::new(HashMap::new());
28}
29
30/// Registry name under which `sandbox(true)` saves the ORIGINAL globals table so
31/// `sandbox(false)` can restore it. Kept in the state's registry (freed on
32/// `lua_close`), NOT in a thread-local `Table` handle: a handle owns an
33/// `XRc<LuaInner>`, so a thread-local holding it would pin the VM alive forever
34/// (the state could never drop) if the caller dropped a still-sandboxed `Lua`.
35const SANDBOX_SAVED_GLOBALS_NAME: &str = "__luaur_sandbox_saved_globals";
36
37unsafe fn global_key(state: *mut lua_State) -> *mut core::ffi::c_void {
38    unsafe { (*state).global as *mut core::ffi::c_void }
39}
40
41/// Drop this VM's compiler / catch-panics / sandboxed-flag entries so they don't
42/// leak one slot per state created. Called from `LuaInner::drop`. (These hold no
43/// Lua handle, so the state drops normally and this runs; the saved-globals table
44/// lives in the registry and is freed with the state on `lua_close`.)
45pub(crate) fn clear_vm_state(state: *mut lua_State) {
46    let key = unsafe { global_key(state) };
47    VM_COMPILERS.with(|m| {
48        m.borrow_mut().remove(&key);
49    });
50    VM_CATCH_PANICS.with(|m| {
51        m.borrow_mut().remove(&key);
52    });
53    VM_SANDBOXED.with(|m| {
54        m.borrow_mut().remove(&key);
55    });
56}
57
58impl Lua {
59    /// Enable or disable sandbox mode. Mirrors `mlua::Lua::sandbox`.
60    ///
61    /// Enabling sets every library table (and the globals table) read-only and
62    /// activates `safeenv`, then installs a fresh proxy global table (via
63    /// `luaL_sandboxthread`) so that script-level global writes go to a
64    /// throwaway table whose `__index` is the original environment. Disabling
65    /// restores the original globals table and clears the read-only/safeenv
66    /// flags.
67    ///
68    /// **DEVIATION:** Luau's standard library (as bundled in luaur) does not
69    /// register `collectgarbage`; mlua's sandbox test additionally checks that
70    /// `collectgarbage` is restricted under the sandbox. That part is not
71    /// exercisable here (see `tests/mlua_luau.rs`).
72    pub fn sandbox(&self, enabled: bool) -> Result<()> {
73        let state = self.state();
74        let key = unsafe { global_key(state) };
75        VM_SANDBOXED.with(|m| {
76            m.borrow_mut().insert(key, enabled);
77        });
78        unsafe {
79            if enabled {
80                // Save the ORIGINAL globals table (once) in the registry so we can
81                // restore it later. Registry-rooted, not a thread-local handle —
82                // see SANDBOX_SAVED_GLOBALS_NAME. `or_insert` semantics: only save
83                // if not already saved (a second sandbox(true) keeps the first).
84                if self
85                    .named_registry_value::<Table>(SANDBOX_SAVED_GLOBALS_NAME)
86                    .is_err()
87                {
88                    let original = self.globals();
89                    let _ = self.set_named_registry_value(SANDBOX_SAVED_GLOBALS_NAME, original);
90                }
91                // Make libraries + base metatables read-only and set safeenv.
92                lua_l_sandbox(state);
93                // Install the proxy global table for script-level writes.
94                lua_l_sandboxthread(state);
95            } else {
96                // Restore the original globals table (dropping the proxy and any
97                // globals written into it), then clear the saved slot.
98                if let Ok(orig) = self.named_registry_value::<Table>(SANDBOX_SAVED_GLOBALS_NAME) {
99                    orig.push_to_stack();
100                    lua_replace(state, LUA_GLOBALSINDEX);
101                    // Clear read-only + safeenv on the restored globals so it is
102                    // writable again.
103                    lua_setreadonly(state, LUA_GLOBALSINDEX, 0);
104                    lua_setsafeenv(state, LUA_GLOBALSINDEX, 0);
105                    // Also clear read-only on the library tables.
106                    self.clear_library_readonly();
107                    // Clear the saved slot so a later sandbox(true) re-saves.
108                    let _ = self.set_named_registry_value(
109                        SANDBOX_SAVED_GLOBALS_NAME,
110                        crate::value::Value::Nil,
111                    );
112                }
113            }
114        }
115        Ok(())
116    }
117
118    /// Clear the read-only flag on every library table reachable from the
119    /// (restored) globals. Used when leaving sandbox mode.
120    fn clear_library_readonly(&self) {
121        let globals = self.globals();
122        if let Ok(pairs) = globals
123            .pairs::<crate::value::Value, crate::value::Value>()
124            .collect::<Result<Vec<_>>>()
125        {
126            for (_, v) in pairs {
127                if let crate::value::Value::Table(t) = v {
128                    t.set_readonly(false);
129                }
130            }
131        }
132    }
133
134    /// Set or clear the `safeenv` flag on the globals table. Mirrors
135    /// `mlua::Globals::set_safeenv` applied to the main globals.
136    ///
137    /// `safeenv` lets the VM fast-path global reads; clearing it forces the slow
138    /// path (needed when globals/`__index` may change at runtime).
139    pub fn set_safeenv(&self, enabled: bool) {
140        let state = self.state();
141        unsafe {
142            lua_setsafeenv(state, LUA_GLOBALSINDEX, enabled as c_int);
143        }
144    }
145
146    /// Install a default [`Compiler`] used to compile every chunk loaded by this
147    /// VM (unless a chunk overrides it via
148    /// [`Chunk::set_compiler`](crate::Chunk::set_compiler)). Mirrors
149    /// `mlua::Lua::set_compiler`.
150    pub fn set_compiler(&self, compiler: Compiler) {
151        let state = self.state();
152        let key = unsafe { global_key(state) };
153        VM_COMPILERS.with(|m| {
154            m.borrow_mut().insert(key, compiler);
155        });
156    }
157
158    /// Record the `catch_rust_panics` behavioral option for this VM.
159    ///
160    /// **DEVIATION:** luaur-rt's callback trampoline always catches a Rust panic
161    /// and converts it into a catchable Lua error (so the VM is never left
162    /// half-unwound). The mlua option that lets a panic propagate as a Rust
163    /// unwind across the VM boundary is therefore recorded here but not enforced
164    /// — see the deferred `test_panic` in `tests/mlua_core.rs`.
165    pub(crate) fn set_catch_rust_panics(&self, enabled: bool) {
166        let state = self.state();
167        let key = unsafe { global_key(state) };
168        VM_CATCH_PANICS.with(|m| {
169            m.borrow_mut().insert(key, enabled);
170        });
171    }
172
173    /// Whether this VM is currently sandboxed (set by [`Lua::sandbox`]). Mirrors
174    /// mlua's `extra.sandboxed` flag; consulted by [`Lua::set_globals`].
175    pub(crate) fn is_sandboxed(&self) -> bool {
176        let state = self.state();
177        let key = unsafe { global_key(state) };
178        VM_SANDBOXED.with(|m| m.borrow().get(&key).copied().unwrap_or(false))
179    }
180
181    /// The VM-default compiler installed via [`Lua::set_compiler`], if any.
182    pub(crate) fn vm_compiler(&self) -> Option<Compiler> {
183        let state = self.state();
184        let key = unsafe { global_key(state) };
185        VM_COMPILERS.with(|m| m.borrow().get(&key).cloned())
186    }
187
188    /// Set (or clear) the metatable shared by all values of a Luau built-in
189    /// type `T`. Mirrors `mlua::Lua::set_type_metatable`.
190    ///
191    /// Implemented for [`Vector`](crate::Vector), `bool`, [`Number`](f64),
192    /// [`LuaString`](crate::LuaString), [`Function`](crate::Function),
193    /// [`Thread`](crate::Thread), and
194    /// [`LightUserData`](crate::LightUserData). Setting it installs a metatable
195    /// in the VM's global per-type metatable slot, so e.g. `v.x`/`v:method`
196    /// dispatch through it.
197    pub fn set_type_metatable<T: TypeMetatable>(&self, metatable: Option<Table>) {
198        T::set_type_metatable(self, metatable);
199    }
200
201    /// The metatable shared by all values of a Luau built-in type `T`, if one
202    /// has been installed. Mirrors `mlua::Lua::type_metatable`.
203    pub fn type_metatable<T: TypeMetatable>(&self) -> Option<Table> {
204        T::type_metatable(self)
205    }
206
207    /// Set a Luau fast-flag (FFlag) by name. Mirrors `mlua::Lua::set_fflag`.
208    ///
209    /// **DEVIATION:** luaur's FastFlags are a fixed, compile-time `FFlag` enum
210    /// rather than a string-keyed registry, so there is no way to look a flag up
211    /// by an arbitrary name. This therefore always reports the name as unknown
212    /// (`Err`) — which matches mlua's contract for an unrecognized flag (the
213    /// only behavior its `test_fflags` asserts). Known flags are configured at
214    /// VM-construction time via `luaur_common::set_all_flags`.
215    pub fn set_fflag(name: &str, _enabled: bool) -> Result<()> {
216        Err(Error::runtime(format!("fflag '{name}' is not supported")))
217    }
218}
219
220impl Thread {
221    /// Sandbox this coroutine: install a fresh proxy global table on its own
222    /// state so global writes inside the coroutine stay local to it. Mirrors
223    /// `mlua::Thread::sandbox`.
224    pub fn sandbox(&self) -> Result<()> {
225        let co = self.thread_state;
226        unsafe {
227            lua_l_sandboxthread(co);
228        }
229        Ok(())
230    }
231}
232
233/// Luau built-in types that have a shared, per-type metatable settable via
234/// [`Lua::set_type_metatable`]. Mirrors mlua's sealed `LuauType` trait.
235pub trait TypeMetatable: private::Sealed {
236    /// Push a representative value of this type onto the stack (so the VM's
237    /// `lua_setmetatable`/`lua_getmetatable` operate on the type's global slot).
238    #[doc(hidden)]
239    unsafe fn push_representative(state: *mut lua_State);
240
241    /// Install (or clear) the shared metatable for this type.
242    fn set_type_metatable(lua: &Lua, metatable: Option<Table>) {
243        let state = lua.state();
244        unsafe {
245            Self::push_representative(state);
246            match metatable {
247                Some(mt) => mt.push_to_stack(),
248                None => crate::sys::lua_pushnil(state),
249            }
250            // For a non-table/non-userdata value, `lua_setmetatable` stores the
251            // metatable in the VM's global per-type slot (`g->mt[type]`).
252            crate::sys::lua_setmetatable(state, -2);
253            // Pop the representative value left on the stack.
254            crate::sys::lua_pop(state, 1);
255        }
256    }
257
258    /// The shared metatable for this type, if installed.
259    fn type_metatable(lua: &Lua) -> Option<Table> {
260        let state = lua.state();
261        unsafe {
262            Self::push_representative(state);
263            let has = crate::sys::lua_getmetatable(state, -1);
264            if has == 0 {
265                // No metatable: pop the representative value.
266                crate::sys::lua_pop(state, 1);
267                return None;
268            }
269            // stack: [value, metatable]
270            let mt = Table::from_ref(lua.pop_ref());
271            crate::sys::lua_pop(state, 1); // pop the representative value
272            Some(mt)
273        }
274    }
275}
276
277mod private {
278    pub trait Sealed {}
279    impl Sealed for crate::vector::Vector {}
280    impl Sealed for bool {}
281    impl Sealed for f64 {}
282    impl Sealed for crate::string::LuaString {}
283    impl Sealed for crate::function::Function {}
284    impl Sealed for crate::thread::Thread {}
285    impl Sealed for crate::light_userdata::LightUserData {}
286}
287
288impl TypeMetatable for crate::vector::Vector {
289    unsafe fn push_representative(state: *mut lua_State) {
290        unsafe {
291            crate::sys::lua_pushvector_lua_state_f32_f32_f32_f32(state, 0.0, 0.0, 0.0, 0.0);
292        }
293    }
294}
295
296impl TypeMetatable for bool {
297    unsafe fn push_representative(state: *mut lua_State) {
298        unsafe { crate::sys::lua_pushboolean(state, 0) }
299    }
300}
301
302impl TypeMetatable for f64 {
303    unsafe fn push_representative(state: *mut lua_State) {
304        unsafe { crate::sys::lua_pushnumber(state, 0.0) }
305    }
306}
307
308impl TypeMetatable for crate::string::LuaString {
309    unsafe fn push_representative(state: *mut lua_State) {
310        unsafe {
311            let s = c"";
312            crate::sys::lua_pushlstring(state, s.as_ptr() as *const c_char, 0);
313        }
314    }
315}
316
317impl TypeMetatable for crate::function::Function {
318    unsafe fn push_representative(state: *mut lua_State) {
319        // Push a throwaway C function so `lua_setmetatable` targets the global
320        // function-type slot.
321        unsafe {
322            crate::sys::lua_pushcclosurek(state, Some(noop_cfn), c"".as_ptr(), 0, None);
323        }
324    }
325}
326
327impl TypeMetatable for crate::thread::Thread {
328    unsafe fn push_representative(state: *mut lua_State) {
329        // A fresh thread targets the global thread-type slot.
330        unsafe {
331            crate::sys::lua_newthread(state);
332        }
333    }
334}
335
336impl TypeMetatable for crate::light_userdata::LightUserData {
337    unsafe fn push_representative(state: *mut lua_State) {
338        crate::sys::lua_pushlightuserdatatagged(state, core::ptr::null_mut(), 0);
339    }
340}
341
342/// A do-nothing C function used as the representative value for the
343/// function-type metatable slot.
344unsafe fn noop_cfn(_state: *mut lua_State) -> c_int {
345    0
346}
347
348#[cfg(test)]
349pub(crate) fn vm_compilers_len() -> usize {
350    VM_COMPILERS.with(|m| m.borrow().len())
351}