mmtk/
memory_manager.rs

1//! VM-to-MMTk interface: safe Rust APIs.
2//!
3//! This module provides a safe Rust API for mmtk-core.
4//! We expect the VM binding to inherit and extend this API by:
5//! 1. adding their VM-specific functions
6//! 2. exposing the functions to native if necessary. And the VM binding needs to manage the unsafety
7//!    for exposing this safe API to FFI.
8//!
9//! For example, for mutators, this API provides a `Box<Mutator>`, and requires a `&mut Mutator` for allocation.
10//! A VM binding can borrow a mutable reference directly from `Box<Mutator>`, and call `alloc()`. Alternatively,
11//! it can turn the `Box` pointer to a native pointer (`*mut Mutator`), and forge a mut reference from the native
12//! pointer. Either way, the VM binding code needs to guarantee the safety.
13
14use crate::mmtk::MMTKBuilder;
15use crate::mmtk::MMTK;
16use crate::plan::AllocationSemantics;
17use crate::plan::{Mutator, MutatorContext};
18use crate::scheduler::WorkBucketStage;
19use crate::scheduler::{GCWork, GCWorker};
20use crate::util::alloc::allocator::AllocationOptions;
21use crate::util::alloc::allocators::AllocatorSelector;
22use crate::util::constants::LOG_BYTES_IN_PAGE;
23use crate::util::heap::layout::vm_layout::vm_layout;
24use crate::util::opaque_pointer::*;
25use crate::util::{Address, ObjectReference};
26use crate::vm::slot::MemorySlice;
27use crate::vm::ReferenceGlue;
28use crate::vm::VMBinding;
29
30use std::collections::HashMap;
31
32/// Initialize an MMTk instance. A VM should call this method after creating an [`crate::MMTK`]
33/// instance but before using any of the methods provided in MMTk (except `process()` and `process_bulk()`).
34///
35/// We expect a binding to ininitialize MMTk in the following steps:
36///
37/// 1. Create an [`crate::MMTKBuilder`] instance.
38/// 2. Set command line options for MMTKBuilder by [`crate::memory_manager::process`] or [`crate::memory_manager::process_bulk`].
39/// 3. Initialize MMTk by calling this function, `mmtk_init()`, and pass the builder earlier. This call will return an MMTK instance.
40///    Usually a binding store the MMTK instance statically as a singleton. We plan to allow multiple instances, but this is not yet fully
41///    supported. Currently we assume a binding will only need one MMTk instance. Note that GC is enabled by default and the binding should
42///    implement `VMCollection::is_collection_enabled()` if it requires that the GC should be disabled at a particular time.
43///
44/// This method will attempt to initialize the built-in `env_logger` if the Cargo feature "builtin_env_logger" is enabled (by default).
45/// If the VM would like to use its own logger, it should disable the default feature "builtin_env_logger" in `Cargo.toml`.
46///
47/// Note that, to allow MMTk to do GC properly, `initialize_collection()` needs to be called after this call when
48/// the VM's thread system is ready to spawn GC workers.
49///
50/// Note that this method returns a boxed pointer of MMTK, which means MMTk has a bound lifetime with the box pointer. However, some of our current APIs assume
51/// that MMTk has a static lifetime, which presents a mismatch with this API. We plan to address the lifetime issue in the future. At this point, we recommend a binding
52/// to 'expand' the lifetime for the boxed pointer to static. There could be multiple ways to achieve it: 1. `Box::leak()` will turn the box pointer to raw pointer
53/// which has static lifetime, 2. create MMTK as a lazily initialized static variable
54/// (see [what we do for our dummy binding](https://github.com/mmtk/mmtk-core/blob/master/vmbindings/dummyvm/src/lib.rs#L42))
55///
56/// Arguments:
57/// * `builder`: The reference to a MMTk builder.
58pub fn mmtk_init<VM: VMBinding>(builder: &MMTKBuilder) -> Box<MMTK<VM>> {
59    crate::util::logger::try_init();
60
61    #[cfg(all(feature = "perf_counter", target_os = "linux"))]
62    {
63        use std::fs::File;
64        use std::io::Read;
65        let mut status = File::open("/proc/self/status").unwrap();
66        let mut contents = String::new();
67        status.read_to_string(&mut contents).unwrap();
68        for line in contents.lines() {
69            let split: Vec<&str> = line.split('\t').collect();
70            if split[0] == "Threads:" {
71                let threads = split[1].parse::<i32>().unwrap();
72                if threads != 1 {
73                    warn!("Current process has {} threads, process-wide perf event measurement will only include child threads spawned from this thread", threads);
74                }
75            }
76        }
77    }
78
79    let mmtk = builder.build();
80    info!(
81        "Initialized MMTk with {:?} ({:?})",
82        *mmtk.options.plan, *mmtk.options.gc_trigger
83    );
84    #[cfg(feature = "extreme_assertions")]
85    warn!("The feature 'extreme_assertions' is enabled. MMTk will run expensive run-time checks. Slow performance should be expected.");
86    Box::new(mmtk)
87}
88
89/// Shut down an MMTk instance.
90/// This would asynchronously request GC workers to stop. Bindings need to check if all GC workers have quit in binding-specific ways.
91pub fn mmtk_shutdown<VM: VMBinding>(mmtk: &'static MMTK<VM>) {
92    mmtk.shutdown();
93}
94
95/// Add an externally mmapped region to the VM space. A VM space can be set through MMTk options (`vm_space_start` and `vm_space_size`),
96/// and can also be set through this function call. A VM space can be discontiguous. This function can be called multiple times,
97/// and all the address ranges passed as arguments in the function will be considered as part of the VM space.
98/// Currently we do not allow removing regions from VM space.
99#[cfg(feature = "vm_space")]
100pub fn set_vm_space<VM: VMBinding>(mmtk: &'static mut MMTK<VM>, start: Address, size: usize) {
101    unsafe { mmtk.get_plan_mut() }
102        .base_mut()
103        .vm_space
104        .set_vm_region(start, size);
105}
106
107/// Request MMTk to create a mutator for the given thread. The ownership
108/// of returned boxed mutator is transferred to the binding, and the binding needs to take care of its
109/// lifetime. For performance reasons, A VM should store the returned mutator in a thread local storage
110/// that can be accessed efficiently. A VM may also copy and embed the mutator stucture to a thread-local data
111/// structure, and use that as a reference to the mutator (it is okay to drop the box once the content is copied --
112/// Note that `Mutator` may contain pointers so a binding may drop the box only if they perform a deep copy).
113///
114/// MMTk generally does not expect the runtime to create or destroy mutators during a pause. See also [`crate::vm::ActivePlan::mutators`].
115///
116/// Arguments:
117/// * `mmtk`: A reference to an MMTk instance.
118/// * `tls`: The thread that will be associated with the mutator.
119pub fn bind_mutator<VM: VMBinding>(
120    mmtk: &'static MMTK<VM>,
121    tls: VMMutatorThread,
122) -> Box<Mutator<VM>> {
123    let mutator = crate::plan::create_mutator(tls, mmtk);
124
125    const LOG_ALLOCATOR_MAPPING: bool = false;
126    if LOG_ALLOCATOR_MAPPING {
127        info!("{:?}", mutator.config);
128    }
129    mutator
130}
131
132/// Report to MMTk that a mutator is no longer needed. All mutator state is flushed before it is
133/// destroyed. A binding should not attempt to use the mutator after this call. MMTk will not
134/// attempt to reclaim the memory for the mutator, so a binding should properly reclaim the memory
135/// for the mutator after this call.
136///
137/// MMTk generally does not expect the runtime to create or destroy mutators during a pause. See also [`crate::vm::ActivePlan::mutators`].
138///
139/// Arguments:
140/// * `mutator`: A reference to the mutator to be destroyed.
141pub fn destroy_mutator<VM: VMBinding>(mutator: &mut Mutator<VM>) {
142    mutator.flush();
143    mutator.on_destroy();
144}
145
146/// Flush the mutator's local states.
147///
148/// Arguments:
149/// * `mutator`: A reference to the mutator.
150pub fn flush_mutator<VM: VMBinding>(mutator: &mut Mutator<VM>) {
151    mutator.flush()
152}
153
154/// Allocate memory for an object.
155///
156/// When the allocation is successful, it returns the starting address of the new object.  The
157/// memory range for the new object is `size` bytes starting from the returned address, and
158/// `RETURNED_ADDRESS + offset` is guaranteed to be aligned to the `align` parameter.  The returned
159/// address of a successful allocation will never be zero.
160///
161/// If MMTk fails to allocate memory, it will attempt a GC to free up some memory and retry the
162/// allocation.  After triggering GC, it will call [`crate::vm::Collection::block_for_gc`] to suspend
163/// the current thread that is allocating. Callers of `alloc` must be aware of this behavior.
164/// For example, JIT compilers that support
165/// precise stack scanning need to make the call site of `alloc` a GC-safe point by generating stack maps. See
166/// [`alloc_with_options`] if it is undesirable to trigger GC at this allocation site.
167///
168/// If MMTk has attempted at least one GC, and still cannot free up enough memory, it will call
169/// [`crate::vm::Collection::out_of_memory`] to inform the binding. The VM binding
170/// can implement that method to handle the out-of-memory event in a VM-specific way, including but
171/// not limited to throwing exceptions or errors. If [`crate::vm::Collection::out_of_memory`] returns
172/// normally without panicking or throwing exceptions, this function will return zero.
173///
174/// For performance reasons, a VM should implement the allocation fast-path on their side rather
175/// than just calling this function.
176///
177/// Arguments:
178/// * `mutator`: The mutator to perform this allocation request.
179/// * `size`: The number of bytes required for the object.
180/// * `align`: Required alignment for the object.
181/// * `offset`: Offset associated with the alignment.
182/// * `semantics`: The allocation semantic required for the allocation.
183pub fn alloc<VM: VMBinding>(
184    mutator: &mut Mutator<VM>,
185    size: usize,
186    align: usize,
187    offset: usize,
188    semantics: AllocationSemantics,
189) -> Address {
190    #[cfg(debug_assertions)]
191    crate::util::alloc::allocator::assert_allocation_args::<VM>(size, align, offset);
192
193    mutator.alloc(size, align, offset, semantics)
194}
195
196/// Allocate memory for an object.
197///
198/// This allocation function allows alternation to the allocation behaviors, specified by the
199/// [`crate::util::alloc::AllocationOptions`]. For example, one can allow
200/// overcommit the memory to go beyond the heap size without triggering a GC. This function can be
201/// used in certain cases where the runtime needs a different allocation behavior other than
202/// what the default [`alloc`] provides.
203///
204/// Arguments:
205/// * `mutator`: The mutator to perform this allocation request.
206/// * `size`: The number of bytes required for the object.
207/// * `align`: Required alignment for the object.
208/// * `offset`: Offset associated with the alignment.
209/// * `semantics`: The allocation semantic required for the allocation.
210/// * `options`: the allocation options to change the default allocation behavior for this request.
211pub fn alloc_with_options<VM: VMBinding>(
212    mutator: &mut Mutator<VM>,
213    size: usize,
214    align: usize,
215    offset: usize,
216    semantics: AllocationSemantics,
217    options: crate::util::alloc::allocator::AllocationOptions,
218) -> Address {
219    #[cfg(debug_assertions)]
220    crate::util::alloc::allocator::assert_allocation_args::<VM>(size, align, offset);
221
222    mutator.alloc_with_options(size, align, offset, semantics, options)
223}
224
225/// Invoke the allocation slow path of [`alloc`].
226/// Like [`alloc`], this function may trigger GC and call [`crate::vm::Collection::block_for_gc`] or
227/// [`crate::vm::Collection::out_of_memory`].  The caller needs to be aware of that.
228///
229/// *Notes*: This is only intended for use when a binding implements the fastpath on
230/// the binding side. When the binding handles fast path allocation and the fast path fails, it can use this
231/// method for slow path allocation. Calling before exhausting fast path allocaiton buffer will lead to bad
232/// performance.
233///
234/// Arguments:
235/// * `mutator`: The mutator to perform this allocation request.
236/// * `size`: The number of bytes required for the object.
237/// * `align`: Required alignment for the object.
238/// * `offset`: Offset associated with the alignment.
239/// * `semantics`: The allocation semantic required for the allocation.
240pub fn alloc_slow<VM: VMBinding>(
241    mutator: &mut Mutator<VM>,
242    size: usize,
243    align: usize,
244    offset: usize,
245    semantics: AllocationSemantics,
246) -> Address {
247    mutator.alloc_slow(size, align, offset, semantics)
248}
249
250/// Invoke the allocation slow path of [`alloc_with_options`].
251///
252/// Like [`alloc_with_options`], This allocation function allows alternation to the allocation behaviors, specified by the
253/// [`crate::util::alloc::AllocationOptions`]. For example, one can allow
254/// overcommit the memory to go beyond the heap size without triggering a GC. This function can be
255/// used in certain cases where the runtime needs a different allocation behavior other than
256/// what the default [`alloc`] provides.
257///
258/// Like [`alloc_slow`], this function is also only intended for use when a binding implements the
259/// fastpath on the binding side.
260///
261/// Arguments:
262/// * `mutator`: The mutator to perform this allocation request.
263/// * `size`: The number of bytes required for the object.
264/// * `align`: Required alignment for the object.
265/// * `offset`: Offset associated with the alignment.
266/// * `semantics`: The allocation semantic required for the allocation.
267pub fn alloc_slow_with_options<VM: VMBinding>(
268    mutator: &mut Mutator<VM>,
269    size: usize,
270    align: usize,
271    offset: usize,
272    semantics: AllocationSemantics,
273    options: AllocationOptions,
274) -> Address {
275    mutator.alloc_slow_with_options(size, align, offset, semantics, options)
276}
277
278/// Perform post-allocation actions, usually initializing object metadata. For many allocators none are
279/// required. For performance reasons, a VM should implement the post alloc fast-path on their side
280/// rather than just calling this function.
281///
282/// Arguments:
283/// * `mutator`: The mutator to perform post-alloc actions.
284/// * `refer`: The newly allocated object.
285/// * `bytes`: The size of the space allocated for the object (in bytes).
286/// * `semantics`: The allocation semantics used for the allocation.
287pub fn post_alloc<VM: VMBinding>(
288    mutator: &mut Mutator<VM>,
289    refer: ObjectReference,
290    bytes: usize,
291    semantics: AllocationSemantics,
292) {
293    mutator.post_alloc(refer, bytes, semantics);
294}
295
296/// The *subsuming* write barrier by MMTk. For performance reasons, a VM should implement the write barrier
297/// fast-path on their side rather than just calling this function.
298///
299/// For a correct barrier implementation, a VM binding needs to choose one of the following options:
300/// * Use subsuming barrier `object_reference_write`
301/// * Use both `object_reference_write_pre` and `object_reference_write_post`, or both, if the binding has difficulty delegating the store to mmtk-core with the subsuming barrier.
302/// * Implement fast-path on the VM side, and call the generic api `object_reference_write_slow` as barrier slow-path call.
303/// * Implement fast-path on the VM side, and do a specialized slow-path call.
304///
305/// Arguments:
306/// * `mutator`: The mutator for the current thread.
307/// * `src`: The modified source object.
308/// * `slot`: The location of the field to be modified.
309/// * `target`: The target for the write operation.
310///
311/// # Deprecated
312///
313/// This function needs to be redesigned.  Its current form has multiple issues.
314///
315/// -   It is only able to write non-null object references into the slot.  But dynamic language
316///     VMs may write non-reference values, such as tagged small integers, special values such as
317///     `null`, `undefined`, `true`, `false`, etc. into a field that previous contains an object
318///     reference.
319/// -   It relies on `slot.store` to write `target` into the slot, but `slot.store` is designed for
320///     forwarding references when an object is moved by GC, and is supposed to preserve tagged
321///     type information, the offset (if it is an interior pointer), etc.  A write barrier is
322///     associated to an assignment operation, which usually updates such information instead.
323///
324/// We will redesign a more general subsuming write barrier to address those problems and replace
325/// the current `object_reference_write`.  Before that happens, VM bindings should use
326/// `object_reference_write_pre` and `object_reference_write_post` instead.
327#[deprecated = "Use `object_reference_write_pre` and `object_reference_write_post` instead, until this function is redesigned"]
328pub fn object_reference_write<VM: VMBinding>(
329    mutator: &mut Mutator<VM>,
330    src: ObjectReference,
331    slot: VM::VMSlot,
332    target: ObjectReference,
333) {
334    mutator.barrier().object_reference_write(src, slot, target);
335}
336
337/// The write barrier by MMTk. This is a *pre* write barrier, which we expect a binding to call
338/// *before* it modifies an object. For performance reasons, a VM should implement the write barrier
339/// fast-path on their side rather than just calling this function.
340///
341/// For a correct barrier implementation, a VM binding needs to choose one of the following options:
342/// * Use subsuming barrier `object_reference_write`
343/// * Use both `object_reference_write_pre` and `object_reference_write_post`, or both, if the binding has difficulty delegating the store to mmtk-core with the subsuming barrier.
344/// * Implement fast-path on the VM side, and call the generic api `object_reference_write_slow` as barrier slow-path call.
345/// * Implement fast-path on the VM side, and do a specialized slow-path call.
346///
347/// Arguments:
348/// * `mutator`: The mutator for the current thread.
349/// * `src`: The modified source object.
350/// * `slot`: The location of the field to be modified.
351/// * `target`: The target for the write operation.  `None` if the slot did not hold an object
352///   reference before the write operation.  For example, the slot may be holding a `null`
353///   reference, a small integer, or special values such as `true`, `false`, `undefined`, etc.
354pub fn object_reference_write_pre<VM: VMBinding>(
355    mutator: &mut Mutator<VM>,
356    src: ObjectReference,
357    slot: VM::VMSlot,
358    target: Option<ObjectReference>,
359) {
360    mutator
361        .barrier()
362        .object_reference_write_pre(src, slot, target);
363}
364
365/// The write barrier by MMTk. This is a *post* write barrier, which we expect a binding to call
366/// *after* it modifies an object. For performance reasons, a VM should implement the write barrier
367/// fast-path on their side rather than just calling this function.
368///
369/// For a correct barrier implementation, a VM binding needs to choose one of the following options:
370/// * Use subsuming barrier `object_reference_write`
371/// * Use both `object_reference_write_pre` and `object_reference_write_post`, or both, if the binding has difficulty delegating the store to mmtk-core with the subsuming barrier.
372/// * Implement fast-path on the VM side, and call the generic api `object_reference_write_slow` as barrier slow-path call.
373/// * Implement fast-path on the VM side, and do a specialized slow-path call.
374///
375/// Arguments:
376/// * `mutator`: The mutator for the current thread.
377/// * `src`: The modified source object.
378/// * `slot`: The location of the field to be modified.
379/// * `target`: The target for the write operation.  `None` if the slot no longer hold an object
380///   reference after the write operation.  This may happen when writing a `null` reference, a small
381///   integers, or a special value such as`true`, `false`, `undefined`, etc., into the slot.
382pub fn object_reference_write_post<VM: VMBinding>(
383    mutator: &mut Mutator<VM>,
384    src: ObjectReference,
385    slot: VM::VMSlot,
386    target: Option<ObjectReference>,
387) {
388    mutator
389        .barrier()
390        .object_reference_write_post(src, slot, target);
391}
392
393/// The *subsuming* memory region copy barrier by MMTk.
394/// This is called when the VM tries to copy a piece of heap memory to another.
395/// The data within the slice does not necessarily to be all valid pointers,
396/// but the VM binding will be able to filter out non-reference values on slot iteration.
397///
398/// For VMs that performs a heap memory copy operation, for example OpenJDK's array copy operation, the binding needs to
399/// call `memory_region_copy*` APIs. Same as `object_reference_write*`, the binding can choose either the subsuming barrier,
400/// or the pre/post barrier.
401///
402/// Arguments:
403/// * `mutator`: The mutator for the current thread.
404/// * `src`: Source memory slice to copy from.
405/// * `dst`: Destination memory slice to copy to.
406///
407/// The size of `src` and `dst` shoule be equal
408pub fn memory_region_copy<VM: VMBinding>(
409    mutator: &'static mut Mutator<VM>,
410    src: VM::VMMemorySlice,
411    dst: VM::VMMemorySlice,
412) {
413    debug_assert_eq!(src.bytes(), dst.bytes());
414    mutator.barrier().memory_region_copy(src, dst);
415}
416
417/// The *generic* memory region copy *pre* barrier by MMTk, which we expect a binding to call
418/// *before* it performs memory copy.
419/// This is called when the VM tries to copy a piece of heap memory to another.
420/// The data within the slice does not necessarily to be all valid pointers,
421/// but the VM binding will be able to filter out non-reference values on slot iteration.
422///
423/// For VMs that performs a heap memory copy operation, for example OpenJDK's array copy operation, the binding needs to
424/// call `memory_region_copy*` APIs. Same as `object_reference_write*`, the binding can choose either the subsuming barrier,
425/// or the pre/post barrier.
426///
427/// Arguments:
428/// * `mutator`: The mutator for the current thread.
429/// * `src`: Source memory slice to copy from.
430/// * `dst`: Destination memory slice to copy to.
431///
432/// The size of `src` and `dst` shoule be equal
433pub fn memory_region_copy_pre<VM: VMBinding>(
434    mutator: &'static mut Mutator<VM>,
435    src: VM::VMMemorySlice,
436    dst: VM::VMMemorySlice,
437) {
438    debug_assert_eq!(src.bytes(), dst.bytes());
439    mutator.barrier().memory_region_copy_pre(src, dst);
440}
441
442/// The *generic* memory region copy *post* barrier by MMTk, which we expect a binding to call
443/// *after* it performs memory copy.
444/// This is called when the VM tries to copy a piece of heap memory to another.
445/// The data within the slice does not necessarily to be all valid pointers,
446/// but the VM binding will be able to filter out non-reference values on slot iteration.
447///
448/// For VMs that performs a heap memory copy operation, for example OpenJDK's array copy operation, the binding needs to
449/// call `memory_region_copy*` APIs. Same as `object_reference_write*`, the binding can choose either the subsuming barrier,
450/// or the pre/post barrier.
451///
452/// Arguments:
453/// * `mutator`: The mutator for the current thread.
454/// * `src`: Source memory slice to copy from.
455/// * `dst`: Destination memory slice to copy to.
456///
457/// The size of `src` and `dst` shoule be equal
458pub fn memory_region_copy_post<VM: VMBinding>(
459    mutator: &'static mut Mutator<VM>,
460    src: VM::VMMemorySlice,
461    dst: VM::VMMemorySlice,
462) {
463    debug_assert_eq!(src.bytes(), dst.bytes());
464    mutator.barrier().memory_region_copy_post(src, dst);
465}
466
467/// Return an AllocatorSelector for the given allocation semantic. This method is provided
468/// so that VM compilers may call it to help generate allocation fast-path.
469///
470/// Arguments:
471/// * `mmtk`: The reference to an MMTk instance.
472/// * `semantics`: The allocation semantic to query.
473pub fn get_allocator_mapping<VM: VMBinding>(
474    mmtk: &MMTK<VM>,
475    semantics: AllocationSemantics,
476) -> AllocatorSelector {
477    mmtk.get_plan().get_allocator_mapping()[semantics]
478}
479
480/// The standard malloc. MMTk either uses its own allocator, or forward the call to a
481/// library malloc.
482pub fn malloc(size: usize) -> Address {
483    crate::util::malloc::malloc(size)
484}
485
486/// The standard malloc except that with the feature `malloc_counted_size`, MMTk will count the allocated memory into its heap size.
487/// Thus the method requires a reference to an MMTk instance. MMTk either uses its own allocator, or forward the call to a
488/// library malloc.
489#[cfg(feature = "malloc_counted_size")]
490pub fn counted_malloc<VM: VMBinding>(mmtk: &MMTK<VM>, size: usize) -> Address {
491    crate::util::malloc::counted_malloc(mmtk, size)
492}
493
494/// The standard calloc.
495pub fn calloc(num: usize, size: usize) -> Address {
496    crate::util::malloc::calloc(num, size)
497}
498
499/// The standard calloc except that with the feature `malloc_counted_size`, MMTk will count the allocated memory into its heap size.
500/// Thus the method requires a reference to an MMTk instance.
501#[cfg(feature = "malloc_counted_size")]
502pub fn counted_calloc<VM: VMBinding>(mmtk: &MMTK<VM>, num: usize, size: usize) -> Address {
503    crate::util::malloc::counted_calloc(mmtk, num, size)
504}
505
506/// The standard realloc.
507pub fn realloc(addr: Address, size: usize) -> Address {
508    crate::util::malloc::realloc(addr, size)
509}
510
511/// The standard realloc except that with the feature `malloc_counted_size`, MMTk will count the allocated memory into its heap size.
512/// Thus the method requires a reference to an MMTk instance, and the size of the existing memory that will be reallocated.
513/// The `addr` in the arguments must be an address that is earlier returned from MMTk's `malloc()`, `calloc()` or `realloc()`.
514#[cfg(feature = "malloc_counted_size")]
515pub fn realloc_with_old_size<VM: VMBinding>(
516    mmtk: &MMTK<VM>,
517    addr: Address,
518    size: usize,
519    old_size: usize,
520) -> Address {
521    crate::util::malloc::realloc_with_old_size(mmtk, addr, size, old_size)
522}
523
524/// The standard free.
525/// The `addr` in the arguments must be an address that is earlier returned from MMTk's `malloc()`, `calloc()` or `realloc()`.
526pub fn free(addr: Address) {
527    crate::util::malloc::free(addr)
528}
529
530/// The standard free except that with the feature `malloc_counted_size`, MMTk will count the allocated memory into its heap size.
531/// Thus the method requires a reference to an MMTk instance, and the size of the memory to free.
532/// The `addr` in the arguments must be an address that is earlier returned from MMTk's `malloc()`, `calloc()` or `realloc()`.
533#[cfg(feature = "malloc_counted_size")]
534pub fn free_with_size<VM: VMBinding>(mmtk: &MMTK<VM>, addr: Address, old_size: usize) {
535    crate::util::malloc::free_with_size(mmtk, addr, old_size)
536}
537
538/// Get the current active malloc'd bytes. Here MMTk only accounts for bytes that are done through those 'counted malloc' functions.
539#[cfg(feature = "malloc_counted_size")]
540pub fn get_malloc_bytes<VM: VMBinding>(mmtk: &MMTK<VM>) -> usize {
541    use std::sync::atomic::Ordering;
542    mmtk.state.malloc_bytes.load(Ordering::SeqCst)
543}
544
545/// Poll for GC. MMTk will decide if a GC is needed. If so, this call will block
546/// the current thread, and trigger a GC. Otherwise, it will simply return.
547/// Usually a binding does not need to call this function. MMTk will poll for GC during its allocation.
548/// However, if a binding uses counted malloc (which won't poll for GC), they may want to poll for GC manually.
549/// This function should only be used by mutator threads.
550pub fn gc_poll<VM: VMBinding>(mmtk: &MMTK<VM>, tls: VMMutatorThread) {
551    use crate::vm::{ActivePlan, Collection};
552    debug_assert!(
553        VM::VMActivePlan::is_mutator(tls.0),
554        "gc_poll() can only be called by a mutator thread."
555    );
556
557    if mmtk.gc_trigger.poll(false, None) {
558        debug!("Collection required");
559        if !mmtk.state.is_initialized() {
560            panic!("GC is not allowed here: collection is not initialized (did you call initialize_collection()?).");
561        }
562        VM::VMCollection::block_for_gc(tls);
563    }
564}
565
566/// Wrapper for [`crate::scheduler::GCWorker::run`].
567pub fn start_worker<VM: VMBinding>(
568    mmtk: &'static MMTK<VM>,
569    tls: VMWorkerThread,
570    worker: Box<GCWorker<VM>>,
571) {
572    worker.run(tls, mmtk);
573}
574
575/// Wrapper for [`crate::mmtk::MMTK::initialize_collection`].
576pub fn initialize_collection<VM: VMBinding>(mmtk: &'static MMTK<VM>, tls: VMThread) {
577    mmtk.initialize_collection(tls);
578}
579
580/// Process MMTk run-time options. Returns true if the option is processed successfully.
581///
582/// Arguments:
583/// * `mmtk`: A reference to an MMTk instance.
584/// * `name`: The name of the option.
585/// * `value`: The value of the option (as a string).
586pub fn process(builder: &mut MMTKBuilder, name: &str, value: &str) -> bool {
587    builder.set_option(name, value)
588}
589
590/// Process multiple MMTk run-time options. Returns true if all the options are processed successfully.
591///
592/// Arguments:
593/// * `mmtk`: A reference to an MMTk instance.
594/// * `options`: a string that is key value pairs separated by white spaces, e.g. "threads=1 stress_factor=4096"
595pub fn process_bulk(builder: &mut MMTKBuilder, options: &str) -> bool {
596    builder.set_options_bulk_by_str(options)
597}
598
599/// Return used memory in bytes. MMTk accounts for memory in pages, thus this method always returns a value in
600/// page granularity.
601///
602/// Arguments:
603/// * `mmtk`: A reference to an MMTk instance.
604pub fn used_bytes<VM: VMBinding>(mmtk: &MMTK<VM>) -> usize {
605    mmtk.get_plan().get_used_pages() << LOG_BYTES_IN_PAGE
606}
607
608/// Return free memory in bytes. MMTk accounts for memory in pages, thus this method always returns a value in
609/// page granularity.
610///
611/// Arguments:
612/// * `mmtk`: A reference to an MMTk instance.
613pub fn free_bytes<VM: VMBinding>(mmtk: &MMTK<VM>) -> usize {
614    mmtk.get_plan().get_free_pages() << LOG_BYTES_IN_PAGE
615}
616
617/// Return a hash map for live bytes statistics in the last GC for each space.
618///
619/// MMTk usually accounts for memory in pages by each space.
620/// This is a special method that we count the size of every live object in a GC, and sum up the total bytes.
621/// We provide this method so users can use [`crate::LiveBytesStats`] to know if
622/// the space is fragmented.
623/// The value returned by this method is only updated when we finish tracing in a GC. A recommended timing
624/// to call this method is at the end of a GC (e.g. when the runtime is about to resume threads).
625pub fn live_bytes_in_last_gc<VM: VMBinding>(
626    mmtk: &MMTK<VM>,
627) -> HashMap<&'static str, crate::LiveBytesStats> {
628    mmtk.state.live_bytes_in_last_gc.borrow().clone()
629}
630
631/// Return the starting address of the heap. *Note that currently MMTk uses
632/// a fixed address range as heap.*
633pub fn starting_heap_address() -> Address {
634    vm_layout().heap_start
635}
636
637/// Return the ending address of the heap. *Note that currently MMTk uses
638/// a fixed address range as heap.*
639pub fn last_heap_address() -> Address {
640    vm_layout().heap_end
641}
642
643/// Return the total memory in bytes.
644///
645/// Arguments:
646/// * `mmtk`: A reference to an MMTk instance.
647pub fn total_bytes<VM: VMBinding>(mmtk: &MMTK<VM>) -> usize {
648    mmtk.get_plan().get_total_pages() << LOG_BYTES_IN_PAGE
649}
650
651/// The application code has requested a collection. This is just a GC hint, and
652/// we may ignore it.
653///
654/// Returns whether a GC was ran or not. If MMTk triggers a GC, this method will block the
655/// calling thread and return true when the GC finishes. Otherwise, this method returns
656/// false immediately.
657///
658/// Arguments:
659/// * `mmtk`: A reference to an MMTk instance.
660/// * `tls`: The thread that triggers this collection request.
661pub fn handle_user_collection_request<VM: VMBinding>(
662    mmtk: &MMTK<VM>,
663    tls: VMMutatorThread,
664) -> bool {
665    mmtk.handle_user_collection_request(tls, false, false)
666}
667
668/// Is the object alive?
669///
670/// Arguments:
671/// * `object`: The object reference to query.
672pub fn is_live_object(object: ObjectReference) -> bool {
673    object.is_live()
674}
675
676/// Check if `addr` is the raw address of an object reference to an MMTk object.
677///
678/// Concretely:
679/// 1.  Return `Some(object)` if `ObjectReference::from_raw_address(addr)` is a valid object
680///     reference to an object in any space in MMTk. `object` is the result of
681///     `ObjectReference::from_raw_address(addr)`.
682/// 2.  Return `None` otherwise.
683///
684/// This function is useful for conservative root scanning.  The VM can iterate through all words in
685/// a stack, filter out zeros, misaligned words, obviously out-of-range words (such as addresses
686/// greater than `0x0000_7fff_ffff_ffff` on Linux on x86_64), and use this function to deside if the
687/// word is really a reference.
688///
689/// This function does not handle internal pointers. If a binding may have internal pointers on
690/// the stack, and requires identifying the base reference for an internal pointer, they should use
691/// [`find_object_from_internal_pointer`] instead.
692///
693/// Note: This function has special behaviors if the VM space (enabled by the `vm_space` feature)
694/// is present.  See `crate::plan::global::BasePlan::vm_space`.
695///
696/// Argument:
697/// * `addr`: A non-zero word-aligned address.  Because the raw address of an `ObjectReference`
698///   cannot be zero and must be word-aligned, the caller must filter out zero and misaligned
699///   addresses before calling this function.  Otherwise the behavior is undefined.
700#[cfg(feature = "vo_bit")]
701pub fn is_mmtk_object(addr: Address) -> Option<ObjectReference> {
702    crate::util::is_mmtk_object::check_object_reference(addr)
703}
704
705/// Find if there is an object with VO bit set for the given address range.
706/// This should be used instead of [`crate::memory_manager::is_mmtk_object`] for conservative stack scanning if
707/// the binding may have internal pointers on the stack.
708///
709/// Note that, we only consider pointers that point to addresses that are equal to or greater than
710/// the raw addresss of the object's `ObjectReference`, and within the allocation as 'internal
711/// pointers'. To be precise, for each object ref `obj_ref`, internal pointers are in the range
712/// `[obj_ref.to_raw_address(), obj_ref.to_object_start() +
713/// ObjectModel::get_current_size(obj_ref))`. If a binding defines internal pointers differently,
714/// calling this method is undefined behavior. If this is the case for you, please submit an issue
715/// or engage us on Zulip to discuss more.
716///
717/// Note that, in the similar situation as [`crate::memory_manager::is_mmtk_object`], the binding should filter
718/// out obvious non-pointers (e.g. alignment check, bound check, etc) before calling this function to avoid unnecessary
719/// cost. This method is not cheap.
720///
721/// To minimize the cost, the user should also use a small `max_search_bytes`.
722///
723/// Note: This function has special behaviors if the VM space (enabled by the `vm_space` feature)
724/// is present.  See `crate::plan::global::BasePlan::vm_space`.
725///
726/// Argument:
727/// * `internal_ptr`: The address to start searching. We search backwards from this address (including this address) to find the base reference.
728/// * `max_search_bytes`: The maximum number of bytes we may search for an object with VO bit set. `internal_ptr - max_search_bytes` is not included.
729#[cfg(feature = "vo_bit")]
730pub fn find_object_from_internal_pointer(
731    internal_ptr: Address,
732    max_search_bytes: usize,
733) -> Option<ObjectReference> {
734    crate::util::is_mmtk_object::check_internal_reference(internal_ptr, max_search_bytes)
735}
736
737/// Return true if the `object` lies in a region of memory where
738/// -   only MMTk can allocate into, or
739/// -   only MMTk's delegated memory allocator (such as a malloc implementation) can allocate into
740///     for allocation requests from MMTk.
741///
742/// Return false otherwise.  This function never panics.
743///
744/// Particularly, if this function returns true, `object` cannot be an object allocated by the VM
745/// itself.
746///
747/// If this function returns true, the object cannot be allocate by the `malloc` function called by
748/// the VM, either. In other words, if the `MallocSpace` of MMTk called `malloc` to allocate the
749/// object for the VM in response to `memory_manager::alloc`, this function will return true; but
750/// if the VM directly called `malloc` to allocate the object, this function will return false.
751///
752/// If `is_mmtk_object(object.to_raw_address())` returns true, `is_in_mmtk_spaces(object)` must also
753/// return true.
754///
755/// This function is useful if an object reference in the VM can be either a pointer into the MMTk
756/// heap, or a pointer to non-MMTk objects.  If the VM has a pre-built boot image that contains
757/// primordial objects, or if the VM has its own allocator or uses any third-party allocators, or
758/// if the VM allows an object reference to point to native objects such as C++ objects, this
759/// function can distinguish between MMTk-allocated objects and other objects.
760///
761/// Note: This function has special behaviors if the VM space (enabled by the `vm_space` feature)
762/// is present.  See `crate::plan::global::BasePlan::vm_space`.
763///
764/// Arguments:
765/// * `object`: The object reference to query.
766pub fn is_in_mmtk_spaces(object: ObjectReference) -> bool {
767    use crate::mmtk::SFT_MAP;
768    SFT_MAP
769        .get_checked(object.to_raw_address())
770        .is_in_space(object)
771}
772
773/// Is the address in the mapped memory? The runtime can use this function to check
774/// if an address is mapped by MMTk. Note that this is different than is_in_mmtk_spaces().
775/// For malloc spaces, MMTk does not map those addresses (malloc does the mmap), so
776/// this function will return false, but is_in_mmtk_spaces will return true if the address
777/// is actually a valid object in malloc spaces. To check if an object is in our heap,
778/// the runtime should always use is_in_mmtk_spaces(). This function is_mapped_address()
779/// may get removed at some point.
780///
781/// Arguments:
782/// * `address`: The address to query.
783// TODO: Do we really need this function? Can a runtime always use is_mapped_object()?
784pub fn is_mapped_address(address: Address) -> bool {
785    address.is_mapped()
786}
787
788/// Add a reference to the list of weak references. A binding may
789/// call this either when a weak reference is created, or when a weak reference is traced during GC.
790///
791/// Arguments:
792/// * `mmtk`: A reference to an MMTk instance.
793/// * `reff`: The weak reference to add.
794pub fn add_weak_candidate<VM: VMBinding>(mmtk: &MMTK<VM>, reff: ObjectReference) {
795    mmtk.reference_processors.add_weak_candidate(reff);
796}
797
798/// Add a reference to the list of soft references. A binding may
799/// call this either when a weak reference is created, or when a weak reference is traced during GC.
800///
801/// Arguments:
802/// * `mmtk`: A reference to an MMTk instance.
803/// * `reff`: The soft reference to add.
804pub fn add_soft_candidate<VM: VMBinding>(mmtk: &MMTK<VM>, reff: ObjectReference) {
805    mmtk.reference_processors.add_soft_candidate(reff);
806}
807
808/// Add a reference to the list of phantom references. A binding may
809/// call this either when a weak reference is created, or when a weak reference is traced during GC.
810///
811/// Arguments:
812/// * `mmtk`: A reference to an MMTk instance.
813/// * `reff`: The phantom reference to add.
814pub fn add_phantom_candidate<VM: VMBinding>(mmtk: &MMTK<VM>, reff: ObjectReference) {
815    mmtk.reference_processors.add_phantom_candidate(reff);
816}
817
818/// Generic hook to allow benchmarks to be harnessed. We do a full heap
819/// GC, and then start recording statistics for MMTk.
820///
821/// Arguments:
822/// * `mmtk`: A reference to an MMTk instance.
823/// * `tls`: The thread that calls the function (and triggers a collection).
824pub fn harness_begin<VM: VMBinding>(mmtk: &MMTK<VM>, tls: VMMutatorThread) {
825    mmtk.harness_begin(tls);
826}
827
828/// Generic hook to allow benchmarks to be harnessed. We stop collecting
829/// statistics, and print stats values.
830///
831/// Arguments:
832/// * `mmtk`: A reference to an MMTk instance.
833pub fn harness_end<VM: VMBinding>(mmtk: &'static MMTK<VM>) {
834    mmtk.harness_end();
835}
836
837/// Register a finalizable object. MMTk will retain the liveness of
838/// the object even if it is not reachable from the program.
839/// Note that finalization upon exit is not supported.
840///
841/// Arguments:
842/// * `mmtk`: A reference to an MMTk instance
843/// * `object`: The object that has a finalizer
844pub fn add_finalizer<VM: VMBinding>(
845    mmtk: &'static MMTK<VM>,
846    object: <VM::VMReferenceGlue as ReferenceGlue<VM>>::FinalizableType,
847) {
848    if *mmtk.options.no_finalizer {
849        warn!("add_finalizer() is called when no_finalizer = true");
850    }
851
852    mmtk.finalizable_processor.lock().unwrap().add(object);
853}
854
855/// Pin an object. MMTk will make sure that the object does not move
856/// during GC. Note that action cannot happen in some plans, eg, semispace.
857/// It returns true if the pinning operation has been performed, i.e.,
858/// the object status changed from non-pinned to pinned
859///
860/// Arguments:
861/// * `object`: The object to be pinned
862#[cfg(feature = "object_pinning")]
863pub fn pin_object(object: ObjectReference) -> bool {
864    use crate::mmtk::SFT_MAP;
865    SFT_MAP
866        .get_checked(object.to_raw_address())
867        .pin_object(object)
868}
869
870/// Unpin an object.
871/// Returns true if the unpinning operation has been performed, i.e.,
872/// the object status changed from pinned to non-pinned
873///
874/// Arguments:
875/// * `object`: The object to be pinned
876#[cfg(feature = "object_pinning")]
877pub fn unpin_object(object: ObjectReference) -> bool {
878    use crate::mmtk::SFT_MAP;
879    SFT_MAP
880        .get_checked(object.to_raw_address())
881        .unpin_object(object)
882}
883
884/// Check whether an object is currently pinned
885///
886/// Arguments:
887/// * `object`: The object to be checked
888#[cfg(feature = "object_pinning")]
889pub fn is_pinned(object: ObjectReference) -> bool {
890    use crate::mmtk::SFT_MAP;
891    SFT_MAP
892        .get_checked(object.to_raw_address())
893        .is_object_pinned(object)
894}
895
896/// Get an object that is ready for finalization. After each GC, if any registered object is not
897/// alive, this call will return one of the objects. MMTk will retain the liveness of those objects
898/// until they are popped through this call. Once an object is popped, it is the responsibility of
899/// the VM to make sure they are properly finalized before reclaimed by the GC. This call is non-blocking,
900/// and will return None if no object is ready for finalization.
901///
902/// Arguments:
903/// * `mmtk`: A reference to an MMTk instance.
904pub fn get_finalized_object<VM: VMBinding>(
905    mmtk: &'static MMTK<VM>,
906) -> Option<<VM::VMReferenceGlue as ReferenceGlue<VM>>::FinalizableType> {
907    if *mmtk.options.no_finalizer {
908        warn!("get_finalized_object() is called when no_finalizer = true");
909    }
910
911    mmtk.finalizable_processor
912        .lock()
913        .unwrap()
914        .get_ready_object()
915}
916
917/// Pop all the finalizers that were registered for finalization. The returned objects may or may not be ready for
918/// finalization. After this call, MMTk's finalizer processor should have no registered finalizer any more.
919///
920/// This is useful for some VMs which require all finalizable objects to be finalized on exit.
921///
922/// Arguments:
923/// * `mmtk`: A reference to an MMTk instance.
924pub fn get_all_finalizers<VM: VMBinding>(
925    mmtk: &'static MMTK<VM>,
926) -> Vec<<VM::VMReferenceGlue as ReferenceGlue<VM>>::FinalizableType> {
927    if *mmtk.options.no_finalizer {
928        warn!("get_all_finalizers() is called when no_finalizer = true");
929    }
930
931    mmtk.finalizable_processor
932        .lock()
933        .unwrap()
934        .get_all_finalizers()
935}
936
937/// Pop finalizers that were registered and associated with a certain object. The returned objects may or may not be ready for finalization.
938/// This is useful for some VMs that may manually execute finalize method for an object.
939///
940/// Arguments:
941/// * `mmtk`: A reference to an MMTk instance.
942/// * `object`: the given object that MMTk will pop its finalizers
943pub fn get_finalizers_for<VM: VMBinding>(
944    mmtk: &'static MMTK<VM>,
945    object: ObjectReference,
946) -> Vec<<VM::VMReferenceGlue as ReferenceGlue<VM>>::FinalizableType> {
947    if *mmtk.options.no_finalizer {
948        warn!("get_finalizers() is called when no_finalizer = true");
949    }
950
951    mmtk.finalizable_processor
952        .lock()
953        .unwrap()
954        .get_finalizers_for(object)
955}
956
957/// Get the number of workers. MMTk spawns worker threads for the 'threads' defined in the options.
958/// So the number of workers is derived from the threads option. Note the feature single_worker overwrites
959/// the threads option, and force one worker thread.
960///
961/// Arguments:
962/// * `mmtk`: A reference to an MMTk instance.
963pub fn num_of_workers<VM: VMBinding>(mmtk: &'static MMTK<VM>) -> usize {
964    mmtk.scheduler.num_workers()
965}
966
967/// Add a work packet to the given work bucket. Note that this simply adds the work packet to the given
968/// work bucket, and the scheduler will decide when to execute the work packet.
969///
970/// Arguments:
971/// * `mmtk`: A reference to an MMTk instance.
972/// * `bucket`: Which work bucket to add this packet to.
973/// * `packet`: The work packet to be added.
974pub fn add_work_packet<VM: VMBinding, W: GCWork<VM>>(
975    mmtk: &'static MMTK<VM>,
976    bucket: WorkBucketStage,
977    packet: W,
978) {
979    mmtk.scheduler.work_buckets[bucket].add(packet)
980}
981
982/// Bulk add a number of work packets to the given work bucket. Note that this simply adds the work packets
983/// to the given work bucket, and the scheduler will decide when to execute the work packets.
984///
985/// Arguments:
986/// * `mmtk`: A reference to an MMTk instance.
987/// * `bucket`: Which work bucket to add these packets to.
988/// * `packet`: The work packets to be added.
989pub fn add_work_packets<VM: VMBinding>(
990    mmtk: &'static MMTK<VM>,
991    bucket: WorkBucketStage,
992    packets: Vec<Box<dyn GCWork<VM>>>,
993) {
994    mmtk.scheduler.work_buckets[bucket].bulk_add(packets)
995}