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
//! Manage the garbage collector.

#[julia_version(since = "1.10")]
use jl_sys::jl_gc_set_max_memory;
pub use jl_sys::{jl_gc_collect, jl_gc_collection_t_JL_GC_FULL};
use jl_sys::{
    jl_gc_collection_t, jl_gc_enable, jl_gc_is_enabled, jl_gc_mark_queue_obj,
    jl_gc_mark_queue_objarray, jl_gc_safepoint, jl_gc_wb, jlrs_gc_safe_enter, jlrs_gc_safe_leave,
    jlrs_gc_unsafe_enter, jlrs_gc_unsafe_leave,
};
use jlrs_macros::julia_version;

use super::{
    get_tls,
    target::{unrooted::Unrooted, Target},
    PTls,
};
#[cfg(feature = "sync-rt")]
use crate::runtime::sync_rt::Julia;
#[julia_version(since = "1.7")]
use crate::{call::Call, data::managed::module::Module};
use crate::{
    data::managed::{
        private::ManagedPriv,
        value::{Value, ValueRef},
    },
    private::Private,
};

/// The different collection modes.
#[derive(Debug, Copy, Clone)]
pub enum GcCollection {
    Auto = 0,
    Full = 1,
    Incremental = 2,
}

/// Manage the GC.
///
/// This trait provides several methods that can be used to enable or disable the GC, force a
/// collection, insert a safepoint, and to enable and disable GC logging. It's implemented for
/// [`Julia`] and all [`Target`]s.
pub trait Gc: private::GcPriv {
    /// Enable or disable the GC.
    #[inline]
    fn enable_gc(&self, on: bool) -> bool {
        // Safety: this function is called with a valid argument and can only be called while
        // Julia is active.
        unsafe { jl_gc_enable(on as i32) != 0 }
    }

    #[julia_version(since = "1.7")]
    /// Enable or disable GC logging.
    ///
    /// This method is not available when the `lts` feature is enabled.
    fn enable_gc_logging(&self, on: bool) {
        // Safety: Julia is active, this method is called from a thread known to Julia, and no
        // Julia data is returned by this method.

        use super::target::unrooted::Unrooted;

        let global = unsafe { Unrooted::new() };

        // Safety: everything is globally rooted.
        let func = unsafe {
            Module::base(&global)
                .submodule(&global, "GC")
                .expect("No GC module in Base")
                .as_managed()
                .function(&global, "enable_logging")
                .expect("No enable_logging function in GC")
                .as_managed()
        };

        let arg = if on {
            Value::true_v(&global)
        } else {
            Value::false_v(&global)
        };

        // Safety: GC.enable_logging is safe to call.
        unsafe { func.call1(&global, arg) }.expect("GC.enable_logging threw an exception");
    }

    /// Returns `true` if the GC is enabled.
    #[inline]
    fn gc_is_enabled(&self) -> bool {
        // Safety: this function can only be called while Julia is active from a thread known to
        // Julia.
        unsafe { jl_gc_is_enabled() != 0 }
    }

    /// Force a collection.
    #[inline]
    fn gc_collect(&self, mode: GcCollection) {
        // Safety: this function can only be called while Julia is active from a thread known to
        // Julia.
        unsafe { jl_gc_collect(mode as jl_gc_collection_t) }
    }

    /// Insert a safepoint, a point where the garbage collector may run.
    #[inline]
    fn gc_safepoint(&self) {
        // Safety: this function can only be called while Julia is active from a thread known to
        // Julia.
        unsafe {
            jl_gc_safepoint();
        }
    }

    /// Put the current task in a GC-safe state.
    ///
    /// In a GC-safe state a task must not be calling into Julia, it indicates that the GC is
    /// allowed to collect without waiting for the task to reach an explicit safepoint.
    ///
    /// Safety:
    ///
    /// While in a GC-safe state, you must not call into Julia in any way that. It should only be used
    /// in combination with blocking operations to allow the GC to collect while waiting for the
    /// blocking operation to complete.
    ///
    /// You must leave the GC-safe state by calling [`Gc::gc_safe_leave`] with the state returned
    /// by this function.
    #[inline]
    unsafe fn gc_safe_enter() -> i8 {
        let ptls = get_tls();
        jlrs_gc_safe_enter(ptls)
    }

    /// Leave a GC-safe region and return to the previous GC-state.
    ///
    /// Safety:
    ///
    /// Must be called with the state returned by a matching call to [`Gc::gc_safe_enter`].
    #[inline]
    unsafe fn gc_safe_leave(state: i8) {
        let ptls = get_tls();
        jlrs_gc_safe_leave(ptls, state)
    }

    /// Put the current task in a GC-unsafe state.
    ///
    /// In a GC-unsafe state a task must reach an explicit safepoint before the GC can collect.
    ///
    /// Safety:
    ///
    /// This function must only be called while the task is in a GC-safe state. After calling this
    /// function the task may call into Julia again.
    ///
    /// You must leave the GC-safe state by calling [`Gc::gc_unsafe_leave`] with the state
    /// returned by this function.
    #[inline]
    unsafe fn gc_unsafe_enter() -> i8 {
        let ptls = get_tls();
        jlrs_gc_unsafe_enter(ptls)
    }

    /// Leave a GC-unsafe region and return to the previous GC-state.
    ///
    /// Safety:
    ///
    /// Must be called with the state returned by a matching call to [`Gc::gc_unsafe_enter`].
    #[inline]
    unsafe fn gc_unsafe_leave(state: i8) {
        let ptls = get_tls();
        jlrs_gc_unsafe_leave(ptls, state)
    }

    #[julia_version(since = "1.10")]
    /// Set GC memory trigger in bytes for greedy memory collecting
    #[inline]
    fn gc_set_max_memory(max_mem: u64) {
        unsafe { jl_gc_set_max_memory(max_mem) }
    }
}

/// Mark `obj`, returns `true` if `obj` points to young data.
///
/// This method can be used to implement custom mark functions. If a foreign type contains
/// references to Julia data, a custom `mark` function must be implemented that calls this
/// function on each of those references.
///
/// Safety
///
/// This method must only be called from `ForeignType::mark`.
#[inline]
pub unsafe fn mark_queue_obj(ptls: PTls, obj: ValueRef) -> bool {
    jl_gc_mark_queue_obj(ptls, obj.ptr().as_ptr()) != 0
}

/// Mark `objs`.
///
/// This method can be used to implement custom mark functions. If a foreign type contains
/// references to Julia data, a custom `mark` function must be implemented. This method can be
/// used on arrays of references to Julia data instead of calling [`mark_queue_obj`] for each
/// reference in that array.
///
/// Safety
///
/// This method must only be called from `ForeignType::mark`.
#[inline]
pub unsafe fn mark_queue_objarray(ptls: PTls, parent: ValueRef, objs: &[Option<ValueRef>]) {
    jl_gc_mark_queue_objarray(ptls, parent.ptr().as_ptr(), objs.as_ptr() as _, objs.len())
}

/// Updates the write barrier.
///
/// When a pointer field of `data` has been set to `child`, this method must be called
/// immediately after changing the field. This must only be done when the child has been
/// mutated by directly changing the field and `data` is managed by Julia's GC.
///
/// This is necessary because the GC must remain aware of all old objects that contain
/// references to young objects.
///
/// Safety: must be called whenever a field of `self` is set to `child` if `self` is
/// managed by the GC.
#[inline]
pub unsafe fn write_barrier<T>(data: &mut T, child: Value) {
    jl_gc_wb(data as *mut _ as *mut _, child.unwrap(Private))
}

/*
void jl_gc_queue_multiroot(const jl_value_t *parent, const jl_value_t *ptr) JL_NOTSAFEPOINT
{
    // first check if this is really necessary
    // TODO: should we store this info in one of the extra gc bits?
    jl_datatype_t *dt = (jl_datatype_t*)jl_typeof(ptr);
    const jl_datatype_layout_t *ly = dt->layout;
    uint32_t npointers = ly->npointers;
    //if (npointers == 0) // this was checked by the caller
    //    return;
    jl_value_t *ptrf = ((jl_value_t**)ptr)[ly->first_ptr];
    if (ptrf && (jl_astaggedvalue(ptrf)->bits.gc & 1) == 0) {
        // this pointer was young, move the barrier back now
        jl_gc_wb_back(parent);
        return;
    }
    const uint8_t *ptrs8 = (const uint8_t *)jl_dt_layout_ptrs(ly);
    const uint16_t *ptrs16 = (const uint16_t *)jl_dt_layout_ptrs(ly);
    const uint32_t *ptrs32 = (const uint32_t*)jl_dt_layout_ptrs(ly);
    for (size_t i = 1; i < npointers; i++) {
        uint32_t fld;
        if (ly->fielddesc_type == 0) {
            fld = ptrs8[i];
        }
        else if (ly->fielddesc_type == 1) {
            fld = ptrs16[i];
        }
        else {
            assert(ly->fielddesc_type == 2);
            fld = ptrs32[i];
        }
        jl_value_t *ptrf = ((jl_value_t**)ptr)[fld];
        if (ptrf && (jl_astaggedvalue(ptrf)->bits.gc & 1) == 0) {
            // this pointer was young, move the barrier back now
            jl_gc_wb_back(parent);
            return;
        }
    }
}
*/

/// Put the current task in a GC-safe state, call `f`, and return to the previous GC state.
///
/// This must only be used when long-running functions that don't call into Julia are called from
/// a thread that can call into Julia. It puts the current task into a GC-safe state, this can be
/// thought of as extended safepoint: a task that is in a GC-safe state allows the GC to collect
/// garbage as if it had reached a safepoint.
///
/// Safety:
///
/// - This function must be called from a thread that can call into Julia.
/// - `f` must not call into Julia in any way, except inside a function called with `gc_unsafe`.
#[inline]
pub unsafe fn gc_safe<F: FnOnce() -> T, T>(f: F) -> T {
    let ptls = get_tls();

    let state = jlrs_gc_safe_enter(ptls);
    let res = f();
    jlrs_gc_safe_leave(ptls, state);

    res
}

/// Put the current task in a GC-unsafe state, call `f`, and return to the previous GC state.
///
/// This should only be used in a function called with [`gc_safe`]. It puts the task back into a
/// GC=unsafe state. If the task is already in an GC-unsafe state calling this function has no
/// effect.
///
/// Safety:
///
/// - This function must be called from a thread that can call into Julia.
#[inline]
pub unsafe fn gc_unsafe<F: for<'scope> FnOnce(Unrooted<'scope>) -> T, T>(f: F) -> T {
    let ptls = get_tls();

    let unrooted = Unrooted::new();
    let state = jlrs_gc_unsafe_enter(ptls);
    let res = f(unrooted);
    jlrs_gc_unsafe_leave(ptls, state);

    res
}

#[cfg(feature = "sync-rt")]
impl Gc for Julia<'_> {}
impl<'frame, T: Target<'frame>> Gc for T {}

mod private {
    use crate::memory::target::Target;
    #[cfg(feature = "sync-rt")]
    use crate::runtime::sync_rt::Julia;
    pub trait GcPriv {}
    impl<'frame, T: Target<'frame>> GcPriv for T {}
    #[cfg(feature = "sync-rt")]
    impl GcPriv for Julia<'_> {}
}