1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
8 * High-level interface to the JS garbage collector.
14 #include "mozilla/TimeStamp.h"
15 #include "mozilla/Vector.h"
17 #include "js/GCAnnotations.h"
18 #include "js/shadow/Zone.h"
19 #include "js/SliceBudget.h"
20 #include "js/TypeDecls.h"
21 #include "js/UniquePtr.h"
22 #include "js/Utility.h"
24 class JS_PUBLIC_API JSTracer
;
30 class JS_PUBLIC_API SliceBudget
;
33 } // namespace gcstats
38 // Options used when starting a GC.
39 enum class GCOptions
: uint32_t {
40 // Normal GC invocation.
42 // Some objects that are unreachable from the program may still be alive after
43 // collection because of internal references
48 // Try to release as much memory as possible by clearing internal caches,
49 // aggressively discarding JIT code and decommitting unused chunks. This
50 // ensures all unreferenced objects are removed from the system.
52 // Finally, compact the GC heap.
57 // This does more drastic cleanup as part of system shutdown, including:
58 // - clearing WeakRef kept object sets
59 // - not marking FinalizationRegistry roots
60 // - repeating collection if JS::NotifyGCRootsRemoved was called
61 // - skipping scheduling of various future work that won't be needed
63 // Note that this assumes that no JS will run after this point!
69 typedef enum JSGCParamKey
{
71 * Maximum nominal heap before last ditch GC.
73 * Soft limit on the number of bytes we are allowed to allocate in the GC
74 * heap. Attempts to allocate gcthings over this limit will return null and
75 * subsequently invoke the standard OOM machinery, independent of available
78 * Pref: javascript.options.mem.max
84 * Maximum size of the generational GC nurseries.
86 * This will be rounded to the nearest gc::ChunkSize.
88 * Pref: javascript.options.mem.nursery.max_kb
89 * Default: JS::DefaultNurseryMaxBytes
91 JSGC_MAX_NURSERY_BYTES
= 2,
93 /** Amount of bytes allocated by the GC. */
96 /** Number of times GC has been invoked. Includes both major and minor GC. */
100 * Whether incremental GC is enabled. If not, GC will always run to
103 * prefs: javascript.options.mem.gc_incremental.
106 JSGC_INCREMENTAL_GC_ENABLED
= 5,
109 * Whether per-zone GC is enabled. If not, all zones are collected every time.
111 * prefs: javascript.options.mem.gc_per_zone
114 JSGC_PER_ZONE_GC_ENABLED
= 6,
116 /** Number of cached empty GC chunks. */
117 JSGC_UNUSED_CHUNKS
= 7,
119 /** Total number of allocated GC chunks. */
120 JSGC_TOTAL_CHUNKS
= 8,
123 * Max milliseconds to spend in an incremental GC slice.
125 * A value of zero means there is no maximum.
127 * Pref: javascript.options.mem.gc_incremental_slice_ms
128 * Default: DefaultTimeBudgetMS.
130 JSGC_SLICE_TIME_BUDGET_MS
= 9,
133 * The "do we collect?" decision depends on various parameters and can be
136 * ZoneSize > Max(ThresholdBase, LastSize) * GrowthFactor * ThresholdFactor
139 * ZoneSize: Current size of this zone.
140 * LastSize: Heap size immediately after the most recent collection.
141 * ThresholdBase: The JSGC_ALLOCATION_THRESHOLD parameter
142 * GrowthFactor: A number above 1, calculated based on some of the
143 * following parameters.
144 * See computeZoneHeapGrowthFactorForHeapSize() in GC.cpp
145 * ThresholdFactor: 1.0 to trigger an incremental collections or between
146 * JSGC_SMALL_HEAP_INCREMENTAL_LIMIT and
147 * JSGC_LARGE_HEAP_INCREMENTAL_LIMIT to trigger a
148 * non-incremental collection.
150 * The RHS of the equation above is calculated and sets
151 * zone->gcHeapThreshold.bytes(). When gcHeapSize.bytes() exeeds
152 * gcHeapThreshold.bytes() for a zone, the zone may be scheduled for a GC.
156 * GCs less than this far apart in milliseconds will be considered
157 * 'high-frequency GCs'.
159 * Pref: javascript.options.mem.gc_high_frequency_time_limit_ms
160 * Default: HighFrequencyThreshold
162 JSGC_HIGH_FREQUENCY_TIME_LIMIT
= 11,
165 * Upper limit for classifying a heap as small (MB).
167 * Dynamic heap growth thresholds are based on whether the heap is small,
168 * medium or large. Heaps smaller than this size are classified as small;
169 * larger heaps are classified as medium or large.
171 * Pref: javascript.options.mem.gc_small_heap_size_max_mb
172 * Default: SmallHeapSizeMaxBytes
174 JSGC_SMALL_HEAP_SIZE_MAX
= 12,
177 * Lower limit for classifying a heap as large (MB).
179 * Dynamic heap growth thresholds are based on whether the heap is small,
180 * medium or large. Heaps larger than this size are classified as large;
181 * smaller heaps are classified as small or medium.
183 * Pref: javascript.options.mem.gc_large_heap_size_min_mb
184 * Default: LargeHeapSizeMinBytes
186 JSGC_LARGE_HEAP_SIZE_MIN
= 13,
189 * Heap growth factor for small heaps in the high-frequency GC state.
191 * Pref: javascript.options.mem.gc_high_frequency_small_heap_growth
192 * Default: HighFrequencySmallHeapGrowth
194 JSGC_HIGH_FREQUENCY_SMALL_HEAP_GROWTH
= 14,
197 * Heap growth factor for large heaps in the high-frequency GC state.
199 * Pref: javascript.options.mem.gc_high_frequency_large_heap_growth
200 * Default: HighFrequencyLargeHeapGrowth
202 JSGC_HIGH_FREQUENCY_LARGE_HEAP_GROWTH
= 15,
205 * Heap growth factor for low frequency GCs.
207 * This factor is applied regardless of the size of the heap when not in the
208 * high-frequency GC state.
210 * Pref: javascript.options.mem.gc_low_frequency_heap_growth
211 * Default: LowFrequencyHeapGrowth
213 JSGC_LOW_FREQUENCY_HEAP_GROWTH
= 16,
216 * Whether balanced heap limits are enabled.
218 * If this is set to true then heap limits are calculated in a way designed to
219 * balance memory usage optimally between many heaps.
221 * Otherwise, heap limits are set based on a linear multiple of the retained
222 * size after the last collection.
224 * Pref: javascript.options.mem.gc_balanced_heap_limits
225 * Default: BalancedHeapLimitsEnabled
227 JSGC_BALANCED_HEAP_LIMITS_ENABLED
= 17,
230 * Heap growth parameter for balanced heap limit calculation.
232 * This parameter trades off GC time for memory usage. Smaller values result
233 * in lower memory use and larger values result in less time spent collecting.
235 * Heap limits are set to the heap's retained size plus some extra space. The
236 * extra space is calculated based on several factors but is scaled
237 * proportionally to this parameter.
239 * Pref: javascript.options.mem.gc_heap_growth_factor
240 * Default: HeapGrowthFactor
242 JSGC_HEAP_GROWTH_FACTOR
= 18,
245 * Lower limit for collecting a zone (MB).
247 * Zones smaller than this size will not normally be collected.
249 * Pref: javascript.options.mem.gc_allocation_threshold_mb
250 * Default GCZoneAllocThresholdBase
252 JSGC_ALLOCATION_THRESHOLD
= 19,
255 * We try to keep at least this many unused chunks in the free chunk pool at
256 * all times, even after a shrinking GC.
258 * Pref: javascript.options.mem.gc_min_empty_chunk_count
259 * Default: MinEmptyChunkCount
261 JSGC_MIN_EMPTY_CHUNK_COUNT
= 21,
264 * We never keep more than this many unused chunks in the free chunk pool.
266 * Pref: javascript.options.mem.gc_max_empty_chunk_count
267 * Default: MaxEmptyChunkCount
269 JSGC_MAX_EMPTY_CHUNK_COUNT
= 22,
272 * Whether compacting GC is enabled.
274 * Pref: javascript.options.mem.gc_compacting
275 * Default: CompactingEnabled
277 JSGC_COMPACTING_ENABLED
= 23,
280 * Whether parallel marking is enabled.
282 * Pref: javascript.options.mem.gc_parallel_marking
283 * Default: ParallelMarkingEnabled
285 JSGC_PARALLEL_MARKING_ENABLED
= 24,
288 * Limit of how far over the incremental trigger threshold we allow the heap
289 * to grow before finishing a collection non-incrementally, for small heaps.
291 * We trigger an incremental GC when a trigger threshold is reached but the
292 * collection may not be fast enough to keep up with the mutator. At some
293 * point we finish the collection non-incrementally.
295 * Default: SmallHeapIncrementalLimit
296 * Pref: javascript.options.mem.gc_small_heap_incremental_limit
298 JSGC_SMALL_HEAP_INCREMENTAL_LIMIT
= 25,
301 * Limit of how far over the incremental trigger threshold we allow the heap
302 * to grow before finishing a collection non-incrementally, for large heaps.
304 * Default: LargeHeapIncrementalLimit
305 * Pref: javascript.options.mem.gc_large_heap_incremental_limit
307 JSGC_LARGE_HEAP_INCREMENTAL_LIMIT
= 26,
310 * Attempt to run a minor GC in the idle time if the free space falls
311 * below this number of bytes.
313 * Default: NurseryChunkUsableSize / 4
316 JSGC_NURSERY_FREE_THRESHOLD_FOR_IDLE_COLLECTION
= 27,
319 * If this percentage of the nursery is tenured and the nursery is at least
320 * 4MB, then proceed to examine which groups we should pretenure.
322 * Default: PretenureThreshold
325 JSGC_PRETENURE_THRESHOLD
= 28,
328 * Attempt to run a minor GC in the idle time if the free space falls
329 * below this percentage (from 0 to 99).
334 JSGC_NURSERY_FREE_THRESHOLD_FOR_IDLE_COLLECTION_PERCENT
= 30,
337 * Minimum size of the generational GC nurseries.
339 * This value will be rounded to the nearest Nursery::SubChunkStep if below
340 * gc::ChunkSize, otherwise it'll be rounded to the nearest gc::ChunkSize.
342 * Default: Nursery::SubChunkLimit
343 * Pref: javascript.options.mem.nursery.min_kb
345 JSGC_MIN_NURSERY_BYTES
= 31,
348 * The minimum time to allow between triggering last ditch GCs in seconds.
350 * Default: 60 seconds
353 JSGC_MIN_LAST_DITCH_GC_PERIOD
= 32,
356 * The delay (in heapsize kilobytes) between slices of an incremental GC.
358 * Default: ZoneAllocDelayBytes
360 JSGC_ZONE_ALLOC_DELAY_KB
= 33,
363 * The current size of the nursery.
365 * This parameter is read-only.
367 JSGC_NURSERY_BYTES
= 34,
370 * Retained size base value for calculating malloc heap threshold.
372 * Default: MallocThresholdBase
374 JSGC_MALLOC_THRESHOLD_BASE
= 35,
377 * Whether incremental weakmap marking is enabled.
379 * Pref: javascript.options.mem.incremental_weakmap
380 * Default: IncrementalWeakMarkEnabled
382 JSGC_INCREMENTAL_WEAKMAP_ENABLED
= 37,
385 * The chunk size in bytes for this system.
387 * This parameter is read-only.
389 JSGC_CHUNK_BYTES
= 38,
392 * The number of background threads to use for parallel GC work for each CPU
393 * core, expressed as an integer percentage.
395 * Pref: javascript.options.mem.gc_helper_thread_ratio
397 JSGC_HELPER_THREAD_RATIO
= 39,
400 * The maximum number of background threads to use for parallel GC work.
402 * Pref: javascript.options.mem.gc_max_helper_threads
404 JSGC_MAX_HELPER_THREADS
= 40,
407 * The number of background threads to use for parallel GC work.
409 * This parameter is read-only and is set based on the
410 * JSGC_HELPER_THREAD_RATIO and JSGC_MAX_HELPER_THREADS parameters.
412 JSGC_HELPER_THREAD_COUNT
= 41,
415 * If the percentage of the tenured strings exceeds this threshold, string
416 * will be allocated in tenured heap instead. (Default is allocated in
419 JSGC_PRETENURE_STRING_THRESHOLD
= 42,
422 * If the finalization rate of the tenured strings exceeds this threshold,
423 * string will be allocated in nursery.
425 JSGC_STOP_PRETENURE_STRING_THRESHOLD
= 43,
428 * A number that is incremented on every major GC slice.
430 JSGC_MAJOR_GC_NUMBER
= 44,
433 * A number that is incremented on every minor GC.
435 JSGC_MINOR_GC_NUMBER
= 45,
438 * JS::MaybeRunNurseryCollection will collect the nursery if it hasn't been
439 * collected in this many milliseconds.
444 JSGC_NURSERY_TIMEOUT_FOR_IDLE_COLLECTION_MS
= 46,
447 * The system page size in KB.
449 * This parameter is read-only.
451 JSGC_SYSTEM_PAGE_SIZE_KB
= 47,
454 * In an incremental GC, this determines the point at which to start
455 * increasing the slice budget and frequency of allocation triggered slices to
456 * try to avoid reaching the incremental limit and finishing the collection
459 * The threshold is calculated by subtracting this value from the heap's
462 JSGC_URGENT_THRESHOLD_MB
= 48,
465 * Set the number of threads to use for parallel marking, or zero to use the
468 * The actual number used is capped to the number of available helper threads.
470 * This is provided for testing purposes.
473 * Default: 0 (no effect).
475 JSGC_MARKING_THREAD_COUNT
= 49,
478 * The heap size above which to use parallel marking.
480 * Default: ParallelMarkingThresholdMB
482 JSGC_PARALLEL_MARKING_THRESHOLD_MB
= 50,
486 * Generic trace operation that calls JS::TraceEdge on each traceable thing's
487 * location reachable from data.
489 typedef void (*JSTraceDataOp
)(JSTracer
* trc
, void* data
);
492 * Trace hook used to trace gray roots incrementally.
494 * This should return whether tracing is finished. It will be called repeatedly
495 * in subsequent GC slices until it returns true.
497 * While tracing this should check the budget and return false if it has been
498 * exceeded. When passed an unlimited budget it should always return true.
500 typedef bool (*JSGrayRootsTracer
)(JSTracer
* trc
, js::SliceBudget
& budget
,
503 typedef enum JSGCStatus
{ JSGC_BEGIN
, JSGC_END
} JSGCStatus
;
505 typedef void (*JSObjectsTenuredCallback
)(JSContext
* cx
, void* data
);
507 typedef enum JSFinalizeStatus
{
509 * Called when preparing to sweep a group of zones, before anything has been
510 * swept. The collector will not yield to the mutator before calling the
511 * callback with JSFINALIZE_GROUP_START status.
513 JSFINALIZE_GROUP_PREPARE
,
516 * Called after preparing to sweep a group of zones. Weak references to
517 * unmarked things have been removed at this point, but no GC things have
518 * been swept. The collector may yield to the mutator after this point.
520 JSFINALIZE_GROUP_START
,
523 * Called after sweeping a group of zones. All dead GC things have been
524 * swept at this point.
526 JSFINALIZE_GROUP_END
,
529 * Called at the end of collection when everything has been swept.
531 JSFINALIZE_COLLECTION_END
534 typedef void (*JSFinalizeCallback
)(JS::GCContext
* gcx
, JSFinalizeStatus status
,
537 typedef void (*JSWeakPointerZonesCallback
)(JSTracer
* trc
, void* data
);
539 typedef void (*JSWeakPointerCompartmentCallback
)(JSTracer
* trc
,
540 JS::Compartment
* comp
,
544 * This is called to tell the embedding that a FinalizationRegistry object has
545 * cleanup work, and that the engine should be called back at an appropriate
546 * later time to perform this cleanup, by calling the function |doCleanup|.
548 * This callback must not do anything that could cause GC.
550 using JSHostCleanupFinalizationRegistryCallback
=
551 void (*)(JSFunction
* doCleanup
, JSObject
* incumbentGlobal
, void* data
);
554 * Each external string has a pointer to JSExternalStringCallbacks. Embedders
555 * can use this to implement custom finalization or memory reporting behavior.
557 struct JSExternalStringCallbacks
{
559 * Finalizes external strings created by JS_NewExternalString. The finalizer
560 * can be called off the main thread.
562 virtual void finalize(char16_t
* chars
) const = 0;
565 * Callback used by memory reporting to ask the embedder how much memory an
566 * external string is keeping alive. The embedder is expected to return a
567 * value that corresponds to the size of the allocation that will be released
568 * by the finalizer callback above.
570 * Implementations of this callback MUST NOT do anything that can cause GC.
572 virtual size_t sizeOfBuffer(const char16_t
* chars
,
573 mozilla::MallocSizeOf mallocSizeOf
) const = 0;
578 #define GCREASONS(D) \
579 /* Reasons internal to the JS engine. */ \
581 D(EAGER_ALLOC_TRIGGER, 1) \
582 D(DESTROY_RUNTIME, 2) \
583 D(ROOTS_REMOVED, 3) \
585 D(TOO_MUCH_MALLOC, 5) \
586 D(ALLOC_TRIGGER, 6) \
588 D(COMPARTMENT_REVIVED, 8) \
590 D(OUT_OF_NURSERY, 10) \
591 D(EVICT_NURSERY, 11) \
592 D(SHARED_MEMORY_LIMIT, 13) \
593 D(EAGER_NURSERY_COLLECTION, 14) \
594 D(BG_TASK_FINISHED, 15) \
596 D(FULL_WHOLE_CELL_BUFFER, 17) \
597 D(FULL_GENERIC_BUFFER, 18) \
598 D(FULL_VALUE_BUFFER, 19) \
599 D(FULL_CELL_PTR_OBJ_BUFFER, 20) \
600 D(FULL_SLOT_BUFFER, 21) \
601 D(FULL_SHAPE_BUFFER, 22) \
602 D(TOO_MUCH_WASM_MEMORY, 23) \
603 D(DISABLE_GENERATIONAL_GC, 24) \
605 D(PREPARE_FOR_TRACING, 26) \
606 D(FULL_WASM_ANYREF_BUFFER, 27) \
607 D(FULL_CELL_PTR_STR_BUFFER, 28) \
608 D(TOO_MUCH_JIT_CODE, 29) \
609 D(FULL_CELL_PTR_BIGINT_BUFFER, 30) \
610 D(NURSERY_TRAILERS, 31) \
611 D(NURSERY_MALLOC_BUFFERS, 32) \
614 * Reasons from Firefox. \
616 * The JS engine attaches special meanings to some of these reasons. \
618 D(DOM_WINDOW_UTILS, FIRST_FIREFOX_REASON) \
619 D(COMPONENT_UTILS, 34) \
620 D(MEM_PRESSURE, 35) \
626 D(NSJSCONTEXT_DESTROY, 41) \
627 D(WORKER_SHUTDOWN, 42) \
628 D(SET_DOC_SHELL, 43) \
632 D(INTER_SLICE_GC, 47) \
634 D(FULL_GC_TIMER, 49) \
637 D(USER_INACTIVE, 52) \
638 D(XPCONNECT_SHUTDOWN, 53) \
641 D(DOM_TESTUTILS, 56) \
643 /* Reasons reserved for embeddings. */ \
644 D(RESERVED1, FIRST_RESERVED_REASON) \
654 enum class GCReason
{
655 FIRST_FIREFOX_REASON
= 33,
656 FIRST_RESERVED_REASON
= 90,
658 #define MAKE_REASON(name, val) name = val,
659 GCREASONS(MAKE_REASON
)
665 * For telemetry, we want to keep a fixed max bucket size over time so we
666 * don't have to switch histograms. 100 is conservative; but the cost of extra
667 * buckets seems to be low while the cost of switching histograms is high.
669 NUM_TELEMETRY_REASONS
= 100
673 * Get a statically allocated C string explaining the given GC reason.
675 extern JS_PUBLIC_API
const char* ExplainGCReason(JS::GCReason reason
);
678 * Return true if the GC reason is internal to the JS engine.
680 extern JS_PUBLIC_API
bool InternalGCReason(JS::GCReason reason
);
685 * SpiderMonkey's GC is capable of performing a collection on an arbitrary
686 * subset of the zones in the system. This allows an embedding to minimize
687 * collection time by only collecting zones that have run code recently,
688 * ignoring the parts of the heap that are unlikely to have changed.
690 * When triggering a GC using one of the functions below, it is first necessary
691 * to select the zones to be collected. To do this, you can call
692 * PrepareZoneForGC on each zone, or you can call PrepareForFullGC to select
693 * all zones. Failing to select any zone is an error.
697 * Schedule the given zone to be collected as part of the next GC.
699 extern JS_PUBLIC_API
void PrepareZoneForGC(JSContext
* cx
, Zone
* zone
);
702 * Schedule all zones to be collected in the next GC.
704 extern JS_PUBLIC_API
void PrepareForFullGC(JSContext
* cx
);
707 * When performing an incremental GC, the zones that were selected for the
708 * previous incremental slice must be selected in subsequent slices as well.
709 * This function selects those slices automatically.
711 extern JS_PUBLIC_API
void PrepareForIncrementalGC(JSContext
* cx
);
714 * Returns true if any zone in the system has been scheduled for GC with one of
715 * the functions above or by the JS engine.
717 extern JS_PUBLIC_API
bool IsGCScheduled(JSContext
* cx
);
720 * Undoes the effect of the Prepare methods above. The given zone will not be
721 * collected in the next GC.
723 extern JS_PUBLIC_API
void SkipZoneForGC(JSContext
* cx
, Zone
* zone
);
726 * Non-Incremental GC:
728 * The following functions perform a non-incremental GC.
732 * Performs a non-incremental collection of all selected zones.
734 extern JS_PUBLIC_API
void NonIncrementalGC(JSContext
* cx
, JS::GCOptions options
,
740 * Incremental GC divides the full mark-and-sweep collection into multiple
741 * slices, allowing client JavaScript code to run between each slice. This
742 * allows interactive apps to avoid long collection pauses. Incremental GC does
743 * not make collection take less time, it merely spreads that time out so that
744 * the pauses are less noticable.
746 * For a collection to be carried out incrementally the following conditions
748 * - The collection must be run by calling JS::IncrementalGC() rather than
750 * - The GC parameter JSGC_INCREMENTAL_GC_ENABLED must be true.
752 * Note: Even if incremental GC is enabled and working correctly,
753 * non-incremental collections can still happen when low on memory.
757 * Begin an incremental collection and perform one slice worth of work. When
758 * this function returns, the collection may not be complete.
759 * IncrementalGCSlice() must be called repeatedly until
760 * !IsIncrementalGCInProgress(cx).
762 * Note: SpiderMonkey's GC is not realtime. Slices in practice may be longer or
763 * shorter than the requested interval.
765 extern JS_PUBLIC_API
void StartIncrementalGC(JSContext
* cx
,
766 JS::GCOptions options
,
768 const js::SliceBudget
& budget
);
771 * Perform a slice of an ongoing incremental collection. When this function
772 * returns, the collection may not be complete. It must be called repeatedly
773 * until !IsIncrementalGCInProgress(cx).
775 * Note: SpiderMonkey's GC is not realtime. Slices in practice may be longer or
776 * shorter than the requested interval.
778 extern JS_PUBLIC_API
void IncrementalGCSlice(JSContext
* cx
, GCReason reason
,
779 const js::SliceBudget
& budget
);
782 * Return whether an incremental GC has work to do on the foreground thread and
783 * would make progress if a slice was run now. If this returns false then the GC
784 * is waiting for background threads to finish their work and a slice started
785 * now would return immediately.
787 extern JS_PUBLIC_API
bool IncrementalGCHasForegroundWork(JSContext
* cx
);
790 * If IsIncrementalGCInProgress(cx), this call finishes the ongoing collection
791 * by performing an arbitrarily long slice. If !IsIncrementalGCInProgress(cx),
792 * this is equivalent to NonIncrementalGC. When this function returns,
793 * IsIncrementalGCInProgress(cx) will always be false.
795 extern JS_PUBLIC_API
void FinishIncrementalGC(JSContext
* cx
, GCReason reason
);
798 * If IsIncrementalGCInProgress(cx), this call aborts the ongoing collection and
799 * performs whatever work needs to be done to return the collector to its idle
800 * state. This may take an arbitrarily long time. When this function returns,
801 * IsIncrementalGCInProgress(cx) will always be false.
803 extern JS_PUBLIC_API
void AbortIncrementalGC(JSContext
* cx
);
807 // The `JS::dbg::GarbageCollectionEvent` class is essentially a view of the
808 // `js::gcstats::Statistics` data without the uber implementation-specific bits.
809 // It should generally be palatable for web developers.
810 class GarbageCollectionEvent
{
811 // The major GC number of the GC cycle this data pertains to.
812 uint64_t majorGCNumber_
;
814 // Reference to a non-owned, statically allocated C string. This is a very
815 // short reason explaining why a GC was triggered.
818 // Reference to a nullable, non-owned, statically allocated C string. If the
819 // collection was forced to be non-incremental, this is a short reason of
820 // why the GC could not perform an incremental collection.
821 const char* nonincrementalReason
;
823 // Represents a single slice of a possibly multi-slice incremental garbage
826 mozilla::TimeStamp startTimestamp
;
827 mozilla::TimeStamp endTimestamp
;
830 // The set of garbage collection slices that made up this GC cycle.
831 mozilla::Vector
<Collection
> collections
;
833 GarbageCollectionEvent(const GarbageCollectionEvent
& rhs
) = delete;
834 GarbageCollectionEvent
& operator=(const GarbageCollectionEvent
& rhs
) = delete;
837 explicit GarbageCollectionEvent(uint64_t majorGCNum
)
838 : majorGCNumber_(majorGCNum
),
840 nonincrementalReason(nullptr),
843 using Ptr
= js::UniquePtr
<GarbageCollectionEvent
>;
844 static Ptr
Create(JSRuntime
* rt
, ::js::gcstats::Statistics
& stats
,
845 uint64_t majorGCNumber
);
847 JSObject
* toJSObject(JSContext
* cx
) const;
849 uint64_t majorGCNumber() const { return majorGCNumber_
; }
856 * During GC, the GC is bracketed by GC_CYCLE_BEGIN/END callbacks. Each
857 * slice between those (whether an incremental or the sole non-incremental
858 * slice) is bracketed by GC_SLICE_BEGIN/GC_SLICE_END.
867 struct JS_PUBLIC_API GCDescription
{
870 JS::GCOptions options_
;
873 GCDescription(bool isZone
, bool isComplete
, JS::GCOptions options
,
876 isComplete_(isComplete
),
880 char16_t
* formatSliceMessage(JSContext
* cx
) const;
881 char16_t
* formatSummaryMessage(JSContext
* cx
) const;
883 mozilla::TimeStamp
startTime(JSContext
* cx
) const;
884 mozilla::TimeStamp
endTime(JSContext
* cx
) const;
885 mozilla::TimeStamp
lastSliceStart(JSContext
* cx
) const;
886 mozilla::TimeStamp
lastSliceEnd(JSContext
* cx
) const;
888 JS::UniqueChars
sliceToJSONProfiler(JSContext
* cx
) const;
889 JS::UniqueChars
formatJSONProfiler(JSContext
* cx
) const;
891 JS::dbg::GarbageCollectionEvent::Ptr
toGCEvent(JSContext
* cx
) const;
894 extern JS_PUBLIC_API UniqueChars
MinorGcToJSON(JSContext
* cx
);
896 typedef void (*GCSliceCallback
)(JSContext
* cx
, GCProgress progress
,
897 const GCDescription
& desc
);
900 * The GC slice callback is called at the beginning and end of each slice. This
901 * callback may be used for GC notifications as well as to perform additional
904 extern JS_PUBLIC_API GCSliceCallback
905 SetGCSliceCallback(JSContext
* cx
, GCSliceCallback callback
);
908 * Describes the progress of an observed nursery collection.
910 enum class GCNurseryProgress
{
912 * The nursery collection is starting.
914 GC_NURSERY_COLLECTION_START
,
916 * The nursery collection is ending.
918 GC_NURSERY_COLLECTION_END
922 * A nursery collection callback receives the progress of the nursery collection
923 * and the reason for the collection.
925 using GCNurseryCollectionCallback
= void (*)(JSContext
* cx
,
926 GCNurseryProgress progress
,
927 GCReason reason
, void* data
);
930 * Add and remove nursery collection callbacks for the given runtime. These will
931 * be called at the start and end of every nursery collection.
933 extern JS_PUBLIC_API
bool AddGCNurseryCollectionCallback(
934 JSContext
* cx
, GCNurseryCollectionCallback callback
, void* data
);
935 extern JS_PUBLIC_API
void RemoveGCNurseryCollectionCallback(
936 JSContext
* cx
, GCNurseryCollectionCallback callback
, void* data
);
938 typedef void (*DoCycleCollectionCallback
)(JSContext
* cx
);
941 * The purge gray callback is called after any COMPARTMENT_REVIVED GC in which
942 * the majority of compartments have been marked gray.
944 extern JS_PUBLIC_API DoCycleCollectionCallback
945 SetDoCycleCollectionCallback(JSContext
* cx
, DoCycleCollectionCallback callback
);
947 using CreateSliceBudgetCallback
= js::SliceBudget (*)(JS::GCReason reason
,
951 * Called when generating a GC slice budget. It allows the embedding to control
952 * the duration of slices and potentially check an interrupt flag as well. For
953 * internally triggered GCs, the given millis parameter is the JS engine's
954 * internal scheduling decision, which the embedding can choose to ignore.
955 * (Otherwise, it will be the value that was passed to eg
956 * JS::IncrementalGCSlice()).
958 extern JS_PUBLIC_API
void SetCreateGCSliceBudgetCallback(
959 JSContext
* cx
, CreateSliceBudgetCallback cb
);
962 * Incremental GC defaults to enabled, but may be disabled for testing or in
963 * embeddings that have not yet implemented barriers on their native classes.
964 * There is not currently a way to re-enable incremental GC once it has been
965 * disabled on the runtime.
967 extern JS_PUBLIC_API
void DisableIncrementalGC(JSContext
* cx
);
970 * Returns true if incremental GC is enabled. Simply having incremental GC
971 * enabled is not sufficient to ensure incremental collections are happening.
972 * See the comment "Incremental GC" above for reasons why incremental GC may be
973 * suppressed. Inspection of the "nonincremental reason" field of the
974 * GCDescription returned by GCSliceCallback may help narrow down the cause if
975 * collections are not happening incrementally when expected.
977 extern JS_PUBLIC_API
bool IsIncrementalGCEnabled(JSContext
* cx
);
980 * Returns true while an incremental GC is ongoing, both when actively
981 * collecting and between slices.
983 extern JS_PUBLIC_API
bool IsIncrementalGCInProgress(JSContext
* cx
);
986 * Returns true while an incremental GC is ongoing, both when actively
987 * collecting and between slices.
989 extern JS_PUBLIC_API
bool IsIncrementalGCInProgress(JSRuntime
* rt
);
992 * Returns true if the most recent GC ran incrementally.
994 extern JS_PUBLIC_API
bool WasIncrementalGC(JSRuntime
* rt
);
1001 * Ensure that generational GC is disabled within some scope.
1003 * This evicts the nursery and discards JIT code so it is not a lightweight
1006 class JS_PUBLIC_API AutoDisableGenerationalGC
{
1010 explicit AutoDisableGenerationalGC(JSContext
* cx
);
1011 ~AutoDisableGenerationalGC();
1015 * Returns true if generational allocation and collection is currently enabled
1016 * on the given runtime.
1018 extern JS_PUBLIC_API
bool IsGenerationalGCEnabled(JSRuntime
* rt
);
1021 * Enable or disable support for pretenuring allocations based on their
1024 extern JS_PUBLIC_API
void SetSiteBasedPretenuringEnabled(bool enable
);
1027 * Pass a subclass of this "abstract" class to callees to require that they
1028 * never GC. Subclasses can use assertions or the hazard analysis to ensure no
1031 class JS_PUBLIC_API AutoRequireNoGC
{
1033 AutoRequireNoGC() = default;
1034 ~AutoRequireNoGC() = default;
1038 * Diagnostic assert (see MOZ_DIAGNOSTIC_ASSERT) that GC cannot occur while this
1039 * class is live. This class does not disable the static rooting hazard
1042 * This works by entering a GC unsafe region, which is checked on allocation and
1045 class JS_PUBLIC_API AutoAssertNoGC
: public AutoRequireNoGC
{
1046 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
1048 JSContext
* cx_
; // nullptr if inactive.
1051 // Nullptr here means get the context from TLS. It does not mean inactive
1052 // (though cx_ may end up nullptr, and thus inactive, if TLS has not yet been
1054 explicit AutoAssertNoGC(JSContext
* cx
= nullptr);
1055 AutoAssertNoGC(AutoAssertNoGC
&& other
) : cx_(other
.cx_
) {
1056 other
.cx_
= nullptr;
1063 explicit AutoAssertNoGC(JSContext
* cx
= nullptr) {}
1064 ~AutoAssertNoGC() {}
1071 * Disable the static rooting hazard analysis in the live region and assert in
1072 * debug builds if any allocation that could potentially trigger a GC occurs
1073 * while this guard object is live. This is most useful to help the exact
1074 * rooting hazard analysis in complex regions, since it cannot understand
1077 * Note: GC behavior is unpredictable even when deterministic and is generally
1078 * non-deterministic in practice. The fact that this guard has not
1079 * asserted is not a guarantee that a GC cannot happen in the guarded
1080 * region. As a rule, anyone performing a GC unsafe action should
1081 * understand the GC properties of all code in that region and ensure
1082 * that the hazard analysis is correct for that code, rather than relying
1086 class JS_PUBLIC_API AutoSuppressGCAnalysis
: public AutoAssertNoGC
{
1088 explicit AutoSuppressGCAnalysis(JSContext
* cx
= nullptr)
1089 : AutoAssertNoGC(cx
) {}
1090 } JS_HAZ_GC_SUPPRESSED
;
1092 class JS_PUBLIC_API AutoSuppressGCAnalysis
: public AutoRequireNoGC
{
1094 explicit AutoSuppressGCAnalysis(JSContext
* cx
= nullptr) {}
1095 } JS_HAZ_GC_SUPPRESSED
;
1099 * Assert that code is only ever called from a GC callback, disable the static
1100 * rooting hazard analysis and assert if any allocation that could potentially
1101 * trigger a GC occurs while this guard object is live.
1103 * This is useful to make the static analysis ignore code that runs in GC
1106 class JS_PUBLIC_API AutoAssertGCCallback
: public AutoSuppressGCAnalysis
{
1109 AutoAssertGCCallback();
1111 AutoAssertGCCallback() {}
1116 * Place AutoCheckCannotGC in scopes that you believe can never GC. These
1117 * annotations will be verified both dynamically via AutoAssertNoGC, and
1118 * statically with the rooting hazard analysis (implemented by making the
1119 * analysis consider AutoCheckCannotGC to be a GC pointer, and therefore
1120 * complain if it is live across a GC call.) It is useful when dealing with
1121 * internal pointers to GC things where the GC thing itself may not be present
1122 * for the static analysis: e.g. acquiring inline chars from a JSString* on the
1125 * We only do the assertion checking in DEBUG builds.
1128 class JS_PUBLIC_API AutoCheckCannotGC
: public AutoAssertNoGC
{
1130 explicit AutoCheckCannotGC(JSContext
* cx
= nullptr) : AutoAssertNoGC(cx
) {}
1131 # ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
1132 AutoCheckCannotGC(const AutoCheckCannotGC
& other
)
1133 : AutoCheckCannotGC(other
.cx_
) {}
1135 AutoCheckCannotGC(const AutoCheckCannotGC
& other
) : AutoCheckCannotGC() {}
1137 AutoCheckCannotGC(AutoCheckCannotGC
&& other
)
1138 : AutoAssertNoGC(std::forward
<AutoAssertNoGC
>(other
)) {}
1140 class JS_PUBLIC_API AutoCheckCannotGC
: public AutoRequireNoGC
{
1142 explicit AutoCheckCannotGC(JSContext
* cx
= nullptr) {}
1143 AutoCheckCannotGC(const AutoCheckCannotGC
& other
) : AutoCheckCannotGC() {}
1144 AutoCheckCannotGC(AutoCheckCannotGC
&& other
) : AutoCheckCannotGC() {}
1147 } JS_HAZ_GC_INVALIDATED JS_HAZ_GC_REF
;
1149 extern JS_PUBLIC_API
void SetLowMemoryState(JSContext
* cx
, bool newState
);
1152 * Internal to Firefox.
1154 extern JS_PUBLIC_API
void NotifyGCRootsRemoved(JSContext
* cx
);
1156 } /* namespace JS */
1158 typedef void (*JSGCCallback
)(JSContext
* cx
, JSGCStatus status
,
1159 JS::GCReason reason
, void* data
);
1162 * Register externally maintained GC roots.
1164 * traceOp: the trace operation. For each root the implementation should call
1165 * JS::TraceEdge whenever the root contains a traceable thing.
1166 * data: the data argument to pass to each invocation of traceOp.
1168 extern JS_PUBLIC_API
bool JS_AddExtraGCRootsTracer(JSContext
* cx
,
1169 JSTraceDataOp traceOp
,
1172 /** Undo a call to JS_AddExtraGCRootsTracer. */
1173 extern JS_PUBLIC_API
void JS_RemoveExtraGCRootsTracer(JSContext
* cx
,
1174 JSTraceDataOp traceOp
,
1177 extern JS_PUBLIC_API
void JS_GC(JSContext
* cx
,
1178 JS::GCReason reason
= JS::GCReason::API
);
1180 extern JS_PUBLIC_API
void JS_MaybeGC(JSContext
* cx
);
1182 extern JS_PUBLIC_API
void JS_SetGCCallback(JSContext
* cx
, JSGCCallback cb
,
1185 extern JS_PUBLIC_API
void JS_SetObjectsTenuredCallback(
1186 JSContext
* cx
, JSObjectsTenuredCallback cb
, void* data
);
1188 extern JS_PUBLIC_API
bool JS_AddFinalizeCallback(JSContext
* cx
,
1189 JSFinalizeCallback cb
,
1192 extern JS_PUBLIC_API
void JS_RemoveFinalizeCallback(JSContext
* cx
,
1193 JSFinalizeCallback cb
);
1196 * Weak pointers and garbage collection
1198 * Weak pointers are by their nature not marked as part of garbage collection,
1199 * but they may need to be updated in two cases after a GC:
1201 * 1) Their referent was found not to be live and is about to be finalized
1202 * 2) Their referent has been moved by a compacting GC
1204 * To handle this, any part of the system that maintain weak pointers to
1205 * JavaScript GC things must register a callback with
1206 * JS_(Add,Remove)WeakPointer{ZoneGroup,Compartment}Callback(). This callback
1207 * must then call JS_UpdateWeakPointerAfterGC() on all weak pointers it knows
1210 * Since sweeping is incremental, we have several callbacks to avoid repeatedly
1211 * having to visit all embedder structures. The WeakPointerZonesCallback is
1212 * called once for each strongly connected group of zones, whereas the
1213 * WeakPointerCompartmentCallback is called once for each compartment that is
1214 * visited while sweeping. Structures that cannot contain references in more
1215 * than one compartment should sweep the relevant per-compartment structures
1216 * using the latter callback to minimizer per-slice overhead.
1218 * The argument to JS_UpdateWeakPointerAfterGC() is an in-out param. If the
1219 * referent is about to be finalized the pointer will be set to null. If the
1220 * referent has been moved then the pointer will be updated to point to the new
1223 * The return value of JS_UpdateWeakPointerAfterGC() indicates whether the
1224 * referent is still alive. If the referent is is about to be finalized, this
1225 * will return false.
1227 * Callers of this method are responsible for updating any state that is
1228 * dependent on the object's address. For example, if the object's address is
1229 * used as a key in a hashtable, then the object must be removed and
1230 * re-inserted with the correct hash.
1233 extern JS_PUBLIC_API
bool JS_AddWeakPointerZonesCallback(
1234 JSContext
* cx
, JSWeakPointerZonesCallback cb
, void* data
);
1236 extern JS_PUBLIC_API
void JS_RemoveWeakPointerZonesCallback(
1237 JSContext
* cx
, JSWeakPointerZonesCallback cb
);
1239 extern JS_PUBLIC_API
bool JS_AddWeakPointerCompartmentCallback(
1240 JSContext
* cx
, JSWeakPointerCompartmentCallback cb
, void* data
);
1242 extern JS_PUBLIC_API
void JS_RemoveWeakPointerCompartmentCallback(
1243 JSContext
* cx
, JSWeakPointerCompartmentCallback cb
);
1246 template <typename T
>
1250 extern JS_PUBLIC_API
bool JS_UpdateWeakPointerAfterGC(
1251 JSTracer
* trc
, JS::Heap
<JSObject
*>* objp
);
1253 extern JS_PUBLIC_API
bool JS_UpdateWeakPointerAfterGCUnbarriered(
1254 JSTracer
* trc
, JSObject
** objp
);
1256 extern JS_PUBLIC_API
void JS_SetGCParameter(JSContext
* cx
, JSGCParamKey key
,
1259 extern JS_PUBLIC_API
void JS_ResetGCParameter(JSContext
* cx
, JSGCParamKey key
);
1261 extern JS_PUBLIC_API
uint32_t JS_GetGCParameter(JSContext
* cx
,
1264 extern JS_PUBLIC_API
void JS_SetGCParametersBasedOnAvailableMemory(
1265 JSContext
* cx
, uint32_t availMemMB
);
1268 * Create a new JSString whose chars member refers to external memory, i.e.,
1269 * memory requiring application-specific finalization.
1271 extern JS_PUBLIC_API JSString
* JS_NewExternalString(
1272 JSContext
* cx
, const char16_t
* chars
, size_t length
,
1273 const JSExternalStringCallbacks
* callbacks
);
1276 * Create a new JSString whose chars member may refer to external memory.
1277 * If a new external string is allocated, |*allocatedExternal| is set to true.
1278 * Otherwise the returned string is either not an external string or an
1279 * external string allocated by a previous call and |*allocatedExternal| is set
1280 * to false. If |*allocatedExternal| is false, |fin| won't be called.
1282 extern JS_PUBLIC_API JSString
* JS_NewMaybeExternalString(
1283 JSContext
* cx
, const char16_t
* chars
, size_t length
,
1284 const JSExternalStringCallbacks
* callbacks
, bool* allocatedExternal
);
1287 * Return the 'callbacks' arg passed to JS_NewExternalString or
1288 * JS_NewMaybeExternalString.
1290 extern JS_PUBLIC_API
const JSExternalStringCallbacks
*
1291 JS_GetExternalStringCallbacks(JSString
* str
);
1295 extern JS_PUBLIC_API GCReason
WantEagerMinorGC(JSRuntime
* rt
);
1297 extern JS_PUBLIC_API GCReason
WantEagerMajorGC(JSRuntime
* rt
);
1299 extern JS_PUBLIC_API
void MaybeRunNurseryCollection(JSRuntime
* rt
,
1300 JS::GCReason reason
);
1302 extern JS_PUBLIC_API
void SetHostCleanupFinalizationRegistryCallback(
1303 JSContext
* cx
, JSHostCleanupFinalizationRegistryCallback cb
, void* data
);
1306 * Clear kept alive objects in JS WeakRef.
1307 * https://tc39.es/proposal-weakrefs/#sec-clear-kept-objects
1309 extern JS_PUBLIC_API
void ClearKeptObjects(JSContext
* cx
);
1311 inline JS_PUBLIC_API
bool NeedGrayRootsForZone(Zone
* zoneArg
) {
1312 shadow::Zone
* zone
= shadow::Zone::from(zoneArg
);
1313 return zone
->isGCMarkingBlackAndGray() || zone
->isGCCompacting();
1316 extern JS_PUBLIC_API
bool AtomsZoneIsCollecting(JSRuntime
* runtime
);
1317 extern JS_PUBLIC_API
bool IsAtomsZone(Zone
* zone
);
1325 * Create an object providing access to the garbage collector's internal notion
1326 * of the current state of memory (both GC heap memory and GCthing-controlled
1329 extern JS_PUBLIC_API JSObject
* NewMemoryInfoObject(JSContext
* cx
);
1332 * Run the finalizer of a nursery-allocated JSObject that is known to be dead.
1334 * This is a dangerous operation - only use this if you know what you're doing!
1336 * This is used by the browser to implement nursery-allocated wrapper cached
1339 extern JS_PUBLIC_API
void FinalizeDeadNurseryObject(JSContext
* cx
,
1342 } /* namespace gc */
1343 } /* namespace js */
1347 # define JS_DEFAULT_ZEAL_FREQ 100
1349 extern JS_PUBLIC_API
void JS_GetGCZealBits(JSContext
* cx
, uint32_t* zealBits
,
1350 uint32_t* frequency
,
1351 uint32_t* nextScheduled
);
1353 extern JS_PUBLIC_API
void JS_SetGCZeal(JSContext
* cx
, uint8_t zeal
,
1354 uint32_t frequency
);
1356 extern JS_PUBLIC_API
void JS_UnsetGCZeal(JSContext
* cx
, uint8_t zeal
);
1358 extern JS_PUBLIC_API
void JS_ScheduleGC(JSContext
* cx
, uint32_t count
);
1362 #endif /* js_GCAPI_h */