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
use crate::sys;
use crate::value::Value;
use crate::{Artichoke, Error};

pub mod arena;

use arena::{ArenaIndex, ArenaSavepointError};

/// Garbage collection primitives for an mruby interpreter.
pub trait MrbGarbageCollection {
    /// Create a savepoint in the GC arena.
    ///
    /// Savepoints allow mruby to deallocate all the objects created via the
    /// C API.
    ///
    /// Normally objects created via the C API are marked as permanently alive
    /// ("white" GC color) with a call to [`mrb_gc_protect`].
    ///
    /// The returned [`ArenaIndex`] implements [`Drop`], so it is sufficient to
    /// let it go out of scope to ensure objects are eventually collected.
    ///
    /// [`mrb_gc_protect`]: sys::mrb_gc_protect
    fn create_arena_savepoint(&mut self) -> Result<ArenaIndex<'_>, ArenaSavepointError>;

    /// Retrieve the number of live objects on the interpreter heap.
    ///
    /// A live object is reachable via top self, the stack, or the arena.
    fn live_object_count(&mut self) -> usize;

    /// Mark a [`Value`] as reachable in the mruby garbage collector.
    fn mark_value(&mut self, value: &Value) -> Result<(), Error>;

    /// Perform an incremental garbage collection.
    ///
    /// An incremental GC is less computationally expensive than a [full GC],
    /// but does not guarantee that all dead objects will be reaped. You may
    /// wish to use an incremental GC if you are operating with an interpreter
    /// in a loop.
    ///
    /// [full GC]: MrbGarbageCollection::full_gc
    fn incremental_gc(&mut self) -> Result<(), Error>;

    /// Perform a full garbage collection.
    ///
    /// A full GC guarantees that all dead objects will be reaped, so it is more
    /// expensive than an [incremental GC]. You may wish to use a full GC if you
    /// are memory constrained.
    ///
    /// [incremental GC]: MrbGarbageCollection::incremental_gc
    fn full_gc(&mut self) -> Result<(), Error>;

    /// Enable garbage collection.
    ///
    /// Returns the prior GC enabled state.
    fn enable_gc(&mut self) -> Result<State, Error>;

    /// Disable garbage collection.
    ///
    /// Returns the prior GC enabled state.
    fn disable_gc(&mut self) -> Result<State, Error>;
}

impl MrbGarbageCollection for Artichoke {
    fn create_arena_savepoint(&mut self) -> Result<ArenaIndex<'_>, ArenaSavepointError> {
        ArenaIndex::new(self)
    }

    fn live_object_count(&mut self) -> usize {
        let live_objects = unsafe { self.with_ffi_boundary(|mrb| sys::mrb_sys_gc_live_objects(mrb)) };
        live_objects.unwrap_or(0)
    }

    fn mark_value(&mut self, value: &Value) -> Result<(), Error> {
        unsafe {
            self.with_ffi_boundary(|mrb| sys::mrb_sys_safe_gc_mark(mrb, value.inner()))?;
        }
        Ok(())
    }

    fn incremental_gc(&mut self) -> Result<(), Error> {
        unsafe {
            self.with_ffi_boundary(|mrb| sys::mrb_incremental_gc(mrb))?;
        }
        Ok(())
    }

    fn full_gc(&mut self) -> Result<(), Error> {
        unsafe {
            self.with_ffi_boundary(|mrb| sys::mrb_full_gc(mrb))?;
        }
        Ok(())
    }

    fn enable_gc(&mut self) -> Result<State, Error> {
        unsafe {
            let state = self.with_ffi_boundary(|mrb| sys::mrb_sys_gc_enable(mrb).into())?;
            Ok(state)
        }
    }

    fn disable_gc(&mut self) -> Result<State, Error> {
        unsafe {
            let state = self.with_ffi_boundary(|mrb| sys::mrb_sys_gc_disable(mrb).into())?;
            Ok(state)
        }
    }
}

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum State {
    Disabled,
    Enabled,
}

impl From<bool> for State {
    fn from(state: bool) -> Self {
        if state {
            Self::Enabled
        } else {
            Self::Disabled
        }
    }
}

#[cfg(test)]
mod tests {
    use super::State;
    use crate::test::prelude::*;

    #[test]
    fn arena_restore_on_explicit_restore() {
        let mut interp = interpreter();
        let baseline_object_count = interp.live_object_count();
        let mut arena = interp.create_arena_savepoint().unwrap();
        for _ in 0..2000 {
            let value = arena.eval(b"'a'").unwrap();
            let _display = value.to_s(&mut arena);
        }
        arena.restore();
        interp.full_gc().unwrap();
        assert_eq!(
            interp.live_object_count(),
            // plus 1 because stack keep is enabled in eval which marks the last
            // returned value as live.
            baseline_object_count + 1,
            "Arena restore + full GC should free unreachable objects",
        );
    }

    #[test]
    fn arena_restore_on_drop() {
        let mut interp = interpreter();
        let baseline_object_count = interp.live_object_count();
        {
            let mut arena = interp.create_arena_savepoint().unwrap();
            for _ in 0..2000 {
                let value = arena.eval(b"'a'").unwrap();
                let _display = value.to_s(&mut arena);
            }
        }
        interp.full_gc().unwrap();
        assert_eq!(
            interp.live_object_count(),
            // plus 1 because stack keep is enabled in eval which marks the last
            // returned value as live.
            baseline_object_count + 1,
            "Arena restore + full GC should free unreachable objects",
        );
    }

    #[test]
    fn gc_state() {
        let mut interp = interpreter();
        assert_eq!(interp.enable_gc().unwrap(), State::Enabled);
        assert_eq!(interp.enable_gc().unwrap(), State::Enabled);

        assert_eq!(interp.disable_gc().unwrap(), State::Enabled);
        assert_eq!(interp.disable_gc().unwrap(), State::Disabled);
        assert_eq!(interp.disable_gc().unwrap(), State::Disabled);

        assert_eq!(interp.enable_gc().unwrap(), State::Disabled);
        assert_eq!(interp.enable_gc().unwrap(), State::Enabled);
    }

    #[test]
    fn enable_disable_gc() {
        let mut interp = interpreter();
        interp.disable_gc().unwrap();
        let mut arena = interp.create_arena_savepoint().unwrap();
        arena
            .interp()
            .eval(
                br#"
                # this value will be garbage collected because it is eventually
                # shadowed and becomes unreachable
                a = []
                # this value will not be garbage collected because it is a local
                # variable in top self
                a = []
                # this value will not be garbage collected because it is a local
                # variable in top self
                b = []
                # this value will not be garbage collected because the last value
                # returned by eval is retained with "stack keep"
                []
                "#,
            )
            .unwrap();
        let live = arena.live_object_count();
        arena.full_gc().unwrap();
        assert_eq!(
            arena.live_object_count(),
            live,
            "GC is disabled. No objects should be collected"
        );
        arena.restore();
        interp.enable_gc().unwrap();
        interp.full_gc().unwrap();
        assert_eq!(
            interp.live_object_count(),
            live - 2,
            "Arrays should be collected after enabling GC and running a full GC"
        );
    }

    #[test]
    fn gc_after_empty_eval() {
        let mut interp = interpreter();
        let mut arena = interp.create_arena_savepoint().unwrap();
        let baseline_object_count = arena.live_object_count();
        arena.eval(b"").unwrap();
        arena.restore();
        interp.full_gc().unwrap();
        assert_eq!(interp.live_object_count(), baseline_object_count);
    }

    #[test]
    fn gc_functional_test() {
        let mut interp = interpreter();
        let baseline_object_count = interp.live_object_count();
        let mut initial_arena = interp.create_arena_savepoint().unwrap();
        for _ in 0..2000 {
            let mut arena = initial_arena.create_arena_savepoint().unwrap();
            let result = arena.eval(b"'gc test'");
            let value = result.unwrap();
            assert!(!value.is_dead(&mut arena));
            arena.restore();
            initial_arena.incremental_gc().unwrap();
        }
        initial_arena.restore();
        interp.full_gc().unwrap();
        assert_eq!(
            interp.live_object_count(),
            // plus 1 because stack keep is enabled in eval which marks the
            // last returned value as live.
            baseline_object_count + 1,
            "Started with {} live objects, ended with {}. Potential memory leak!",
            baseline_object_count,
            interp.live_object_count()
        );
    }
}