Debian Codegraph @

js/public/GCAPI.h

raw
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/. */
6
7 /*
8 * High-level interface to the JS garbage collector.
9 */
10
11 #ifndef js_GCAPI_h
12 #define js_GCAPI_h
13
14 #include "mozilla/TimeStamp.h"
15 #include "mozilla/Vector.h"
16
17 #include "js/CharacterEncoding.h" // JS::UTF8Chars
18 #include "js/GCAnnotations.h"
19 #include "js/shadow/Zone.h"
20 #include "js/SliceBudget.h"
21 #include "js/TypeDecls.h"
22 #include "js/UniquePtr.h"
23 #include "js/Utility.h"
24
25 class JS_PUBLIC_API JSTracer;
26
27 namespace js {
28 namespace gc {
29 class GCRuntime;
30 } // namespace gc
31 namespace gcstats {
32 struct Statistics;
33 } // namespace gcstats
34 } // namespace js
35
36 namespace JS {
37
38 class JS_PUBLIC_API SliceBudget;
39
40 // Options used when starting a GC.
41 enum class GCOptions : uint32_t {
42 // Normal GC invocation.
43 //
44 // Some objects that are unreachable from the program may still be alive after
45 // collection because of internal references
46 Normal = 0,
47
48 // A shrinking GC.
49 //
50 // Try to release as much memory as possible by clearing internal caches,
51 // aggressively discarding JIT code and decommitting unused chunks. This
52 // ensures all unreferenced objects are removed from the system.
53 //
54 // Finally, compact the GC heap.
55 Shrink = 1,
56
57 // A shutdown GC.
58 //
59 // This does more drastic cleanup as part of system shutdown, including:
60 // - clearing WeakRef kept object sets
61 // - not marking FinalizationRegistry roots
62 // - repeating collection if JS::NotifyGCRootsRemoved was called
63 // - skipping scheduling of various future work that won't be needed
64 //
65 // Note that this assumes that no JS will run after this point!
66 Shutdown = 2
67 };
68
69 } // namespace JS
70
71 typedef enum JSGCParamKey {
72 /**
73 * Maximum nominal heap before last ditch GC.
74 *
75 * Soft limit on the number of bytes we are allowed to allocate in the GC
76 * heap. Attempts to allocate gcthings over this limit will return null and
77 * subsequently invoke the standard OOM machinery, independent of available
78 * physical memory.
79 *
80 * Pref: javascript.options.mem.max
81 * Default: 0xffffffff
82 */
83 JSGC_MAX_BYTES = 0,
84
85 /**
86 * Maximum size of the generational GC nurseries.
87 *
88 * This will be rounded to the nearest gc::ChunkSize.
89 *
90 * Pref: javascript.options.mem.nursery.max_kb
91 * Default: JS::DefaultNurseryMaxBytes
92 */
93 JSGC_MAX_NURSERY_BYTES = 2,
94
95 /** Amount of bytes allocated by the GC. */
96 JSGC_BYTES = 3,
97
98 /** Number of times GC has been invoked. Includes both major and minor GC. */
99 JSGC_NUMBER = 4,
100
101 /**
102 * Whether incremental GC is enabled. If not, GC will always run to
103 * completion.
104 *
105 * prefs: javascript.options.mem.gc_incremental.
106 * Default: false
107 */
108 JSGC_INCREMENTAL_GC_ENABLED = 5,
109
110 /**
111 * Whether per-zone GC is enabled. If not, all zones are collected every time.
112 *
113 * prefs: javascript.options.mem.gc_per_zone
114 * Default: false
115 */
116 JSGC_PER_ZONE_GC_ENABLED = 6,
117
118 /** Number of cached empty GC chunks. */
119 JSGC_UNUSED_CHUNKS = 7,
120
121 /** Total number of allocated GC chunks. */
122 JSGC_TOTAL_CHUNKS = 8,
123
124 /**
125 * Max milliseconds to spend in an incremental GC slice.
126 *
127 * A value of zero means there is no maximum.
128 *
129 * Pref: javascript.options.mem.gc_incremental_slice_ms
130 * Default: DefaultTimeBudgetMS.
131 */
132 JSGC_SLICE_TIME_BUDGET_MS = 9,
133
134 /**
135 * The "do we collect?" decision depends on various parameters and can be
136 * summarised as:
137 *
138 * ZoneSize > Max(ThresholdBase, LastSize) * GrowthFactor * ThresholdFactor
139 *
140 * Where
141 * ZoneSize: Current size of this zone.
142 * LastSize: Heap size immediately after the most recent collection.
143 * ThresholdBase: The JSGC_ALLOCATION_THRESHOLD parameter
144 * GrowthFactor: A number above 1, calculated based on some of the
145 * following parameters.
146 * See computeZoneHeapGrowthFactorForHeapSize() in GC.cpp
147 * ThresholdFactor: 1.0 to trigger an incremental collections or between
148 * JSGC_SMALL_HEAP_INCREMENTAL_LIMIT and
149 * JSGC_LARGE_HEAP_INCREMENTAL_LIMIT to trigger a
150 * non-incremental collection.
151 *
152 * The RHS of the equation above is calculated and sets
153 * zone->gcHeapThreshold.bytes(). When gcHeapSize.bytes() exeeds
154 * gcHeapThreshold.bytes() for a zone, the zone may be scheduled for a GC.
155 */
156
157 /**
158 * GCs less than this far apart in milliseconds will be considered
159 * 'high-frequency GCs'.
160 *
161 * Pref: javascript.options.mem.gc_high_frequency_time_limit_ms
162 * Default: HighFrequencyThreshold
163 */
164 JSGC_HIGH_FREQUENCY_TIME_LIMIT = 11,
165
166 /**
167 * Upper limit for classifying a heap as small (MB).
168 *
169 * Dynamic heap growth thresholds are based on whether the heap is small,
170 * medium or large. Heaps smaller than this size are classified as small;
171 * larger heaps are classified as medium or large.
172 *
173 * Pref: javascript.options.mem.gc_small_heap_size_max_mb
174 * Default: SmallHeapSizeMaxBytes
175 */
176 JSGC_SMALL_HEAP_SIZE_MAX = 12,
177
178 /**
179 * Lower limit for classifying a heap as large (MB).
180 *
181 * Dynamic heap growth thresholds are based on whether the heap is small,
182 * medium or large. Heaps larger than this size are classified as large;
183 * smaller heaps are classified as small or medium.
184 *
185 * Pref: javascript.options.mem.gc_large_heap_size_min_mb
186 * Default: LargeHeapSizeMinBytes
187 */
188 JSGC_LARGE_HEAP_SIZE_MIN = 13,
189
190 /**
191 * Heap growth factor for small heaps in the high-frequency GC state.
192 *
193 * Pref: javascript.options.mem.gc_high_frequency_small_heap_growth
194 * Default: HighFrequencySmallHeapGrowth
195 */
196 JSGC_HIGH_FREQUENCY_SMALL_HEAP_GROWTH = 14,
197
198 /**
199 * Heap growth factor for large heaps in the high-frequency GC state.
200 *
201 * Pref: javascript.options.mem.gc_high_frequency_large_heap_growth
202 * Default: HighFrequencyLargeHeapGrowth
203 */
204 JSGC_HIGH_FREQUENCY_LARGE_HEAP_GROWTH = 15,
205
206 /**
207 * Heap growth factor for low frequency GCs.
208 *
209 * This factor is applied regardless of the size of the heap when not in the
210 * high-frequency GC state.
211 *
212 * Pref: javascript.options.mem.gc_low_frequency_heap_growth
213 * Default: LowFrequencyHeapGrowth
214 */
215 JSGC_LOW_FREQUENCY_HEAP_GROWTH = 16,
216
217 /**
218 * Whether balanced heap limits are enabled.
219 *
220 * If this is set to true then heap limits are calculated in a way designed to
221 * balance memory usage optimally between many heaps.
222 *
223 * Otherwise, heap limits are set based on a linear multiple of the retained
224 * size after the last collection.
225 *
226 * Pref: javascript.options.mem.gc_balanced_heap_limits
227 * Default: BalancedHeapLimitsEnabled
228 */
229 JSGC_BALANCED_HEAP_LIMITS_ENABLED = 17,
230
231 /**
232 * Heap growth parameter for balanced heap limit calculation.
233 *
234 * This parameter trades off GC time for memory usage. Smaller values result
235 * in lower memory use and larger values result in less time spent collecting.
236 *
237 * Heap limits are set to the heap's retained size plus some extra space. The
238 * extra space is calculated based on several factors but is scaled
239 * proportionally to this parameter.
240 *
241 * Pref: javascript.options.mem.gc_heap_growth_factor
242 * Default: HeapGrowthFactor
243 */
244 JSGC_HEAP_GROWTH_FACTOR = 18,
245
246 /**
247 * Lower limit for collecting a zone (MB).
248 *
249 * Zones smaller than this size will not normally be collected.
250 *
251 * Pref: javascript.options.mem.gc_allocation_threshold_mb
252 * Default GCZoneAllocThresholdBase
253 */
254 JSGC_ALLOCATION_THRESHOLD = 19,
255
256 /**
257 * We try to keep at least this many unused chunks in the free chunk pool at
258 * all times, even after a shrinking GC.
259 *
260 * Pref: javascript.options.mem.gc_min_empty_chunk_count
261 * Default: MinEmptyChunkCount
262 */
263 JSGC_MIN_EMPTY_CHUNK_COUNT = 21,
264
265 /**
266 * Whether compacting GC is enabled.
267 *
268 * Pref: javascript.options.mem.gc_compacting
269 * Default: CompactingEnabled
270 */
271 JSGC_COMPACTING_ENABLED = 23,
272
273 /**
274 * Whether parallel marking is enabled.
275 *
276 * Pref: javascript.options.mem.gc_parallel_marking
277 * Default: ParallelMarkingEnabled
278 */
279 JSGC_PARALLEL_MARKING_ENABLED = 24,
280
281 /**
282 * Limit of how far over the incremental trigger threshold we allow the heap
283 * to grow before finishing a collection non-incrementally, for small heaps.
284 *
285 * We trigger an incremental GC when a trigger threshold is reached but the
286 * collection may not be fast enough to keep up with the mutator. At some
287 * point we finish the collection non-incrementally.
288 *
289 * Default: SmallHeapIncrementalLimit
290 * Pref: javascript.options.mem.gc_small_heap_incremental_limit
291 */
292 JSGC_SMALL_HEAP_INCREMENTAL_LIMIT = 25,
293
294 /**
295 * Limit of how far over the incremental trigger threshold we allow the heap
296 * to grow before finishing a collection non-incrementally, for large heaps.
297 *
298 * Default: LargeHeapIncrementalLimit
299 * Pref: javascript.options.mem.gc_large_heap_incremental_limit
300 */
301 JSGC_LARGE_HEAP_INCREMENTAL_LIMIT = 26,
302
303 /**
304 * Free space bytes threshold for eager nursery collection.
305 *
306 * Default: NurseryChunkUsableSize / 4
307 * Pref: javascript.options.mem.nursery_eager_collection_threshold_kb
308 */
309 JSGC_NURSERY_EAGER_COLLECTION_THRESHOLD_KB = 27,
310
311 /**
312 * Free space fraction threshold for eager nursery collection. This is a
313 * percentage (from 0 to 99).
314 *
315 * Default: 25
316 * Pref: javascript.options.mem.nursery_eager_collection_threshold_percent
317 */
318 JSGC_NURSERY_EAGER_COLLECTION_THRESHOLD_PERCENT = 30,
319
320 /**
321 * Minimum size of the generational GC nurseries.
322 *
323 * This value will be rounded to the nearest Nursery::SubChunkStep if below
324 * gc::ChunkSize, otherwise it'll be rounded to the nearest gc::ChunkSize.
325 *
326 * Default: Nursery::SubChunkLimit
327 * Pref: javascript.options.mem.nursery.min_kb
328 */
329 JSGC_MIN_NURSERY_BYTES = 31,
330
331 /**
332 * The minimum time to allow between triggering last ditch GCs in seconds.
333 *
334 * Default: 60 seconds
335 * Pref: None
336 */
337 JSGC_MIN_LAST_DITCH_GC_PERIOD = 32,
338
339 /**
340 * The delay (in heapsize kilobytes) between slices of an incremental GC.
341 *
342 * Default: ZoneAllocDelayBytes
343 */
344 JSGC_ZONE_ALLOC_DELAY_KB = 33,
345
346 /*
347 * The current size of the nursery.
348 *
349 * This parameter is read-only.
350 */
351 JSGC_NURSERY_BYTES = 34,
352
353 /**
354 * Retained size base value for calculating malloc heap threshold.
355 *
356 * Default: MallocThresholdBase
357 */
358 JSGC_MALLOC_THRESHOLD_BASE = 35,
359
360 /**
361 * Whether incremental weakmap marking is enabled.
362 *
363 * Pref: javascript.options.mem.incremental_weakmap
364 * Default: IncrementalWeakMarkEnabled
365 */
366 JSGC_INCREMENTAL_WEAKMAP_ENABLED = 37,
367
368 /**
369 * The chunk size in bytes for this system.
370 *
371 * This parameter is read-only.
372 */
373 JSGC_CHUNK_BYTES = 38,
374
375 /**
376 * The number of background threads to use for parallel GC work for each CPU
377 * core, expressed as an integer percentage.
378 *
379 * Pref: javascript.options.mem.gc_helper_thread_ratio
380 */
381 JSGC_HELPER_THREAD_RATIO = 39,
382
383 /**
384 * The maximum number of background threads to use for parallel GC work.
385 *
386 * Pref: javascript.options.mem.gc_max_helper_threads
387 */
388 JSGC_MAX_HELPER_THREADS = 40,
389
390 /**
391 * The number of background threads to use for parallel GC work.
392 *
393 * This parameter is read-only and is set based on the
394 * JSGC_HELPER_THREAD_RATIO and JSGC_MAX_HELPER_THREADS parameters.
395 */
396 JSGC_HELPER_THREAD_COUNT = 41,
397
398 /**
399 * A number that is incremented on every major GC slice.
400 */
401 JSGC_MAJOR_GC_NUMBER = 44,
402
403 /**
404 * A number that is incremented on every minor GC.
405 */
406 JSGC_MINOR_GC_NUMBER = 45,
407
408 /**
409 * JS::MaybeRunNurseryCollection will collect the nursery if it hasn't been
410 * collected in this many milliseconds.
411 *
412 * Default: 5000
413 * Pref: javascript.options.mem.nursery_eager_collection_timeout_ms
414 */
415 JSGC_NURSERY_EAGER_COLLECTION_TIMEOUT_MS = 46,
416
417 /**
418 * The system page size in KB.
419 *
420 * This parameter is read-only.
421 */
422 JSGC_SYSTEM_PAGE_SIZE_KB = 47,
423
424 /**
425 * In an incremental GC, this determines the point at which to start
426 * increasing the slice budget and frequency of allocation triggered slices to
427 * try to avoid reaching the incremental limit and finishing the collection
428 * synchronously.
429 *
430 * The threshold is calculated by subtracting this value from the heap's
431 * incremental limit.
432 */
433 JSGC_URGENT_THRESHOLD_MB = 48,
434
435 /**
436 * Get the number of threads used for parallel marking.
437 *
438 * Pref: None.
439 */
440 JSGC_MARKING_THREAD_COUNT = 49,
441
442 /**
443 * The heap size above which to use parallel marking.
444 *
445 * Pref: javascript.options.mem.gc_parallel_marking_threshold_mb
446 * Default: ParallelMarkingThresholdMB
447 */
448 JSGC_PARALLEL_MARKING_THRESHOLD_MB = 50,
449
450 /**
451 * Whether the semispace nursery is enabled.
452 *
453 * Pref: javascript.options.mem.gc_experimental_semispace_nursery
454 * Default: SemispaceNurseryEnabled
455 */
456 JSGC_SEMISPACE_NURSERY_ENABLED = 51,
457
458 /**
459 * Set the maximum number of threads to use for parallel marking, if enabled.
460 *
461 * The actual number used is calculated based on the number of available
462 * helper threads and can be found by getting the JSGC_MARKING_THREAD_COUNT
463 * parameter.
464 *
465 * Pref: javascript.options.mem.gc_max_parallel_marking_threads
466 * Default: 2.
467 */
468 JSGC_MAX_MARKING_THREADS = 52,
469
470 /**
471 * Whether to automatically generate missing allocation sites so data about
472 * them can be gathered.
473 *
474 * Pref: None, this is an internal engine feature.
475 * Default: false.
476 */
477 JSGC_GENERATE_MISSING_ALLOC_SITES = 53,
478
479 /**
480 * A number that is incremented every GC slice.
481 */
482 JSGC_SLICE_NUMBER = 54,
483
484 /**
485 * Whether the nursery is enabled.
486 *
487 * Pref: javascript.options.mem.gc_generational
488 * Default: true
489 */
490 JSGC_NURSERY_ENABLED = 55,
491
492 /*
493 * Whether we are in high frequency GC mode, where the time between
494 * collections is less than that specified by JSGC_HIGH_FREQUENCY_TIME_LIMIT.
495 */
496 JSGC_HIGH_FREQUENCY_MODE = 56,
497
498 /**
499 * The engine attempts to keep nursery collection time less than this limit by
500 * restricting the size of the nursery.
501 *
502 * This only happens in optimized builds. It does not happen during pageload
503 * (as indicated by js::gc::SetPerformanceHint).
504 *
505 * Setting this to zero disables this feature.
506 *
507 * Default: 4
508 * Pref: javascript.options.mem.nursery_max_time_goal_ms
509 */
510 JSGC_NURSERY_MAX_TIME_GOAL_MS = 57,
511 } JSGCParamKey;
512
513 /*
514 * Generic trace operation that calls JS::TraceEdge on each traceable thing's
515 * location reachable from data.
516 */
517 typedef void (*JSTraceDataOp)(JSTracer* trc, void* data);
518
519 /*
520 * Trace hook used to trace gray roots incrementally.
521 *
522 * This should return whether tracing is finished. It will be called repeatedly
523 * in subsequent GC slices until it returns true.
524 *
525 * While tracing this should check the budget and return false if it has been
526 * exceeded. When passed an unlimited budget it should always return true.
527 */
528 typedef bool (*JSGrayRootsTracer)(JSTracer* trc, JS::SliceBudget& budget,
529 void* data);
530
531 typedef enum JSGCStatus { JSGC_BEGIN, JSGC_END } JSGCStatus;
532
533 typedef void (*JSObjectsTenuredCallback)(JS::GCContext* gcx, void* data);
534
535 typedef enum JSFinalizeStatus {
536 /**
537 * Called when preparing to sweep a group of zones, before anything has been
538 * swept. The collector will not yield to the mutator before calling the
539 * callback with JSFINALIZE_GROUP_START status.
540 */
541 JSFINALIZE_GROUP_PREPARE,
542
543 /**
544 * Called after preparing to sweep a group of zones. Weak references to
545 * unmarked things have been removed at this point, but no GC things have
546 * been swept. The collector may yield to the mutator after this point.
547 */
548 JSFINALIZE_GROUP_START,
549
550 /**
551 * Called after sweeping a group of zones. All dead GC things have been
552 * swept at this point.
553 */
554 JSFINALIZE_GROUP_END,
555
556 /**
557 * Called at the end of collection when everything has been swept.
558 */
559 JSFINALIZE_COLLECTION_END
560 } JSFinalizeStatus;
561
562 typedef void (*JSFinalizeCallback)(JS::GCContext* gcx, JSFinalizeStatus status,
563 void* data);
564
565 typedef void (*JSWeakPointerZonesCallback)(JSTracer* trc, void* data);
566
567 typedef void (*JSWeakPointerCompartmentCallback)(JSTracer* trc,
568 JS::Compartment* comp,
569 void* data);
570
571 /*
572 * This is called to tell the embedding that a FinalizationRegistry object has
573 * cleanup work, and that the engine should be called back at an appropriate
574 * later time to perform this cleanup, by calling the function |doCleanup|.
575 *
576 * This callback must not do anything that could cause GC.
577 */
578 using JSHostCleanupFinalizationRegistryCallback =
579 void (*)(JSFunction* doCleanup, JSObject* incumbentGlobal, void* data);
580
581 /**
582 * Each external string has a pointer to JSExternalStringCallbacks. Embedders
583 * can use this to implement custom finalization or memory reporting behavior.
584 */
585 struct JSExternalStringCallbacks {
586 /**
587 * Finalizes external strings created by JS_NewExternalStringLatin1 or
588 * JS_NewExternalUCString. The finalizer can be called off the main
589 * thread.
590 */
591 virtual void finalize(JS::Latin1Char* chars) const = 0;
592 virtual void finalize(char16_t* chars) const = 0;
593
594 /**
595 * Callback used by memory reporting to ask the embedder how much memory an
596 * external string is keeping alive. The embedder is expected to return a
597 * value that corresponds to the size of the allocation that will be released
598 * by the finalizer callback above.
599 *
600 * Implementations of this callback MUST NOT do anything that can cause GC.
601 */
602 virtual size_t sizeOfBuffer(const JS::Latin1Char* chars,
603 mozilla::MallocSizeOf mallocSizeOf) const = 0;
604 virtual size_t sizeOfBuffer(const char16_t* chars,
605 mozilla::MallocSizeOf mallocSizeOf) const = 0;
606 };
607
608 namespace JS {
609
610 #define GCREASONS(D) \
611 /* Reasons internal to the JS engine. */ \
612 D(API, 0) \
613 D(EAGER_ALLOC_TRIGGER, 1) \
614 D(DESTROY_RUNTIME, 2) \
615 D(ROOTS_REMOVED, 3) \
616 D(LAST_DITCH, 4) \
617 D(TOO_MUCH_MALLOC, 5) \
618 D(ALLOC_TRIGGER, 6) \
619 D(DEBUG_GC, 7) \
620 D(COMPARTMENT_REVIVED, 8) \
621 D(RESET, 9) \
622 D(OUT_OF_NURSERY, 10) \
623 D(EVICT_NURSERY, 11) \
624 D(SHARED_MEMORY_LIMIT, 13) \
625 D(EAGER_NURSERY_COLLECTION, 14) \
626 D(BG_TASK_FINISHED, 15) \
627 D(ABORT_GC, 16) \
628 D(FULL_WHOLE_CELL_BUFFER, 17) \
629 D(FULL_GENERIC_BUFFER, 18) \
630 D(FULL_VALUE_BUFFER, 19) \
631 D(FULL_CELL_PTR_OBJ_BUFFER, 20) \
632 D(FULL_SLOT_BUFFER, 21) \
633 D(FULL_SHAPE_BUFFER, 22) \
634 D(TOO_MUCH_WASM_MEMORY, 23) \
635 D(DISABLE_GENERATIONAL_GC, 24) \
636 D(FINISH_GC, 25) \
637 D(PREPARE_FOR_TRACING, 26) \
638 D(FULL_WASM_ANYREF_BUFFER, 27) \
639 D(FULL_CELL_PTR_STR_BUFFER, 28) \
640 D(TOO_MUCH_JIT_CODE, 29) \
641 D(FULL_CELL_PTR_BIGINT_BUFFER, 30) \
642 D(NURSERY_TRAILERS, 31) \
643 D(NURSERY_MALLOC_BUFFERS, 32) \
644 \
645 /* \
646 * Reasons from Firefox. \
647 * \
648 * The JS engine attaches special meanings to some of these reasons. \
649 */ \
650 D(DOM_WINDOW_UTILS, FIRST_FIREFOX_REASON) \
651 D(COMPONENT_UTILS, 34) \
652 D(MEM_PRESSURE, 35) \
653 D(CC_FINISHED, 36) \
654 D(CC_FORCED, 37) \
655 D(LOAD_END, 38) \
656 D(UNUSED3, 39) \
657 D(PAGE_HIDE, 40) \
658 D(NSJSCONTEXT_DESTROY, 41) \
659 D(WORKER_SHUTDOWN, 42) \
660 D(SET_DOC_SHELL, 43) \
661 D(DOM_UTILS, 44) \
662 D(DOM_IPC, 45) \
663 D(DOM_WORKER, 46) \
664 D(INTER_SLICE_GC, 47) \
665 D(UNUSED1, 48) \
666 D(FULL_GC_TIMER, 49) \
667 D(SHUTDOWN_CC, 50) \
668 D(UNUSED2, 51) \
669 D(USER_INACTIVE, 52) \
670 D(XPCONNECT_SHUTDOWN, 53) \
671 D(DOCSHELL, 54) \
672 D(HTML_PARSER, 55) \
673 D(DOM_TESTUTILS, 56) \
674 D(PREPARE_FOR_PAGELOAD, LAST_FIREFOX_REASON) \
675 \
676 /* Reasons reserved for embeddings. */ \
677 D(RESERVED1, FIRST_RESERVED_REASON) \
678 D(RESERVED2, 91) \
679 D(RESERVED3, 92) \
680 D(RESERVED4, 93) \
681 D(RESERVED5, 94) \
682 D(RESERVED6, 95) \
683 D(RESERVED7, 96) \
684 D(RESERVED8, 97) \
685 D(RESERVED9, 98)
686
687 enum class GCReason {
688 FIRST_FIREFOX_REASON = 33,
689 LAST_FIREFOX_REASON = 57,
690 FIRST_RESERVED_REASON = 90,
691
692 #define MAKE_REASON(name, val) name = val,
693 GCREASONS(MAKE_REASON)
694 #undef MAKE_REASON
695 NO_REASON,
696 NUM_REASONS,
697
698 /*
699 * For telemetry, we want to keep a fixed max bucket size over time so we
700 * don't have to switch histograms. 100 is conservative; but the cost of extra
701 * buckets seems to be low while the cost of switching histograms is high.
702 */
703 NUM_TELEMETRY_REASONS = 100
704 };
705
706 /**
707 * Get a statically allocated C string explaining the given GC reason.
708 */
709 extern JS_PUBLIC_API const char* ExplainGCReason(JS::GCReason reason);
710
711 /**
712 * Return true if the GC reason is internal to the JS engine.
713 */
714 extern JS_PUBLIC_API bool InternalGCReason(JS::GCReason reason);
715
716 /**
717 * Get a statically allocated C string explaining the given Abort reason.
718 * Input is the integral value of the enum.
719 */
720 extern JS_PUBLIC_API const char* ExplainGCAbortReason(uint32_t reason);
721
722 /**
723 * Get a statically allocated C string describing the Phase.
724 * Input is the integral value of the enum.
725 */
726 extern JS_PUBLIC_API const char* GetGCPhaseName(uint32_t phase);
727
728 /*
729 * Zone GC:
730 *
731 * SpiderMonkey's GC is capable of performing a collection on an arbitrary
732 * subset of the zones in the system. This allows an embedding to minimize
733 * collection time by only collecting zones that have run code recently,
734 * ignoring the parts of the heap that are unlikely to have changed.
735 *
736 * When triggering a GC using one of the functions below, it is first necessary
737 * to select the zones to be collected. To do this, you can call
738 * PrepareZoneForGC on each zone, or you can call PrepareForFullGC to select
739 * all zones. Failing to select any zone is an error.
740 */
741
742 /**
743 * Schedule the given zone to be collected as part of the next GC.
744 */
745 extern JS_PUBLIC_API void PrepareZoneForGC(JSContext* cx, Zone* zone);
746
747 /**
748 * Schedule all zones to be collected in the next GC.
749 */
750 extern JS_PUBLIC_API void PrepareForFullGC(JSContext* cx);
751
752 /**
753 * When performing an incremental GC, the zones that were selected for the
754 * previous incremental slice must be selected in subsequent slices as well.
755 * This function selects those slices automatically.
756 */
757 extern JS_PUBLIC_API void PrepareForIncrementalGC(JSContext* cx);
758
759 /**
760 * Returns true if any zone in the system has been scheduled for GC with one of
761 * the functions above or by the JS engine.
762 */
763 extern JS_PUBLIC_API bool IsGCScheduled(JSContext* cx);
764
765 /**
766 * Undoes the effect of the Prepare methods above. The given zone will not be
767 * collected in the next GC.
768 */
769 extern JS_PUBLIC_API void SkipZoneForGC(JSContext* cx, Zone* zone);
770
771 /*
772 * Non-Incremental GC:
773 *
774 * The following functions perform a non-incremental GC.
775 */
776
777 /**
778 * Performs a non-incremental collection of all selected zones.
779 */
780 extern JS_PUBLIC_API void NonIncrementalGC(JSContext* cx, JS::GCOptions options,
781 GCReason reason);
782
783 /*
784 * Incremental GC:
785 *
786 * Incremental GC divides the full mark-and-sweep collection into multiple
787 * slices, allowing client JavaScript code to run between each slice. This
788 * allows interactive apps to avoid long collection pauses. Incremental GC does
789 * not make collection take less time, it merely spreads that time out so that
790 * the pauses are less noticable.
791 *
792 * For a collection to be carried out incrementally the following conditions
793 * must be met:
794 * - The collection must be run by calling JS::IncrementalGC() rather than
795 * JS_GC().
796 * - The GC parameter JSGC_INCREMENTAL_GC_ENABLED must be true.
797 *
798 * Note: Even if incremental GC is enabled and working correctly,
799 * non-incremental collections can still happen when low on memory.
800 */
801
802 /**
803 * Begin an incremental collection and perform one slice worth of work. When
804 * this function returns, the collection may not be complete.
805 * IncrementalGCSlice() must be called repeatedly until
806 * !IsIncrementalGCInProgress(cx).
807 *
808 * Note: SpiderMonkey's GC is not realtime. Slices in practice may be longer or
809 * shorter than the requested interval.
810 */
811 extern JS_PUBLIC_API void StartIncrementalGC(JSContext* cx,
812 JS::GCOptions options,
813 GCReason reason,
814 const JS::SliceBudget& budget);
815
816 /**
817 * Perform a slice of an ongoing incremental collection. When this function
818 * returns, the collection may not be complete. It must be called repeatedly
819 * until !IsIncrementalGCInProgress(cx).
820 *
821 * Note: SpiderMonkey's GC is not realtime. Slices in practice may be longer or
822 * shorter than the requested interval.
823 */
824 extern JS_PUBLIC_API void IncrementalGCSlice(JSContext* cx, GCReason reason,
825 const JS::SliceBudget& budget);
826
827 /**
828 * Return whether an incremental GC has work to do on the foreground thread and
829 * would make progress if a slice was run now. If this returns false then the GC
830 * is waiting for background threads to finish their work and a slice started
831 * now would return immediately.
832 */
833 extern JS_PUBLIC_API bool IncrementalGCHasForegroundWork(JSContext* cx);
834
835 /**
836 * If IsIncrementalGCInProgress(cx), this call finishes the ongoing collection
837 * by performing an arbitrarily long slice. If !IsIncrementalGCInProgress(cx),
838 * this is equivalent to NonIncrementalGC. When this function returns,
839 * IsIncrementalGCInProgress(cx) will always be false.
840 */
841 extern JS_PUBLIC_API void FinishIncrementalGC(JSContext* cx, GCReason reason);
842
843 /**
844 * If IsIncrementalGCInProgress(cx), this call aborts the ongoing collection and
845 * performs whatever work needs to be done to return the collector to its idle
846 * state. This may take an arbitrarily long time. When this function returns,
847 * IsIncrementalGCInProgress(cx) will always be false.
848 */
849 extern JS_PUBLIC_API void AbortIncrementalGC(JSContext* cx);
850
851 namespace dbg {
852
853 // The `JS::dbg::GarbageCollectionEvent` class is essentially a view of the
854 // `js::gcstats::Statistics` data without the uber implementation-specific bits.
855 // It should generally be palatable for web developers.
856 class GarbageCollectionEvent {
857 // The major GC number of the GC cycle this data pertains to.
858 uint64_t majorGCNumber_;
859
860 // Reference to a non-owned, statically allocated C string. This is a very
861 // short reason explaining why a GC was triggered.
862 const char* reason;
863
864 // Reference to a nullable, non-owned, statically allocated C string. If the
865 // collection was forced to be non-incremental, this is a short reason of
866 // why the GC could not perform an incremental collection.
867 const char* nonincrementalReason;
868
869 // Represents a single slice of a possibly multi-slice incremental garbage
870 // collection.
871 struct Collection {
872 mozilla::TimeStamp startTimestamp;
873 mozilla::TimeStamp endTimestamp;
874 };
875
876 // The set of garbage collection slices that made up this GC cycle.
877 mozilla::Vector<Collection> collections;
878
879 GarbageCollectionEvent(const GarbageCollectionEvent& rhs) = delete;
880 GarbageCollectionEvent& operator=(const GarbageCollectionEvent& rhs) = delete;
881
882 public:
883 explicit GarbageCollectionEvent(uint64_t majorGCNum)
884 : majorGCNumber_(majorGCNum),
885 reason(nullptr),
886 nonincrementalReason(nullptr),
887 collections() {}
888
889 using Ptr = js::UniquePtr<GarbageCollectionEvent>;
890 static Ptr Create(JSRuntime* rt, ::js::gcstats::Statistics& stats,
891 uint64_t majorGCNumber);
892
893 JSObject* toJSObject(JSContext* cx) const;
894
895 uint64_t majorGCNumber() const { return majorGCNumber_; }
896 };
897
898 } // namespace dbg
899
900 enum GCProgress {
901 /*
902 * During GC, the GC is bracketed by GC_CYCLE_BEGIN/END callbacks. Each
903 * slice between those (whether an incremental or the sole non-incremental
904 * slice) is bracketed by GC_SLICE_BEGIN/GC_SLICE_END.
905 */
906
907 GC_CYCLE_BEGIN,
908 GC_SLICE_BEGIN,
909 GC_SLICE_END,
910 GC_CYCLE_END
911 };
912
913 struct JS_PUBLIC_API GCDescription {
914 bool isZone_;
915 bool isComplete_;
916 JS::GCOptions options_;
917 GCReason reason_;
918
919 GCDescription(bool isZone, bool isComplete, JS::GCOptions options,
920 GCReason reason)
921 : isZone_(isZone),
922 isComplete_(isComplete),
923 options_(options),
924 reason_(reason) {}
925
926 char16_t* formatSliceMessage(JSContext* cx) const;
927 char16_t* formatSummaryMessage(JSContext* cx) const;
928
929 mozilla::TimeStamp startTime(JSContext* cx) const;
930 mozilla::TimeStamp endTime(JSContext* cx) const;
931 mozilla::TimeStamp lastSliceStart(JSContext* cx) const;
932 mozilla::TimeStamp lastSliceEnd(JSContext* cx) const;
933
934 JS::UniqueChars sliceToJSONProfiler(JSContext* cx) const;
935 JS::UniqueChars formatJSONProfiler(JSContext* cx) const;
936
937 JS::dbg::GarbageCollectionEvent::Ptr toGCEvent(JSContext* cx) const;
938 };
939
940 extern JS_PUBLIC_API UniqueChars MinorGcToJSON(JSContext* cx);
941
942 typedef void (*GCSliceCallback)(JSContext* cx, GCProgress progress,
943 const GCDescription& desc);
944
945 /**
946 * The GC slice callback is called at the beginning and end of each slice. This
947 * callback may be used for GC notifications as well as to perform additional
948 * marking.
949 */
950 extern JS_PUBLIC_API GCSliceCallback
951 SetGCSliceCallback(JSContext* cx, GCSliceCallback callback);
952
953 /**
954 * Describes the progress of an observed nursery collection.
955 */
956 enum class GCNurseryProgress {
957 /**
958 * The nursery collection is starting.
959 */
960 GC_NURSERY_COLLECTION_START,
961 /**
962 * The nursery collection is ending.
963 */
964 GC_NURSERY_COLLECTION_END
965 };
966
967 /**
968 * A nursery collection callback receives the progress of the nursery collection
969 * and the reason for the collection.
970 */
971 using GCNurseryCollectionCallback = void (*)(JSContext* cx,
972 GCNurseryProgress progress,
973 GCReason reason, void* data);
974
975 /**
976 * Add and remove nursery collection callbacks for the given runtime. These will
977 * be called at the start and end of every nursery collection.
978 */
979 extern JS_PUBLIC_API bool AddGCNurseryCollectionCallback(
980 JSContext* cx, GCNurseryCollectionCallback callback, void* data);
981 extern JS_PUBLIC_API void RemoveGCNurseryCollectionCallback(
982 JSContext* cx, GCNurseryCollectionCallback callback, void* data);
983
984 typedef void (*DoCycleCollectionCallback)(JSContext* cx);
985
986 /**
987 * The purge gray callback is called after any COMPARTMENT_REVIVED GC in which
988 * the majority of compartments have been marked gray.
989 */
990 extern JS_PUBLIC_API DoCycleCollectionCallback
991 SetDoCycleCollectionCallback(JSContext* cx, DoCycleCollectionCallback callback);
992
993 using CreateSliceBudgetCallback = JS::SliceBudget (*)(JS::GCReason reason,
994 int64_t millis);
995
996 /**
997 * Called when generating a GC slice budget. It allows the embedding to control
998 * the duration of slices and potentially check an interrupt flag as well. For
999 * internally triggered GCs, the given millis parameter is the JS engine's
1000 * internal scheduling decision, which the embedding can choose to ignore.
1001 * (Otherwise, it will be the value that was passed to eg
1002 * JS::IncrementalGCSlice()).
1003 */
1004 extern JS_PUBLIC_API void SetCreateGCSliceBudgetCallback(
1005 JSContext* cx, CreateSliceBudgetCallback cb);
1006
1007 /**
1008 * Returns true if incremental GC is enabled. Simply having incremental GC
1009 * enabled is not sufficient to ensure incremental collections are happening.
1010 * See the comment "Incremental GC" above for reasons why incremental GC may be
1011 * suppressed. Inspection of the "nonincremental reason" field of the
1012 * GCDescription returned by GCSliceCallback may help narrow down the cause if
1013 * collections are not happening incrementally when expected.
1014 */
1015 extern JS_PUBLIC_API bool IsIncrementalGCEnabled(JSContext* cx);
1016
1017 /**
1018 * Returns true while an incremental GC is ongoing, both when actively
1019 * collecting and between slices.
1020 */
1021 extern JS_PUBLIC_API bool IsIncrementalGCInProgress(JSContext* cx);
1022
1023 /**
1024 * Returns true while an incremental GC is ongoing, both when actively
1025 * collecting and between slices.
1026 */
1027 extern JS_PUBLIC_API bool IsIncrementalGCInProgress(JSRuntime* rt);
1028
1029 /**
1030 * Returns true if the most recent GC ran incrementally.
1031 */
1032 extern JS_PUBLIC_API bool WasIncrementalGC(JSRuntime* rt);
1033
1034 /*
1035 * Generational GC:
1036 */
1037
1038 /**
1039 * Ensure that generational GC is disabled within some scope.
1040 *
1041 * This evicts the nursery and discards JIT code so it is not a lightweight
1042 * operation.
1043 */
1044 class JS_PUBLIC_API AutoDisableGenerationalGC {
1045 JSContext* cx;
1046
1047 public:
1048 explicit AutoDisableGenerationalGC(JSContext* cx);
1049 ~AutoDisableGenerationalGC();
1050 };
1051
1052 /**
1053 * Returns true if generational allocation and collection is currently enabled
1054 * on the given runtime.
1055 */
1056 extern JS_PUBLIC_API bool IsGenerationalGCEnabled(JSRuntime* rt);
1057
1058 /**
1059 * Pass a subclass of this "abstract" class to callees to require that they
1060 * never GC. Subclasses can use assertions or the hazard analysis to ensure no
1061 * GC happens.
1062 */
1063 class JS_PUBLIC_API AutoRequireNoGC {
1064 protected:
1065 AutoRequireNoGC() = default;
1066 ~AutoRequireNoGC() = default;
1067 };
1068
1069 /**
1070 * Diagnostic assert (see MOZ_DIAGNOSTIC_ASSERT) that GC cannot occur while this
1071 * class is live. This class does not disable the static rooting hazard
1072 * analysis.
1073 *
1074 * This works by entering a GC unsafe region, which is checked on allocation and
1075 * on GC.
1076 */
1077 class JS_PUBLIC_API AutoAssertNoGC : public AutoRequireNoGC {
1078 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
1079 protected:
1080 JSContext* cx_; // nullptr if inactive.
1081
1082 public:
1083 // Nullptr here means get the context from TLS. It does not mean inactive
1084 // (though cx_ may end up nullptr, and thus inactive, if TLS has not yet been
1085 // initialized.)
1086 explicit AutoAssertNoGC(JSContext* cx = nullptr);
1087 AutoAssertNoGC(AutoAssertNoGC&& other) : cx_(other.cx_) {
1088 other.cx_ = nullptr;
1089 }
1090 ~AutoAssertNoGC();
1091
1092 void reset();
1093 #else
1094 public:
1095 explicit AutoAssertNoGC(JSContext* cx = nullptr) {}
1096 ~AutoAssertNoGC() {}
1097
1098 void reset() {}
1099 #endif
1100 };
1101
1102 /**
1103 * Disable the static rooting hazard analysis in the live region and assert in
1104 * debug builds if any allocation that could potentially trigger a GC occurs
1105 * while this guard object is live. This is most useful to help the exact
1106 * rooting hazard analysis in complex regions, since it cannot understand
1107 * dataflow.
1108 *
1109 * Note: GC behavior is unpredictable even when deterministic and is generally
1110 * non-deterministic in practice. The fact that this guard has not
1111 * asserted is not a guarantee that a GC cannot happen in the guarded
1112 * region. As a rule, anyone performing a GC unsafe action should
1113 * understand the GC properties of all code in that region and ensure
1114 * that the hazard analysis is correct for that code, rather than relying
1115 * on this class.
1116 */
1117 #ifdef DEBUG
1118 class JS_PUBLIC_API AutoSuppressGCAnalysis : public AutoAssertNoGC {
1119 public:
1120 explicit AutoSuppressGCAnalysis(JSContext* cx = nullptr)
1121 : AutoAssertNoGC(cx) {}
1122 } JS_HAZ_GC_SUPPRESSED;
1123 #else
1124 class JS_PUBLIC_API AutoSuppressGCAnalysis : public AutoRequireNoGC {
1125 public:
1126 explicit AutoSuppressGCAnalysis(JSContext* cx = nullptr) {}
1127 } JS_HAZ_GC_SUPPRESSED;
1128 #endif
1129
1130 /**
1131 * Assert that code is only ever called from a GC callback, disable the static
1132 * rooting hazard analysis and assert if any allocation that could potentially
1133 * trigger a GC occurs while this guard object is live.
1134 *
1135 * This is useful to make the static analysis ignore code that runs in GC
1136 * callbacks.
1137 */
1138 class JS_PUBLIC_API AutoAssertGCCallback : public AutoSuppressGCAnalysis {
1139 public:
1140 #ifdef DEBUG
1141 AutoAssertGCCallback();
1142 #else
1143 AutoAssertGCCallback() {}
1144 #endif
1145 };
1146
1147 /**
1148 * Place AutoCheckCannotGC in scopes that you believe can never GC. These
1149 * annotations will be verified both dynamically via AutoAssertNoGC, and
1150 * statically with the rooting hazard analysis (implemented by making the
1151 * analysis consider AutoCheckCannotGC to be a GC pointer, and therefore
1152 * complain if it is live across a GC call.) It is useful when dealing with
1153 * internal pointers to GC things where the GC thing itself may not be present
1154 * for the static analysis: e.g. acquiring inline chars from a JSString* on the
1155 * heap.
1156 *
1157 * We only do the assertion checking in DEBUG builds.
1158 */
1159 #ifdef DEBUG
1160 class JS_PUBLIC_API AutoCheckCannotGC : public AutoAssertNoGC {
1161 public:
1162 explicit AutoCheckCannotGC(JSContext* cx = nullptr) : AutoAssertNoGC(cx) {}
1163 # ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
1164 AutoCheckCannotGC(const AutoCheckCannotGC& other)
1165 : AutoCheckCannotGC(other.cx_) {}
1166 # else
1167 AutoCheckCannotGC(const AutoCheckCannotGC& other) : AutoCheckCannotGC() {}
1168 # endif
1169 AutoCheckCannotGC(AutoCheckCannotGC&& other)
1170 : AutoAssertNoGC(std::forward<AutoAssertNoGC>(other)) {}
1171 #else
1172 class JS_PUBLIC_API AutoCheckCannotGC : public AutoRequireNoGC {
1173 public:
1174 explicit AutoCheckCannotGC(JSContext* cx = nullptr) {}
1175 AutoCheckCannotGC(const AutoCheckCannotGC& other) : AutoCheckCannotGC() {}
1176 AutoCheckCannotGC(AutoCheckCannotGC&& other) : AutoCheckCannotGC() {}
1177 void reset() {}
1178 #endif
1179 } JS_HAZ_GC_INVALIDATED JS_HAZ_GC_REF;
1180
1181 extern JS_PUBLIC_API void SetLowMemoryState(JSContext* cx, bool newState);
1182
1183 /*
1184 * Internal to Firefox.
1185 */
1186 extern JS_PUBLIC_API void NotifyGCRootsRemoved(JSContext* cx);
1187
1188 } /* namespace JS */
1189
1190 typedef void (*JSGCCallback)(JSContext* cx, JSGCStatus status,
1191 JS::GCReason reason, void* data);
1192
1193 /**
1194 * Register externally maintained GC roots.
1195 *
1196 * traceOp: the trace operation. For each root the implementation should call
1197 * JS::TraceEdge whenever the root contains a traceable thing.
1198 * data: the data argument to pass to each invocation of traceOp.
1199 */
1200 extern JS_PUBLIC_API bool JS_AddExtraGCRootsTracer(JSContext* cx,
1201 JSTraceDataOp traceOp,
1202 void* data);
1203
1204 /** Undo a call to JS_AddExtraGCRootsTracer. */
1205 extern JS_PUBLIC_API void JS_RemoveExtraGCRootsTracer(JSContext* cx,
1206 JSTraceDataOp traceOp,
1207 void* data);
1208
1209 extern JS_PUBLIC_API void JS_GC(JSContext* cx,
1210 JS::GCReason reason = JS::GCReason::API);
1211
1212 extern JS_PUBLIC_API void JS_MaybeGC(JSContext* cx);
1213
1214 extern JS_PUBLIC_API void JS_SetGCCallback(JSContext* cx, JSGCCallback cb,
1215 void* data);
1216
1217 extern JS_PUBLIC_API void JS_SetObjectsTenuredCallback(
1218 JSContext* cx, JSObjectsTenuredCallback cb, void* data);
1219
1220 extern JS_PUBLIC_API bool JS_AddFinalizeCallback(JSContext* cx,
1221 JSFinalizeCallback cb,
1222 void* data);
1223
1224 extern JS_PUBLIC_API void JS_RemoveFinalizeCallback(JSContext* cx,
1225 JSFinalizeCallback cb);
1226
1227 /*
1228 * Weak pointers and garbage collection
1229 *
1230 * Weak pointers are by their nature not marked as part of garbage collection,
1231 * but they may need to be updated in two cases after a GC:
1232 *
1233 * 1) Their referent was found not to be live and is about to be finalized
1234 * 2) Their referent has been moved by a compacting GC
1235 *
1236 * To handle this, any part of the system that maintain weak pointers to
1237 * JavaScript GC things must register a callback with
1238 * JS_(Add,Remove)WeakPointer{ZoneGroup,Compartment}Callback(). This callback
1239 * must then call JS_UpdateWeakPointerAfterGC() on all weak pointers it knows
1240 * about.
1241 *
1242 * Since sweeping is incremental, we have several callbacks to avoid repeatedly
1243 * having to visit all embedder structures. The WeakPointerZonesCallback is
1244 * called once for each strongly connected group of zones, whereas the
1245 * WeakPointerCompartmentCallback is called once for each compartment that is
1246 * visited while sweeping. Structures that cannot contain references in more
1247 * than one compartment should sweep the relevant per-compartment structures
1248 * using the latter callback to minimizer per-slice overhead.
1249 *
1250 * The argument to JS_UpdateWeakPointerAfterGC() is an in-out param. If the
1251 * referent is about to be finalized the pointer will be set to null. If the
1252 * referent has been moved then the pointer will be updated to point to the new
1253 * location.
1254 *
1255 * The return value of JS_UpdateWeakPointerAfterGC() indicates whether the
1256 * referent is still alive. If the referent is is about to be finalized, this
1257 * will return false.
1258 *
1259 * Callers of this method are responsible for updating any state that is
1260 * dependent on the object's address. For example, if the object's address is
1261 * used as a key in a hashtable, then the object must be removed and
1262 * re-inserted with the correct hash.
1263 */
1264
1265 extern JS_PUBLIC_API bool JS_AddWeakPointerZonesCallback(
1266 JSContext* cx, JSWeakPointerZonesCallback cb, void* data);
1267
1268 extern JS_PUBLIC_API void JS_RemoveWeakPointerZonesCallback(
1269 JSContext* cx, JSWeakPointerZonesCallback cb);
1270
1271 extern JS_PUBLIC_API bool JS_AddWeakPointerCompartmentCallback(
1272 JSContext* cx, JSWeakPointerCompartmentCallback cb, void* data);
1273
1274 extern JS_PUBLIC_API void JS_RemoveWeakPointerCompartmentCallback(
1275 JSContext* cx, JSWeakPointerCompartmentCallback cb);
1276
1277 namespace JS {
1278 template <typename T>
1279 class Heap;
1280 }
1281
1282 extern JS_PUBLIC_API bool JS_UpdateWeakPointerAfterGC(
1283 JSTracer* trc, JS::Heap<JSObject*>* objp);
1284
1285 extern JS_PUBLIC_API bool JS_UpdateWeakPointerAfterGCUnbarriered(
1286 JSTracer* trc, JSObject** objp);
1287
1288 extern JS_PUBLIC_API void JS_SetGCParameter(JSContext* cx, JSGCParamKey key,
1289 uint32_t value);
1290
1291 extern JS_PUBLIC_API void JS_ResetGCParameter(JSContext* cx, JSGCParamKey key);
1292
1293 extern JS_PUBLIC_API uint32_t JS_GetGCParameter(JSContext* cx,
1294 JSGCParamKey key);
1295
1296 extern JS_PUBLIC_API void JS_SetGCParametersBasedOnAvailableMemory(
1297 JSContext* cx, uint32_t availMemMB);
1298
1299 /**
1300 * Create a new JSString whose chars member refers to external memory, i.e.,
1301 * memory requiring application-specific finalization.
1302 */
1303 extern JS_PUBLIC_API JSString* JS_NewExternalStringLatin1(
1304 JSContext* cx, const JS::Latin1Char* chars, size_t length,
1305 const JSExternalStringCallbacks* callbacks);
1306 extern JS_PUBLIC_API JSString* JS_NewExternalUCString(
1307 JSContext* cx, const char16_t* chars, size_t length,
1308 const JSExternalStringCallbacks* callbacks);
1309
1310 /**
1311 * Create a new JSString whose chars member may refer to external memory.
1312 * If a new external string is allocated, |*allocatedExternal| is set to true.
1313 * Otherwise the returned string is either not an external string or an
1314 * external string allocated by a previous call and |*allocatedExternal| is set
1315 * to false. If |*allocatedExternal| is false, |fin| won't be called.
1316 */
1317 extern JS_PUBLIC_API JSString* JS_NewMaybeExternalStringLatin1(
1318 JSContext* cx, const JS::Latin1Char* chars, size_t length,
1319 const JSExternalStringCallbacks* callbacks, bool* allocatedExternal);
1320 extern JS_PUBLIC_API JSString* JS_NewMaybeExternalUCString(
1321 JSContext* cx, const char16_t* chars, size_t length,
1322 const JSExternalStringCallbacks* callbacks, bool* allocatedExternal);
1323
1324 /**
1325 * Similar to JS_NewMaybeExternalStringLatin1.
1326 *
1327 * Create an external Latin1 string if the utf8 buffer contains only ASCII
1328 * chars, otherwise copy the chars into a non-external string.
1329 */
1330 extern JS_PUBLIC_API JSString* JS_NewMaybeExternalStringUTF8(
1331 JSContext* cx, const JS::UTF8Chars& utf8,
1332 const JSExternalStringCallbacks* callbacks, bool* allocatedExternal);
1333
1334 /**
1335 * Return the 'callbacks' arg passed to JS_NewExternalStringLatin1,
1336 * JS_NewExternalUCString, JS_NewMaybeExternalStringLatin1,
1337 * or JS_NewMaybeExternalUCString.
1338 */
1339 extern JS_PUBLIC_API const JSExternalStringCallbacks*
1340 JS_GetExternalStringCallbacks(JSString* str);
1341
1342 namespace JS {
1343
1344 /**
1345 * Check whether the nursery should be eagerly collected, this is before it is
1346 * full.
1347 *
1348 * The idea is that this can be called when the host environment has some idle
1349 * time which it can use to for GC activity.
1350 *
1351 * Returns GCReason::NO_REASON to indicate no collection is desired.
1352 */
1353 extern JS_PUBLIC_API GCReason WantEagerMinorGC(JSRuntime* rt);
1354
1355 extern JS_PUBLIC_API GCReason WantEagerMajorGC(JSRuntime* rt);
1356
1357 /**
1358 * Check whether the nursery should be eagerly collected as per WantEagerMajorGC
1359 * above, and if so run a collection.
1360 *
1361 * The idea is that this can be called when the host environment has some idle
1362 * time which it can use to for GC activity.
1363 */
1364 extern JS_PUBLIC_API void MaybeRunNurseryCollection(JSRuntime* rt,
1365 JS::GCReason reason);
1366
1367 extern JS_PUBLIC_API void RunNurseryCollection(
1368 JSRuntime* rt, JS::GCReason reason,
1369 mozilla::TimeDuration aSinceLastMinorGC);
1370
1371 extern JS_PUBLIC_API void SetHostCleanupFinalizationRegistryCallback(
1372 JSContext* cx, JSHostCleanupFinalizationRegistryCallback cb, void* data);
1373
1374 /**
1375 * Clear kept alive objects in JS WeakRef.
1376 * https://tc39.es/proposal-weakrefs/#sec-clear-kept-objects
1377 */
1378 extern JS_PUBLIC_API void ClearKeptObjects(JSContext* cx);
1379
1380 inline JS_PUBLIC_API bool NeedGrayRootsForZone(Zone* zoneArg) {
1381 shadow::Zone* zone = shadow::Zone::from(zoneArg);
1382 return zone->isGCMarkingBlackAndGray() || zone->isGCCompacting();
1383 }
1384
1385 extern JS_PUBLIC_API bool AtomsZoneIsCollecting(JSRuntime* runtime);
1386 extern JS_PUBLIC_API bool IsAtomsZone(Zone* zone);
1387
1388 } // namespace JS
1389
1390 namespace js {
1391 namespace gc {
1392
1393 /**
1394 * Create an object providing access to the garbage collector's internal notion
1395 * of the current state of memory (both GC heap memory and GCthing-controlled
1396 * malloc memory.
1397 */
1398 extern JS_PUBLIC_API JSObject* NewMemoryInfoObject(JSContext* cx);
1399
1400 /*
1401 * Get the GCContext for the current context.
1402 *
1403 * This is here to allow the browser to call finalizers for dead nursery
1404 * objects. This is a dangerous operation - only use this if you know what
1405 * you're doing!
1406 */
1407 extern JS_PUBLIC_API JS::GCContext* GetGCContext(JSContext* cx);
1408
1409 } /* namespace gc */
1410 } /* namespace js */
1411
1412 #ifdef JS_GC_ZEAL
1413
1414 namespace JS {
1415
1416 static constexpr uint32_t ShellDefaultGCZealFrequency = 100;
1417 static constexpr uint32_t BrowserDefaultGCZealFrequency = 5000;
1418
1419 extern JS_PUBLIC_API void GetGCZealBits(JSContext* cx, uint32_t* zealBits,
1420 uint32_t* frequency,
1421 uint32_t* nextScheduled);
1422
1423 extern JS_PUBLIC_API void SetGCZeal(JSContext* cx, uint8_t zeal,
1424 uint32_t frequency);
1425
1426 extern JS_PUBLIC_API void UnsetGCZeal(JSContext* cx, uint8_t zeal);
1427
1428 extern JS_PUBLIC_API void ScheduleGC(JSContext* cx, uint32_t count);
1429
1430 } // namespace JS
1431
1432 #endif
1433
1434 #endif /* js_GCAPI_h */