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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
use crate::VmErrorResult;
use crate::gc::GcObject;
use crate::gc::GcRuntime;
use crate::gc::debug::{DumpContext, HeapEnumContext};
use crate::gc::{GCS_ATOMIC, GCS_PAUSE, GCS_PROPAGATE, GCS_PROPAGATE_AGAIN, GCS_SWEEP};
use crate::gc::{GcCategoryNamer, GcHeapEdge, GcHeapNode};
use crate::handle::RawHandle;
use crate::memory::MemoryRuntime;
use crate::state::GlobalState;
use crate::state::{GcInterrupt, GcPhase};
use crate::thread::Thread;
use crate::types;
use crate::value::TValue;
use luau_common::{BString, flags};

const GC_SWEEP_PAGE_STEP_COST: usize = 16;

impl GlobalState {
    /// `getheaptriggererroroffset`
    unsafe fn heap_trigger_error_offset(&self) -> i64 {
        let global_mut = unsafe { self.as_ptr().as_mut().unwrap_unchecked() };
        let stats = &mut global_mut.gc_stats;
        let error_kb = (stats
            .atomic_start_total_size_bytes
            .wrapping_sub(stats.heap_goal_size_bytes)
            / 1024) as i32;

        let slot =
            &mut stats.trigger_terms[stats.trigger_term_pos as usize % stats.trigger_terms.len()];
        let previous = *slot;
        *slot = error_kb;
        stats.trigger_integral += error_kb - previous;
        stats.trigger_term_pos += 1;

        let ku = 0.9f64;
        let tu = 2.5f64;
        let kp = 0.45 * ku;
        let ti = 0.8 * tu;
        let ki = 0.54 * ku / ti;

        let proportional = kp * error_kb as f64;
        let integral = ki * stats.trigger_integral as f64;
        ((proportional + integral) * 1024.0) as i64
    }

    /// `getheaptrigger`
    unsafe fn heap_trigger(&self, heap_goal: usize) -> usize {
        unsafe {
            let stats = &self.as_ptr().as_ref().unwrap_unchecked().gc_stats;
            let allocation_duration = stats.atomic_start_timestamp - stats.end_timestamp;

            if allocation_duration < 1e-3 {
                return heap_goal;
            }

            let allocation_rate = stats
                .atomic_start_total_size_bytes
                .wrapping_sub(stats.end_total_size_bytes) as f64
                / allocation_duration;
            let mark_duration = stats.atomic_start_timestamp - stats.start_timestamp;

            let expected_growth = (mark_duration * allocation_rate) as i64;
            let offset = self.heap_trigger_error_offset();
            let heap_trigger = heap_goal as i64 - (expected_growth + offset);
            let total_bytes = self.as_ptr().as_ref().unwrap_unchecked().total_bytes as i64;

            if heap_trigger < total_bytes {
                total_bytes as usize
            } else if heap_trigger > heap_goal as i64 {
                heap_goal
            } else {
                heap_trigger as usize
            }
        }
    }
}

impl Thread {
    /// `gcinterrupt`
    unsafe fn gc_interrupt(&self, event: GcInterrupt) -> VmErrorResult {
        let global = unsafe { self.global() };
        let Some(interrupt) = global.take_gc_interrupt_callback() else {
            return Ok(());
        };

        interrupt(self, event)
    }

    /// `gcstep`
    unsafe fn gc_step(&self, limit: usize) -> usize {
        unsafe {
            let global = self.global();
            let mut cost = 0usize;

            match global.gc_state() {
                GCS_PAUSE => {
                    self.mark_root();
                    debug_assert_eq!(global.gc_state(), GCS_PROPAGATE);
                }
                GCS_PROPAGATE => {
                    while global.gray().is_some() && cost < limit {
                        cost += global.propagate_mark();
                    }

                    if global.gray().is_none() {
                        global.set_gray(global.gray_again());
                        global.set_gray_again(None);
                        global.set_gc_state(GCS_PROPAGATE_AGAIN);
                    }
                }
                GCS_PROPAGATE_AGAIN => {
                    while global.gray().is_some() && cost < limit {
                        cost += global.propagate_mark();
                    }

                    if global.gray().is_none() {
                        global.set_gc_state(GCS_ATOMIC);
                    }
                }
                GCS_ATOMIC => {
                    let global_mut = global.as_ptr().as_mut().unwrap_unchecked();
                    global_mut.gc_stats.atomic_start_timestamp = crate::perf::clock();
                    global_mut.gc_stats.atomic_start_total_size_bytes = global_mut.total_bytes;

                    cost = self.atomic();
                    debug_assert_eq!(global.gc_state(), GCS_SWEEP);
                }
                GCS_SWEEP => {
                    while let Some(page) = global.sweep_gco_page()
                        && cost < limit
                    {
                        let next = page.next_page();
                        let steps = page.sweep_gco(self);

                        global.set_sweep_gco_page(next);
                        cost += steps as usize * GC_SWEEP_PAGE_STEP_COST;
                    }

                    if global.sweep_gco_page().is_none() {
                        let main_thread = global.main_thread();
                        debug_assert!(!global.is_dead((&main_thread).into()));
                        global.make_white((&main_thread).into());
                        self.shrink_buffers();
                        global.set_gc_state(GCS_PAUSE);
                    }
                }
                other => unreachable!("unexpected gc state {}", other),
            }

            cost
        }
    }
}

impl GcRuntime for Thread {
    /// `luaC_freeall`
    unsafe fn free_all(&self) {
        unsafe {
            let global = self.global();
            debug_assert!(*self == global.main_thread());
            self.visit_gco(self.as_ptr().cast(), super::sweep::delete_gco);

            for index in 0..global
                .as_ptr()
                .as_ref()
                .unwrap_unchecked()
                .string_table
                .size
                .max(0) as usize
            {
                debug_assert!(
                    global
                        .as_ptr()
                        .as_ref()
                        .unwrap_unchecked()
                        .string_table
                        .hash
                        .add(index)
                        .read()
                        .is_null()
                );
            }

            debug_assert_eq!(
                global
                    .as_ptr()
                    .as_ref()
                    .unwrap_unchecked()
                    .string_table
                    .n_use,
                0
            );
        }
    }

    /// `luaC_needsGC`
    unsafe fn needs_gc(&self) -> bool {
        let global = unsafe { self.global() };
        unsafe {
            global.as_ptr().as_ref().unwrap_unchecked().total_bytes
                >= global.as_ptr().as_ref().unwrap_unchecked().gc_threshold
        }
    }

    /// `luaC_checkGC`
    unsafe fn check_gc(&self) -> VmErrorResult {
        if unsafe { self.needs_gc() } {
            unsafe { self.step(true)? };
        }
        Ok(())
    }

    /// `luaC_step`
    unsafe fn step(&self, assist: bool) -> VmErrorResult<usize> {
        unsafe {
            let global = self.global();
            let step_size = global.as_ptr().as_ref().unwrap_unchecked().gc_step_size as usize;
            let step_mul = global.as_ptr().as_ref().unwrap_unchecked().gc_step_mul as usize;
            let mut limit = step_size * step_mul / 100;

            debug_assert!(
                global.as_ptr().as_ref().unwrap_unchecked().total_bytes
                    >= global.as_ptr().as_ref().unwrap_unchecked().gc_threshold
            );
            let debt = global.as_ptr().as_ref().unwrap_unchecked().total_bytes
                - global.as_ptr().as_ref().unwrap_unchecked().gc_threshold;

            if flags::LuauBackedgeHeapCheck.get() && assist {
                limit = limit.max(debt * step_mul / 100);
            }

            self.gc_interrupt(GcInterrupt::BeforeStep)?;

            let gc_state = global.gc_state();
            if gc_state == GCS_PAUSE {
                global
                    .as_ptr()
                    .as_mut()
                    .unwrap_unchecked()
                    .gc_stats
                    .start_timestamp = crate::perf::clock();
            }

            let last_gc_state = gc_state;
            let work = self.gc_step(limit);
            let actual_step_size =
                work * 100 / global.as_ptr().as_ref().unwrap_unchecked().gc_step_mul as usize;

            if global.gc_state() == GCS_PAUSE {
                let total_bytes = global.as_ptr().as_ref().unwrap_unchecked().total_bytes;
                let gc_goal = global.as_ptr().as_ref().unwrap_unchecked().gc_goal as usize;
                let heap_goal = (total_bytes / 100) * gc_goal;
                let heap_trigger = global.heap_trigger(heap_goal);
                let end_timestamp = crate::perf::clock();

                let global_mut = global.as_ptr().as_mut().unwrap_unchecked();
                global_mut.gc_threshold = heap_trigger;
                global_mut.gc_stats.heap_goal_size_bytes = heap_goal;
                global_mut.gc_stats.end_timestamp = end_timestamp;
                global_mut.gc_stats.end_total_size_bytes = global_mut.total_bytes;
            } else {
                let global_mut = global.as_ptr().as_mut().unwrap_unchecked();
                global_mut.gc_threshold = global_mut.total_bytes + actual_step_size;
                if global_mut.gc_threshold >= debt {
                    global_mut.gc_threshold -= debt;
                }
            }

            self.gc_interrupt(GcInterrupt::AfterStep {
                previous_phase: GcPhase::from_state(last_gc_state),
            })?;
            Ok(actual_step_size)
        }
    }

    /// `luaC_fullgc`
    unsafe fn full_gc(&self) {
        unsafe {
            let global = self.global();

            if global.keep_invariant() {
                global.set_sweep_gco_page(global.all_gco_pages());
                global.set_gray(None);
                global.set_gray_again(None);
                global.set_weak(None);
                global.set_gc_state(GCS_SWEEP);
            }

            debug_assert!(matches!(global.gc_state(), GCS_PAUSE | GCS_SWEEP));
            while global.gc_state() != GCS_PAUSE {
                debug_assert_eq!(global.gc_state(), GCS_SWEEP);
                self.gc_step(usize::MAX);
            }

            let sentinel = global.uv_head();
            let mut upvalue = sentinel.open_data().next();

            while upvalue != sentinel {
                let current_upvalue = upvalue;
                let next = current_upvalue.open_data().next();

                current_upvalue
                    .as_ptr()
                    .as_mut()
                    .unwrap_unchecked()
                    .marked_open = 0;
                upvalue = next;
            }

            self.mark_root();
            while global.gc_state() != GCS_PAUSE {
                self.gc_step(usize::MAX);
            }

            self.shrink_buffers_full();

            let total_bytes = global.as_ptr().as_ref().unwrap_unchecked().total_bytes;
            let gc_goal = global.as_ptr().as_ref().unwrap_unchecked().gc_goal as usize;
            let gc_step_mul = global.as_ptr().as_ref().unwrap_unchecked().gc_step_mul as usize;
            let heap_goal_size_bytes = (total_bytes / 100) * gc_goal;
            let mut gc_threshold = total_bytes * (gc_goal * gc_step_mul / 100 - 100) / gc_step_mul;

            if gc_threshold < total_bytes {
                gc_threshold = total_bytes;
            }

            let global_mut = global.as_ptr().as_mut().unwrap_unchecked();
            global_mut.gc_threshold = gc_threshold;
            global_mut.gc_stats.heap_goal_size_bytes = heap_goal_size_bytes;
        }
    }

    /// `luaC_validate`
    unsafe fn validate(&self) {
        unsafe {
            let global = self.global();

            debug_assert!(!global.is_dead(self.into()));
            global.validate_liveness(TValue::from_ref(
                &global.as_ptr().as_ref().unwrap_unchecked().registry,
            ));

            for tag in 0..types::LUA_T_COUNT {
                if let Some(metatable) = global.metatable(tag) {
                    debug_assert!(!global.is_dead(metatable.into()));
                }
            }

            for metatable in (&*global.userdata_type_registry_ptr()).recognized_metatables() {
                debug_assert!(!global.is_dead(metatable.into()));
            }

            for tag in 0..crate::userdata::USERDATA_TAG_LIMIT {
                if let Some(metatable) = global.userdata_metatable(tag) {
                    debug_assert!(!global.is_dead(metatable.into()));
                }
            }

            for tag in 0..crate::userdata::USERDATA_INTERNAL_LIMIT {
                let direct_access =
                    &global.as_ptr().as_ref().unwrap_unchecked().userdata_direct[tag];
                global.validate_liveness(TValue::from_ref(&direct_access.index_tm));
                global.validate_liveness(TValue::from_ref(&direct_access.new_index_tm));
                global.validate_liveness(TValue::from_ref(&direct_access.name_call_tm));

                if let Some(fields) = global.userdata_direct_field(tag) {
                    debug_assert!(!global.is_dead(fields.into()));
                }
            }

            global.validate_gray_list(global.weak());
            global.validate_gray_list(global.gray());
            global.validate_gray_list(global.gray_again());

            global.validate_object(GcObject::from(self));
            self.visit_gco(self.as_ptr().cast(), super::debug::validate_gco_visitor);

            let sentinel = global.uv_head();
            let mut upvalue = sentinel.open_data().next();

            while upvalue != sentinel {
                let current_upvalue = upvalue;
                let open = current_upvalue.open_data();
                let object: GcObject = current_upvalue.into();
                debug_assert_eq!(
                    current_upvalue.as_ptr().as_ref().unwrap_unchecked().tt,
                    types::LUA_TUPVALUE as u8
                );
                debug_assert!(current_upvalue.is_open());
                debug_assert!(open.next().open_data().prev() == current_upvalue);
                debug_assert!(open.prev().open_data().next() == current_upvalue);
                debug_assert!(!object.is_black());

                upvalue = open.next();
            }
        }
    }

    /// `luaC_dump`
    unsafe fn dump(&self, file: *mut (), category_name: Option<&mut dyn GcCategoryNamer>) {
        unsafe {
            let global = self.global();
            let output = &mut *file.cast::<BString>();
            let mut category_name = category_name;

            output.clear();
            output.extend_from_slice(b"{\"objects\":{\n");

            super::debug::dump_gco(output, self, global.main_thread().into());

            let mut context = DumpContext {
                thread: self,
                output,
            };
            self.visit_gco((&raw mut context).cast(), super::debug::dump_gco_visitor);

            output.extend_from_slice(b"\"0\":{\"type\":\"userdata\",\"cat\":0,\"size\":0}\n");
            output.extend_from_slice(b"},\"roots\":{\n");
            output.extend_from_slice(b"\"mainthread\":");
            super::debug::append_ref(output, global.main_thread().into());
            output.extend_from_slice(b",\"registry\":");
            super::debug::append_ref(
                output,
                TValue::from_ref(&global.as_ptr().as_ref().unwrap_unchecked().registry).gc_value(),
            );
            output.extend_from_slice(b"},\"stats\":{\n");
            output.extend_from_slice(b"\"size\":");
            super::debug::append_decimal(
                output,
                global.as_ptr().as_ref().unwrap_unchecked().total_bytes,
            );
            output.extend_from_slice(b",\n\"categories\":{\n");

            for (index, bytes) in global
                .as_ptr()
                .as_ref()
                .unwrap_unchecked()
                .memcat_bytes
                .iter()
                .copied()
                .enumerate()
            {
                if bytes == 0 {
                    continue;
                }

                output.push(b'"');
                super::debug::append_decimal(output, index);
                output.extend_from_slice(b"\":{");

                if let Some(category_name) = category_name.as_deref_mut() {
                    output.extend_from_slice(b"\"name\":\"");
                    category_name.category_name(self, index as u8, output);
                    output.extend_from_slice(b"\", ");
                }

                output.extend_from_slice(b"\"size\":");
                super::debug::append_decimal(output, bytes);
                output.extend_from_slice(b"},\n");
            }

            output.extend_from_slice(b"\"none\":{}\n}\n}}\n");
        }
    }

    /// `luaC_enumheap`
    unsafe fn enum_heap(&self, context: *mut (), node: GcHeapNode, edge: GcHeapEdge) {
        unsafe {
            let global = self.global();
            let mut heap = HeapEnumContext {
                thread: self,
                context,
                node,
                edge,
            };

            heap.enum_object(global.main_thread().into());
            self.visit_gco((&raw mut heap).cast(), super::debug::enum_heap_gco_visitor);
        }
    }

    /// `luaC_allocationrate`
    unsafe fn allocation_rate(&self) -> i64 {
        unsafe {
            let global = self.global();
            let duration_threshold = 1e-3;

            let (bytes, duration) = match global.gc_state() {
                x if x <= GCS_ATOMIC => (
                    global
                        .as_ptr()
                        .as_ref()
                        .unwrap_unchecked()
                        .total_bytes
                        .wrapping_sub(
                            global
                                .as_ptr()
                                .as_ref()
                                .unwrap_unchecked()
                                .gc_stats
                                .end_total_size_bytes,
                        ),
                    crate::perf::clock()
                        - global
                            .as_ptr()
                            .as_ref()
                            .unwrap_unchecked()
                            .gc_stats
                            .end_timestamp,
                ),
                _ => (
                    global
                        .as_ptr()
                        .as_ref()
                        .unwrap_unchecked()
                        .gc_stats
                        .atomic_start_total_size_bytes
                        .wrapping_sub(
                            global
                                .as_ptr()
                                .as_ref()
                                .unwrap_unchecked()
                                .gc_stats
                                .end_total_size_bytes,
                        ),
                    global
                        .as_ptr()
                        .as_ref()
                        .unwrap_unchecked()
                        .gc_stats
                        .atomic_start_timestamp
                        - global
                            .as_ptr()
                            .as_ref()
                            .unwrap_unchecked()
                            .gc_stats
                            .end_timestamp,
                ),
            };

            if duration < duration_threshold {
                -1
            } else {
                (bytes as f64 / duration) as i64
            }
        }
    }
}