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

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 of 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`](sys::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.
    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) -> i32;

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

    /// Perform an incremental garbage collection.
    ///
    /// An incremental GC is less computationally expensive than a
    /// [full GC](MrbGarbageCollection::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.
    fn incremental_gc(&mut self);

    /// 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](MrbGarbageCollection::incremental_gc). You may wish to
    /// use a full GC if you are memory constrained.
    fn full_gc(&mut self);

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

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

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

    fn live_object_count(&mut self) -> i32 {
        unsafe {
            self.with_ffi_boundary(|mrb| sys::mrb_sys_gc_live_objects(mrb))
                .unwrap_or_default()
        }
    }

    fn mark_value(&mut self, value: &Value) {
        unsafe {
            let _ = self.with_ffi_boundary(|mrb| sys::mrb_sys_safe_gc_mark(mrb, value.inner()));
        }
    }

    fn incremental_gc(&mut self) {
        unsafe {
            let _ = self.with_ffi_boundary(|mrb| sys::mrb_incremental_gc(mrb));
        }
    }

    fn full_gc(&mut self) {
        unsafe {
            let _ = self.with_ffi_boundary(|mrb| sys::mrb_full_gc(mrb));
        }
    }

    fn enable_gc(&mut self) -> State {
        unsafe {
            self.with_ffi_boundary(|mrb| {
                if sys::mrb_sys_gc_enable(mrb) {
                    State::Enabled
                } else {
                    State::Disabled
                }
            })
            .unwrap_or(State::Disabled)
        }
    }

    fn disable_gc(&mut self) -> State {
        unsafe {
            self.with_ffi_boundary(|mrb| {
                if sys::mrb_sys_gc_disable(mrb) {
                    State::Enabled
                } else {
                    State::Disabled
                }
            })
            .unwrap_or(State::Disabled)
        }
    }
}

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

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

    #[test]
    fn arena_restore_on_explicit_restore() {
        let mut interp = interpreter().unwrap();
        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 _ = value.to_s(&mut arena);
        }
        arena.restore();
        interp.full_gc();
        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().unwrap();
        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 _ = value.to_s(&mut arena);
            }
        }
        interp.full_gc();
        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 enable_disable_gc() {
        let mut interp = interpreter().unwrap();
        interp.disable_gc();
        let mut arena = interp.create_arena_savepoint().unwrap();
        let _ = 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();
        assert_eq!(
            arena.live_object_count(),
            live,
            "GC is disabled. No objects should be collected"
        );
        arena.restore();
        interp.enable_gc();
        interp.full_gc();
        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().unwrap();
        let mut arena = interp.create_arena_savepoint().unwrap();
        let baseline_object_count = arena.live_object_count();
        drop(&mut arena.eval(b"").unwrap());
        arena.restore();
        interp.full_gc();
        assert_eq!(interp.live_object_count(), baseline_object_count);
    }

    #[test]
    fn gc_functional_test() {
        let mut interp = interpreter().unwrap();
        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();
        }
        initial_arena.restore();
        interp.full_gc();
        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()
        );
    }
}