luau-vm 0.732.0

Pure-Rust Luau virtual machine, garbage collector, and standard libraries
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
use core::mem::MaybeUninit;
use core::ptr::{self, NonNull};

use crate::Table;
use crate::VmErrorResult;
use crate::gc::{GcBarrier, GcObject, GcRuntime};
use crate::handle::RawHandle;
use crate::handle::sealed::Sealed;
use crate::layout::Align8Byte;
use crate::memory::{LuaPage, MemoryRuntime};
use crate::native::NativeCallResult;
use crate::state::{GlobalState, ThreadState};
use crate::string::TString;
use crate::table::RawLuaTable;
use crate::thread::Thread;
use crate::types::LUA_TUSERDATA;
use crate::value::{RawTValue, TValue};

mod typed;

pub use typed::UserdataTypeRegistration;
pub(crate) use typed::UserdataTypeRegistry;
pub use typed::{
    TypedUserdata, TypedUserdataAccess, TypedUserdataError, UserdataTypeRegistryAccess,
};

#[repr(C)]
pub struct RawUserdata {
    pub tt: u8,
    pub marked: u8,
    pub memcat: u8,
    pub tag: u8,
    pub len: i32,
    pub metatable: *mut RawLuaTable,
    pub data: [Align8Byte; 1],
}

#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(transparent)]
pub struct Userdata {
    raw: NonNull<RawUserdata>,
}

impl Userdata {
    /// Constructs a non-owning handle from a VM userdata record.
    ///
    /// # Safety
    ///
    /// `raw` must address a live `RawUserdata` owned by the VM in which this
    /// handle will be used. The handle does not root the userdata or extend
    /// its lifetime.
    pub const unsafe fn from_raw(raw: NonNull<RawUserdata>) -> Self {
        Self { raw }
    }

    const fn size_userdata(payload_len: usize) -> usize {
        core::mem::offset_of!(RawUserdata, data)
            + if payload_len > 16 {
                (payload_len + 15) & !15
            } else {
                payload_len
            }
    }

    pub fn allocation_size_for_payload_len(payload_len: usize) -> Option<usize> {
        let max_len = i32::MAX as usize - core::mem::size_of::<RawUserdata>();
        (payload_len <= max_len).then(|| Self::size_userdata(payload_len))
    }

    /// Returns this userdata's metatable handle, if present.
    ///
    /// # Safety
    ///
    /// The userdata and its owning VM must be live. The returned handle is
    /// non-owning and is invalidated when the metatable is freed.
    pub unsafe fn metatable(&self) -> Option<Table> {
        unsafe {
            NonNull::new(self.as_ptr().as_ref().unwrap_unchecked().metatable)
                .map(|raw| Table::from_raw(raw))
        }
    }

    /// Replaces this userdata's metatable pointer.
    ///
    /// # Safety
    ///
    /// The userdata must be live, and `metatable`, when present, must belong
    /// to the same VM. The caller must maintain the VM's GC barrier protocol.
    pub unsafe fn set_metatable(&self, metatable: Option<Table>) {
        unsafe {
            self.as_ptr().as_mut().unwrap_unchecked().metatable =
                metatable.map_or(core::ptr::null_mut(), |table| table.as_ptr())
        };
    }

    pub fn total_payload_len(&self) -> usize {
        unsafe { self.as_ptr().as_ref().unwrap_unchecked().len as usize }
    }

    pub const fn data_ptr(&self) -> *const u8 {
        unsafe { (&raw const self.raw.as_ref().data).cast::<u8>() }
    }

    /// Returns the mutable address of this userdata's inline payload.
    ///
    /// # Safety
    ///
    /// The userdata must be live, and the caller must enforce bounds and
    /// aliasing for every access through the returned pointer.
    pub const unsafe fn data_mut_ptr(&self) -> *mut u8 {
        unsafe { (&raw mut (*self.raw.as_ptr()).data).cast::<u8>() }
    }

    unsafe fn inline_destructor_slot(&self, requested_payload_len: usize) -> *mut u8 {
        unsafe { self.data_mut_ptr().add(requested_payload_len).cast::<u8>() }
    }

    /// Stores the inline destructor following the requested payload.
    ///
    /// # Safety
    ///
    /// This must be an inline-destructor userdata whose allocation contains a
    /// destructor-sized trailer immediately after `requested_payload_len`.
    pub unsafe fn set_inline_destructor(
        &self,
        requested_payload_len: usize,
        destructor: LuaInlineDestructor,
    ) {
        debug_assert_eq!(
            unsafe { self.as_ptr().as_ref().unwrap_unchecked().tag as usize },
            USERDATA_TAG_IDTOR
        );

        let inline_destructor_size = core::mem::size_of::<LuaInlineDestructor>();
        debug_assert!(self.total_payload_len() >= inline_destructor_size);
        debug_assert_eq!(
            self.total_payload_len() - inline_destructor_size,
            requested_payload_len
        );

        unsafe {
            ptr::copy_nonoverlapping(
                (&raw const destructor).cast::<u8>(),
                self.inline_destructor_slot(requested_payload_len),
                inline_destructor_size,
            );
        }
    }

    /// Loads the destructor stored after an inline-destructor payload.
    ///
    /// # Safety
    ///
    /// This must be a live inline-destructor userdata whose payload trailer
    /// was initialized with a valid `LuaInlineDestructor`.
    pub unsafe fn inline_destructor(&self) -> LuaInlineDestructor {
        debug_assert_eq!(
            unsafe { self.as_ptr().as_ref().unwrap_unchecked().tag as usize },
            USERDATA_TAG_IDTOR
        );

        let mut destructor = MaybeUninit::<LuaInlineDestructor>::uninit();
        unsafe {
            let inline_destructor_size = core::mem::size_of::<LuaInlineDestructor>();
            debug_assert!(self.total_payload_len() >= inline_destructor_size);
            ptr::copy_nonoverlapping(
                self.inline_destructor_slot(self.total_payload_len() - inline_destructor_size),
                destructor.as_mut_ptr().cast::<u8>(),
                inline_destructor_size,
            );
            destructor.assume_init()
        }
    }

    /// Returns this userdata allocation's full GC size.
    ///
    /// # Safety
    ///
    /// The userdata record must be live and its stored payload length must
    /// describe the allocation that contains it.
    pub unsafe fn allocation_size(&self) -> usize {
        Self::size_userdata(self.total_payload_len())
    }
}

impl crate::handle::sealed::Sealed for Userdata {}

impl RawHandle for Userdata {
    type Raw = RawUserdata;

    fn as_ptr(&self) -> *mut Self::Raw {
        self.raw.as_ptr()
    }
}

impl AsRef<Userdata> for Userdata {
    fn as_ref(&self) -> &Userdata {
        self
    }
}

#[repr(C)]
pub struct LuaUserdataDirectAccessData {
    pub index_tm: RawTValue,
    pub new_index_tm: RawTValue,
    pub name_call_tm: RawTValue,
    pub index: Option<LuaUserdataDirectAccess>,
    pub new_index: Option<LuaUserdataDirectAccess>,
    pub name_call: Option<LuaUserdataDirectNamecall>,
}

impl GlobalState {
    pub fn userdata_direct_field(&self, tag: usize) -> Option<Table> {
        unsafe {
            Some(Table::from_raw(NonNull::new(
                self.as_ptr()
                    .as_ref()
                    .unwrap_unchecked()
                    .userdata_direct_fields[tag],
            )?))
        }
    }

    pub fn set_userdata_direct_field(&self, tag: usize, table: Option<Table>) {
        unsafe {
            self.as_ptr()
                .as_mut()
                .unwrap_unchecked()
                .userdata_direct_fields[tag] =
                table.map_or(core::ptr::null_mut(), |table| table.as_ptr());
        }
    }
}

/// Unstable userdata allocation and destruction capability.
///
/// # Safety
///
/// The thread, userdata, and page handles must be live and belong to the same
/// VM. Tags, payload sizes, destructor storage, and deallocation pages must
/// match the original allocation, with rooting and GC barriers preserved.
#[allow(
    clippy::missing_safety_doc,
    reason = "all methods share the capability-level safety contract"
)]
pub trait UserdataRuntime: Sealed {
    unsafe fn new_userdata_tagged_internal(&self, size: usize, tag: i32) -> VmErrorResult<*mut ()>;

    /// `luaU_newudata`
    unsafe fn new_userdata_internal(&self, size: usize, tag: i32) -> VmErrorResult<Userdata>;

    /// `luaU_freeudata`
    unsafe fn free_userdata(&self, userdata: Userdata, page: LuaPage);
}

/// `LUA_LUTAG_LIMIT`
pub const LIGHT_USERDATA_TAG_LIMIT: usize = 128;

/// `LUA_UTAG_LIMIT`
pub const USERDATA_TAG_LIMIT: usize = 128;

pub(crate) const USERDATA_TAG_IDTOR: usize = USERDATA_TAG_LIMIT;
pub(crate) const USERDATA_TAG_PROXY: usize = USERDATA_TAG_IDTOR + 1;
pub(crate) const USERDATA_INTERNAL_LIMIT: usize = USERDATA_TAG_PROXY + 1;

pub type LuaDestructor = fn(&Thread, *mut ());

pub type LuaUserdataMark = fn(&Thread, *mut ());

pub type LuaInlineDestructor = fn(*mut ());

pub type LuaUserdataDirectAccess = fn(&Thread, *mut (), i32, *mut u16, i32) -> VmErrorResult;

pub type LuaUserdataDirectNamecall = fn(&Thread, *mut (), i32, *mut u16, i32) -> NativeCallResult;

pub type LuaUserdataDirectFieldGet = fn(*mut (), &mut UserdataDirectFieldResult);

impl GlobalState {
    pub fn userdata_metatable(&self, tag: usize) -> Option<Table> {
        unsafe {
            Some(Table::from_raw(NonNull::new(
                self.as_ptr().as_ref().unwrap_unchecked().userdata_mt[tag],
            )?))
        }
    }

    pub fn set_userdata_metatable(&self, tag: usize, table: Option<Table>) {
        unsafe {
            (*self.as_ptr()).userdata_mt[tag] =
                table.map_or(core::ptr::null_mut(), |table| table.as_ptr());
        }
    }

    pub fn userdata_dtor(&self, tag: usize) -> Option<LuaDestructor> {
        unsafe { (*self.as_ptr()).userdata_gc[tag] }
    }

    pub fn set_userdata_dtor(&self, tag: usize, destructor: Option<LuaDestructor>) {
        unsafe {
            (*self.as_ptr()).userdata_gc[tag] = destructor;
        }
    }

    pub fn userdata_mark(&self, tag: usize) -> Option<LuaUserdataMark> {
        unsafe { (*self.as_ptr()).userdata_mark[tag] }
    }

    pub fn set_userdata_mark(&self, tag: usize, mark: Option<LuaUserdataMark>) {
        unsafe {
            (*self.as_ptr()).userdata_mark[tag] = mark;
        }
    }

    pub fn light_userdata_name(&self, tag: usize) -> Option<TString> {
        unsafe {
            NonNull::new((*self.as_ptr()).light_userdata_name[tag])
                .map(|raw| TString::from_raw(raw))
        }
    }

    pub fn set_light_userdata_name(&self, tag: usize, name: Option<TString>) {
        unsafe {
            (*self.as_ptr()).light_userdata_name[tag] =
                name.map_or(core::ptr::null_mut(), |name| name.as_ptr());
        }
    }
}

#[repr(transparent)]
pub struct UserdataDirectFieldResult(pub(crate) TValue);

impl UserdataRuntime for Thread {
    unsafe fn new_userdata_tagged_internal(&self, size: usize, tag: i32) -> VmErrorResult<*mut ()> {
        assert!((tag as u32) < USERDATA_INTERNAL_LIMIT as u32);
        unsafe {
            self.check_gc()?;
            self.thread_barrier();
            self.ensure_stack(self, 1)?;

            let userdata = self.new_userdata_internal(size, tag)?;
            let data = userdata.data_mut_ptr();
            let top = self.stack_top();
            top.value_unchecked().set_userdata_value(userdata);
            debug_assert!(top < self.current_call_info().top());
            self.set_stack_top(top.add(1));

            Ok(data.cast())
        }
    }

    /// `luaU_newudata`
    unsafe fn new_userdata_internal(
        &self,
        payload_len: usize,
        tag: i32,
    ) -> VmErrorResult<Userdata> {
        let Some(allocation_size) = Userdata::allocation_size_for_payload_len(payload_len) else {
            return unsafe { self.too_big() };
        };

        unsafe {
            let userdata = self.new_gco::<Userdata>(
                allocation_size,
                self.as_ptr().as_ref().unwrap_unchecked().active_memcat,
            )?;
            GcObject::from(userdata).init_header(self, LUA_TUSERDATA as u8);
            userdata.as_ptr().as_mut().unwrap_unchecked().len = payload_len as i32;
            userdata.set_metatable(None);
            assert!((tag as u32) < USERDATA_INTERNAL_LIMIT as u32);
            userdata.as_ptr().as_mut().unwrap_unchecked().tag = tag as u8;

            Ok(userdata)
        }
    }

    /// `luaU_freeudata`
    unsafe fn free_userdata(&self, userdata: Userdata, page: LuaPage) {
        let userdata_ref = unsafe { userdata.as_ptr().as_ref().unwrap_unchecked() };
        let tag = userdata_ref.tag;
        let memcat = userdata_ref.memcat;
        let data = unsafe { userdata.data_mut_ptr() };

        unsafe {
            if tag < USERDATA_TAG_LIMIT as u8 {
                if let Some(dtor) = self.global().userdata_dtor(tag as usize) {
                    dtor(self, data.cast());
                }
            } else if tag == USERDATA_TAG_IDTOR as u8 {
                let dtor = userdata.inline_destructor();
                dtor(data.cast());
            }

            self.free_gco(userdata.into(), userdata.allocation_size(), memcat, page);
        }
    }
}

impl UserdataDirectFieldResult {
    /// `lua_userdatadirectfield_setnumber`
    pub fn set_number(&mut self, value: f64) {
        self.0.set_number(value);
    }

    /// `lua_userdatadirectfield_setvector`
    pub fn set_vector(&mut self, value: [f32; crate::types::LUA_VECTOR_SIZE]) {
        self.0.set_vector(value);
    }

    /// `lua_userdatadirectfield_setboolean`
    pub fn set_boolean(&mut self, value: i32) {
        self.0.set_boolean(value);
    }

    /// `lua_userdatadirectfield_setinteger64`
    pub fn set_integer64(&mut self, value: i64) {
        self.0.set_integer(value);
    }

    /// `lua_userdatadirectfield_setnil`
    pub fn set_nil(&mut self) {
        self.0.set_nil();
    }
}