Skip to main content

luaur_rt/
memory.rs

1//! Memory limit + memory-category control. Mirrors mlua's `Lua::set_memory_limit`
2//! and `Lua::set_memory_category`.
3//!
4//! ## Memory limit
5//!
6//! Luau routes every allocation through `global_State::frealloc(ud, ...)`. We
7//! install a limit-enforcing allocator ([`limited_alloc`]) over the default one
8//! by overwriting `frealloc`/`ud` on the global state, keyed by a heap-boxed
9//! [`MemoryControl`] that holds the cap and a pointer back to the global state
10//! (so the allocator can compare the would-be `totalbytes` to the cap). When a
11//! growing allocation would exceed the cap the allocator returns null, which the
12//! VM turns into a `LUA_ERRMEM` longjmp — surfaced by luaur-rt as
13//! [`Error::MemoryError`](crate::Error::MemoryError).
14//!
15//! A limit of `0` means "unlimited" (mlua's convention).
16//!
17//! ## Memory categories
18//!
19//! Luau tags allocations with an 8-bit *category* (`global_State::activememcat`,
20//! `memcatbytes[256]`). mlua exposes named categories; we keep a per-VM
21//! name→id table (max 255 user categories: id 0 is reserved for `"main"`),
22//! validate names (`[A-Za-z0-9_]+`), and call `lua_setmemcat`.
23
24use std::cell::RefCell;
25use std::collections::HashMap;
26
27use crate::error::{Error, Result};
28use crate::state::Lua;
29use crate::sys::*;
30
31/// The per-VM allocator control block, pointed to by `global_State::ud` once a
32/// memory limit is installed.
33struct MemoryControl {
34    /// The byte cap (`0` = unlimited).
35    limit: usize,
36    /// The global state, so the allocator can read the live `totalbytes`.
37    global: *mut core::ffi::c_void,
38    /// The original allocator we delegate to (libc realloc/free).
39    base: unsafe extern "C" fn(
40        *mut core::ffi::c_void,
41        *mut core::ffi::c_void,
42        usize,
43        usize,
44    ) -> *mut core::ffi::c_void,
45    /// The original allocator's userdata.
46    base_ud: *mut core::ffi::c_void,
47}
48
49thread_local! {
50    /// One `MemoryControl` per VM, keyed by the global-state pointer. Boxed so
51    /// its address (handed to the VM as `ud`) is stable.
52    static MEMORY_CONTROLS: RefCell<HashMap<*mut core::ffi::c_void, Box<MemoryControl>>> =
53        RefCell::new(HashMap::new());
54
55    /// Per-VM memory-category name→id table (id 0 is reserved for `"main"`).
56    static MEMORY_CATEGORIES: RefCell<HashMap<*mut core::ffi::c_void, HashMap<String, u8>>> =
57        RefCell::new(HashMap::new());
58}
59
60/// The global-state pointer for `state` — the per-VM key.
61unsafe fn global_key(state: *mut lua_State) -> *mut core::ffi::c_void {
62    unsafe { (*state).global as *mut core::ffi::c_void }
63}
64
65/// The global-state pointer for `state`, exposed for `LuaInner::drop` to capture
66/// the memory-map key BEFORE `lua_close` frees the state.
67pub(crate) unsafe fn memory_key(state: *mut lua_State) -> *mut core::ffi::c_void {
68    unsafe { global_key(state) }
69}
70
71/// Drop this VM's memory-control + category entries so they don't leak one slot
72/// per state created. Called from `LuaInner::drop` **after** `lua_close`: the
73/// `MemoryControl` whose address was handed to the VM as the allocator `ud` must
74/// stay live for the entire close (which frees every object through it), so this
75/// takes `key` — the global-state pointer captured *before* close, since the
76/// state is freed by the time this runs.
77pub(crate) fn clear_memory(key: *mut core::ffi::c_void) {
78    MEMORY_CONTROLS.with(|m| {
79        m.borrow_mut().remove(&key);
80    });
81    MEMORY_CATEGORIES.with(|m| {
82        m.borrow_mut().remove(&key);
83    });
84}
85
86/// The limit-enforcing allocator. Reads the live `totalbytes` from the global
87/// state and refuses any growing allocation that would push it past the cap.
88unsafe extern "C" fn limited_alloc(
89    ud: *mut core::ffi::c_void,
90    ptr: *mut core::ffi::c_void,
91    osize: usize,
92    nsize: usize,
93) -> *mut core::ffi::c_void {
94    let ctrl = unsafe { &*(ud as *const MemoryControl) };
95    if ctrl.limit != 0 && nsize > osize {
96        let g = ctrl.global as *const luaur_vm::records::global_state::global_State;
97        let used = unsafe { (*g).totalbytes };
98        // The would-be new total once this (re)allocation is accounted for.
99        let projected = used.saturating_sub(osize).saturating_add(nsize);
100        if projected > ctrl.limit {
101            return core::ptr::null_mut();
102        }
103    }
104    unsafe { (ctrl.base)(ctrl.base_ud, ptr, osize, nsize) }
105}
106
107impl Lua {
108    /// Set the VM's memory limit in bytes (`0` = unlimited). Mirrors
109    /// `mlua::Lua::set_memory_limit`.
110    ///
111    /// Once installed, an allocation that would exceed the cap fails with
112    /// [`Error::MemoryError`](crate::Error::MemoryError), both during execution
113    /// and during chunk loading.
114    pub fn set_memory_limit(&self, limit: usize) -> Result<usize> {
115        let state = self.state();
116        unsafe {
117            let key = global_key(state);
118            let g = (*state).global;
119            let prev = MEMORY_CONTROLS.with(|m| {
120                let mut map = m.borrow_mut();
121                if let Some(ctrl) = map.get_mut(&key) {
122                    // Already installed: just update the cap.
123                    let prev = ctrl.limit;
124                    ctrl.limit = limit;
125                    Some(prev)
126                } else {
127                    None
128                }
129            });
130            if let Some(prev) = prev {
131                return Ok(prev);
132            }
133            // First install: capture the existing allocator and wrap it.
134            let base = (*g).frealloc.expect("VM allocator must be set");
135            let base_ud = (*g).ud;
136            let ctrl = Box::new(MemoryControl {
137                limit,
138                global: g as *mut core::ffi::c_void,
139                base,
140                base_ud,
141            });
142            let ctrl_ptr = (&*ctrl) as *const MemoryControl as *mut core::ffi::c_void;
143            MEMORY_CONTROLS.with(|m| {
144                m.borrow_mut().insert(key, ctrl);
145            });
146            (*g).ud = ctrl_ptr;
147            (*g).frealloc = Some(limited_alloc);
148            Ok(0)
149        }
150    }
151
152    /// Set the active memory category by name. Mirrors
153    /// `mlua::Lua::set_memory_category`.
154    ///
155    /// Category names must be non-empty and consist only of `[A-Za-z0-9_]`.
156    /// At most 255 distinct user categories can be created (id 0 is reserved
157    /// for the implicit `"main"` category); creating a 256th fails.
158    pub fn set_memory_category(&self, name: &str) -> Result<()> {
159        if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {
160            return Err(Error::runtime(format!(
161                "invalid memory category name: {name:?}"
162            )));
163        }
164        let state = self.state();
165        let key = unsafe { global_key(state) };
166        let id = MEMORY_CATEGORIES.with(|m| -> Result<u8> {
167            let mut map = m.borrow_mut();
168            let cats = map.entry(key).or_insert_with(|| {
169                let mut h = HashMap::new();
170                // id 0 is the implicit "main" category.
171                h.insert("main".to_string(), 0u8);
172                h
173            });
174            if let Some(&id) = cats.get(name) {
175                return Ok(id);
176            }
177            // Assign the next free id. Luau has 256 category slots (ids
178            // 0..=255); id 0 is the implicit "main" and the top slot (255) is
179            // reserved, so at most 255 distinct categories exist (ids 0..=254 —
180            // "main" plus 254 user categories). Creating a 256th fails.
181            let next = cats.len();
182            if next >= 255 {
183                return Err(Error::runtime(
184                    "too many memory categories (limit 255)".to_string(),
185                ));
186            }
187            let id = next as u8;
188            cats.insert(name.to_string(), id);
189            Ok(id)
190        })?;
191        lua_setmemcat(state, id as c_int);
192        Ok(())
193    }
194
195    /// The number of bytes accounted to the named memory category, or `None` if
196    /// the category was never set on this VM. A luaur-rt extension (mlua tracks
197    /// this only via `heap_dump`, which luaur cannot back — see the module).
198    pub fn memory_category_bytes(&self, name: &str) -> Option<usize> {
199        let state = self.state();
200        let key = unsafe { global_key(state) };
201        let id =
202            MEMORY_CATEGORIES.with(|m| m.borrow().get(&key).and_then(|c| c.get(name).copied()))?;
203        unsafe {
204            let g = (*state).global;
205            Some((*g).memcatbytes[id as usize])
206        }
207    }
208}
209
210#[cfg(test)]
211pub(crate) fn memory_controls_len() -> usize {
212    MEMORY_CONTROLS.with(|m| m.borrow().len())
213}