Debian Codegraph @

js/src/gc/Zone.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 #ifndef gc_Zone_h
8 #define gc_Zone_h
9
10 #include "mozilla/Array.h"
11 #include "mozilla/Assertions.h"
12 #include "mozilla/Attributes.h"
13 #include "mozilla/LinkedList.h"
14 #include "mozilla/MemoryReporting.h"
15 #include "mozilla/PodOperations.h"
16 #include "mozilla/TimeStamp.h"
17
18 #include <array>
19
20 #include "jstypes.h"
21
22 #include "ds/Bitmap.h"
23 #include "gc/ArenaList.h"
24 #include "gc/Barrier.h"
25 #include "gc/BufferAllocator.h"
26 #include "gc/FindSCCs.h"
27 #include "gc/GCMarker.h"
28 #include "gc/NurseryAwareHashMap.h"
29 #include "gc/Policy.h"
30 #include "gc/Pretenuring.h"
31 #include "gc/Statistics.h"
32 #include "gc/ZoneAllocator.h"
33 #include "js/GCHashTable.h"
34 #include "js/Vector.h"
35 #include "vm/AtomsTable.h"
36 #include "vm/InvalidatingFuse.h"
37 #include "vm/JSObject.h"
38 #include "vm/JSScript.h"
39 #include "vm/ShapeZone.h"
40
41 namespace js {
42
43 class DebugScriptMap;
44 class RegExpZone;
45 class WeakRefObject;
46
47 namespace jit {
48 class JitZone;
49 } // namespace jit
50
51 namespace gc {
52
53 class FinalizationObservers;
54 class ZoneList;
55
56 using ZoneComponentFinder = ComponentFinder<JS::Zone>;
57
58 struct UniqueIdGCPolicy {
59 static bool traceWeak(JSTracer* trc, Cell** keyp, uint64_t* valuep);
60 };
61
62 // Maps a Cell* to a unique, 64bit id.
63 using UniqueIdMap = GCHashMap<Cell*, uint64_t, PointerHasher<Cell*>,
64 SystemAllocPolicy, UniqueIdGCPolicy>;
65
66 template <typename T>
67 class ZoneAllCellIter;
68
69 template <typename T>
70 class ZoneCellIter;
71
72 #ifdef JS_GC_ZEAL
73
74 class MissingAllocSites {
75 public:
76 using SiteMap = JS::GCHashMap<uint32_t, UniquePtr<AllocSite>,
77 DefaultHasher<uint32_t>, SystemAllocPolicy>;
78
79 using ScriptMap = JS::GCHashMap<WeakHeapPtr<JSScript*>, SiteMap,
80 StableCellHasher<WeakHeapPtr<JSScript*>>,
81 SystemAllocPolicy>;
82 JS::WeakCache<ScriptMap> scriptMap;
83
84 explicit MissingAllocSites(JS::Zone* zone) : scriptMap(zone) {}
85 };
86
87 #endif // JS_GC_ZEAL
88
89 } // namespace gc
90
91 // If two different nursery strings are wrapped into the same zone, and have
92 // the same contents, then deduplication may make them duplicates.
93 // `DuplicatesPossible` will allow this and map both wrappers to the same (now
94 // tenured) source string.
95 using StringWrapperMap =
96 NurseryAwareHashMap<JSString*, JSString*, ZoneAllocPolicy,
97 DuplicatesPossible>;
98
99 // Cache for NewMaybeExternalString and NewStringFromBuffer. It has separate
100 // cache entries for the Latin1 JSThinInlineString fast path and for the generic
101 // path where we allocate either a JSExternalString, an inline string, or a
102 // string with a StringBuffer.
103 class MOZ_NON_TEMPORARY_CLASS ExternalStringCache {
104 static const size_t NumEntries = 4;
105 mozilla::Array<JSInlineString*, NumEntries> inlineLatin1Entries_;
106 mozilla::Array<JSLinearString*, NumEntries> entries_;
107
108 public:
109 ExternalStringCache() { purge(); }
110
111 ExternalStringCache(const ExternalStringCache&) = delete;
112 void operator=(const ExternalStringCache&) = delete;
113
114 void purge() {
115 inlineLatin1Entries_ = {};
116 entries_ = {};
117 }
118
119 MOZ_ALWAYS_INLINE JSLinearString* lookup(const JS::Latin1Char* chars,
120 size_t len) const;
121 MOZ_ALWAYS_INLINE JSLinearString* lookup(const char16_t* chars,
122 size_t len) const;
123 MOZ_ALWAYS_INLINE void put(JSLinearString* s);
124
125 MOZ_ALWAYS_INLINE JSInlineString* lookupInlineLatin1(
126 const JS::Latin1Char* chars, size_t len) const;
127 MOZ_ALWAYS_INLINE JSInlineString* lookupInlineLatin1(const char16_t* chars,
128 size_t len) const;
129 MOZ_ALWAYS_INLINE void putInlineLatin1(JSInlineString* s);
130
131 private:
132 template <typename CharT>
133 MOZ_ALWAYS_INLINE JSLinearString* lookupImpl(const CharT* chars,
134 size_t len) const;
135 template <typename CharT>
136 MOZ_ALWAYS_INLINE JSInlineString* lookupInlineLatin1Impl(const CharT* chars,
137 size_t len) const;
138 };
139
140 class MOZ_NON_TEMPORARY_CLASS FunctionToStringCache {
141 struct Entry {
142 BaseScript* script;
143 JSString* string;
144
145 void set(BaseScript* scriptArg, JSString* stringArg) {
146 script = scriptArg;
147 string = stringArg;
148 }
149 };
150 static const size_t NumEntries = 2;
151 mozilla::Array<Entry, NumEntries> entries_;
152
153 public:
154 FunctionToStringCache() { purge(); }
155
156 FunctionToStringCache(const FunctionToStringCache&) = delete;
157 void operator=(const FunctionToStringCache&) = delete;
158
159 void purge() { mozilla::PodArrayZero(entries_); }
160
161 MOZ_ALWAYS_INLINE JSString* lookup(BaseScript* script) const;
162 MOZ_ALWAYS_INLINE void put(BaseScript* script, JSString* string);
163 };
164
165 // HashAndLength is a simple class encapsulating the combination of a HashNumber
166 // and a (string) length into a single 64-bit value. Having them bundled
167 // together like this enables us to compare pairs of hashes and lengths with a
168 // single 64-bit comparison.
169 class HashAndLength {
170 public:
171 MOZ_ALWAYS_INLINE explicit HashAndLength(uint64_t initialValue = unsetValue())
172 : mHashAndLength(initialValue) {}
173 MOZ_ALWAYS_INLINE HashAndLength(HashNumber hash, uint32_t length)
174 : mHashAndLength(uint64FromHashAndLength(hash, length)) {}
175
176 void MOZ_ALWAYS_INLINE set(HashNumber hash, uint32_t length) {
177 mHashAndLength = uint64FromHashAndLength(hash, length);
178 }
179
180 constexpr MOZ_ALWAYS_INLINE HashNumber hash() const {
181 return hashFromUint64(mHashAndLength);
182 }
183 constexpr MOZ_ALWAYS_INLINE uint32_t length() const {
184 return lengthFromUint64(mHashAndLength);
185 }
186
187 constexpr MOZ_ALWAYS_INLINE bool isEqual(HashNumber hash,
188 uint32_t length) const {
189 return mHashAndLength == uint64FromHashAndLength(hash, length);
190 }
191
192 // This function is used at compile-time to verify and that we pack and unpack
193 // hash and length values consistently.
194 static constexpr bool staticChecks() {
195 std::array<HashNumber, 5> hashes{0x00000000, 0xffffffff, 0xf0f0f0f0,
196 0x0f0f0f0f, 0x73737373};
197 std::array<uint32_t, 6> lengths{0, 1, 2, 3, 11, 56};
198
199 for (const HashNumber hash : hashes) {
200 for (const uint32_t length : lengths) {
201 const uint64_t lengthAndHash = uint64FromHashAndLength(hash, length);
202 if (hashFromUint64(lengthAndHash) != hash) {
203 return false;
204 }
205 if (lengthFromUint64(lengthAndHash) != length) {
206 return false;
207 }
208 }
209 }
210
211 return true;
212 }
213
214 static constexpr MOZ_ALWAYS_INLINE uint64_t unsetValue() {
215 // This needs to be a combination of hash and length that would never occur
216 // together. There is only one string of length zero, and its hash is zero,
217 // so the hash here can be anything except zero.
218 return uint64FromHashAndLength(0xffffffff, 0);
219 }
220
221 private:
222 uint64_t mHashAndLength;
223
224 static constexpr MOZ_ALWAYS_INLINE uint64_t
225 uint64FromHashAndLength(HashNumber hash, uint32_t length) {
226 return (static_cast<uint64_t>(length) << 32) | hash;
227 }
228
229 static constexpr MOZ_ALWAYS_INLINE uint32_t
230 lengthFromUint64(uint64_t hashAndLength) {
231 return static_cast<uint32_t>(hashAndLength >> 32);
232 }
233
234 static constexpr MOZ_ALWAYS_INLINE HashNumber
235 hashFromUint64(uint64_t hashAndLength) {
236 return hashAndLength & 0xffffffff;
237 }
238 };
239
240 static_assert(HashAndLength::staticChecks());
241
242 // AtomCacheHashTable is a medium-capacity, low-overhead cache for matching
243 // strings to previously-added JSAtoms.
244 // This cache is very similar to a typical CPU memory cache. We use the low bits
245 // of the hash as an index into a table of sets of entries. Cache eviction
246 // follows a "least recently added" policy.
247 // All of the operations here are designed to be low-cost and efficient for
248 // modern CPU architectures. Failed lookups should incur at most one CPU memory
249 // cache miss and successful lookups should incur at most three (depending on
250 // whether or not the underlying chararacter buffers are already in the cache).
251 class AtomCacheHashTable {
252 public:
253 static MOZ_ALWAYS_INLINE constexpr uint32_t computeIndexFromHash(
254 const HashNumber hash) {
255 // Simply use the low bits of the hash value as the cache index.
256 return hash & (sSize - 1);
257 }
258
259 MOZ_ALWAYS_INLINE JSAtom* lookupForAdd(
260 const AtomHasher::Lookup& lookup) const {
261 MOZ_ASSERT(lookup.atom == nullptr, "Lookup by atom is not supported");
262
263 const uint32_t index = computeIndexFromHash(lookup.hash);
264
265 const EntrySet& entrySet = mEntrySets[index];
266 for (const Entry& entry : entrySet.mEntries) {
267 JSAtom* const atom = entry.mAtom;
268
269 if (!entry.mHashAndLength.isEqual(lookup.hash, lookup.length)) {
270 continue;
271 }
272
273 // This is annotated with MOZ_UNLIKELY because it virtually never happens
274 // that, after matching the hash and the length, the string isn't a match.
275 if (MOZ_UNLIKELY(!lookup.StringsMatch(*atom))) {
276 continue;
277 }
278
279 return atom;
280 }
281
282 return nullptr;
283 }
284
285 MOZ_ALWAYS_INLINE void add(const HashNumber hash, JSAtom* atom) {
286 const uint32_t index = computeIndexFromHash(hash);
287
288 mEntrySets[index].add(hash, atom->length(), atom);
289 }
290
291 private:
292 struct Entry {
293 MOZ_ALWAYS_INLINE Entry()
294 : mHashAndLength(HashAndLength::unsetValue()), mAtom(nullptr) {}
295
296 MOZ_ALWAYS_INLINE void set(const HashNumber hash, const uint32_t length,
297 JSAtom* const atom) {
298 mHashAndLength.set(hash, length);
299 mAtom = atom;
300 }
301
302 // Hash and length are also available, from JSAtom and JSString
303 // respectively, but are cached here to avoid likely cache misses in the
304 // frequent case of a missed lookup.
305 HashAndLength mHashAndLength;
306 // No read barrier is required here because the table is cleared at the
307 // start of GC.
308 JSAtom* mAtom;
309 };
310
311 static_assert(sizeof(Entry) <= 16);
312
313 // EntrySet represents a bundling of all of the Entry's that are mapped to the
314 // same index.
315 // NOTE/TODO: Since we have a tendency to use the entirety of this structure
316 // together, it would be really nice to mark this class with alignas(64) to
317 // ensure that the entire thing ends up on a single (hardware) cache line but
318 // we can't do that because AtomCacheHashTable is allocated with js::UniquePtr
319 // which doesn't support alignments greater than 8. In practice, on my Windows
320 // machine at least, I am seeing that these objects *are* 64-byte aligned, but
321 // it would be nice to guarantee that this will be the case.
322 struct EntrySet {
323 MOZ_ALWAYS_INLINE void add(const HashNumber hash, const uint32_t length,
324 JSAtom* const atom) {
325 MOZ_ASSERT(mEntries[0].mAtom != atom);
326 MOZ_ASSERT(mEntries[1].mAtom != atom);
327 MOZ_ASSERT(mEntries[2].mAtom != atom);
328 MOZ_ASSERT(mEntries[3].mAtom != atom);
329 mEntries[3] = mEntries[2];
330 mEntries[2] = mEntries[1];
331 mEntries[1] = mEntries[0];
332 mEntries[0].set(hash, length, atom);
333 }
334
335 std::array<Entry, 4> mEntries;
336 };
337
338 static_assert(sizeof(EntrySet) <= 64,
339 "EntrySet will not fit in a cache line");
340
341 // This value was picked empirically based on performance testing using SP2
342 // and SP3. 2k was better than 1k but 4k was not much better than 2k.
343 static constexpr uint32_t sSize = 2 * 1024;
344 static_assert(mozilla::IsPowerOfTwo(sSize));
345 std::array<EntrySet, sSize> mEntrySets;
346 };
347
348 } // namespace js
349
350 namespace JS {
351
352 // [SMDOC] GC Zones
353 //
354 // A zone is a collection of compartments. Every compartment belongs to exactly
355 // one zone. In Firefox, there is roughly one zone per tab along with a system
356 // zone for everything else. Zones mainly serve as boundaries for garbage
357 // collection. Unlike compartments, they have no special security properties.
358 //
359 // Every GC thing belongs to exactly one zone. GC things from the same zone but
360 // different compartments can share an arena (4k page). GC things from different
361 // zones cannot be stored in the same arena. The garbage collector is capable of
362 // collecting one zone at a time; it cannot collect at the granularity of
363 // compartments.
364 //
365 // GC things are tied to zones and compartments as follows:
366 //
367 // - JSObjects belong to a compartment and cannot be shared between
368 // compartments. If an object needs to point to a JSObject in a different
369 // compartment, regardless of zone, it must go through a cross-compartment
370 // wrapper. Each compartment keeps track of its outgoing wrappers in a table.
371 // JSObjects find their compartment via their ObjectGroup.
372 //
373 // - JSStrings do not belong to any particular compartment, but they do belong
374 // to a zone. Thus, two different compartments in the same zone can point to a
375 // JSString. When a string needs to be wrapped, we copy it if it's in a
376 // different zone and do nothing if it's in the same zone. Thus, transferring
377 // strings within a zone is very efficient.
378 //
379 // - Shapes and base shapes belong to a zone and are shared between compartments
380 // in that zone where possible. Accessor shapes store getter and setter
381 // JSObjects which belong to a single compartment, so these shapes and all
382 // their descendants can't be shared with other compartments.
383 //
384 // - Scripts are also compartment-local and cannot be shared. A script points to
385 // its compartment.
386 //
387 // - ObjectGroup and JitCode objects belong to a compartment and cannot be
388 // shared. There is no mechanism to obtain the compartment from a JitCode
389 // object.
390 //
391 // A zone remains alive as long as any GC things in the zone are alive. A
392 // compartment remains alive as long as any JSObjects, scripts, shapes, or base
393 // shapes within it are alive.
394 //
395 // We always guarantee that a zone has at least one live compartment by refusing
396 // to delete the last compartment in a live zone.
397 class Zone : public js::ZoneAllocator, public js::gc::GraphNodeBase<JS::Zone> {
398 public:
399 js::gc::ArenaLists arenas;
400
401 js::gc::BufferAllocator bufferAllocator;
402
403 // Per-zone data for use by an embedder.
404 js::MainThreadData<void*> data;
405
406 // When true, skip calling the metadata callback. We use this:
407 // - to avoid invoking the callback recursively;
408 // - to avoid observing lazy prototype setup (which confuses callbacks that
409 // want to use the types being set up!);
410 // - to avoid attaching allocation stacks to allocation stack nodes, which
411 // is silly
412 // And so on.
413 js::MainThreadData<bool> suppressAllocationMetadataBuilder;
414
415 // Flags permanently set when nursery allocation is disabled for this zone.
416 js::MainThreadData<bool> nurseryStringsDisabled;
417 js::MainThreadData<bool> nurseryBigIntsDisabled;
418
419 private:
420 // Flags dynamically updated based on more than one condition, including the
421 // flags above.
422 js::MainThreadOrIonCompileData<bool> allocNurseryObjects_;
423 js::MainThreadOrIonCompileData<bool> allocNurseryStrings_;
424 js::MainThreadOrIonCompileData<bool> allocNurseryBigInts_;
425
426 // Minimum Heap value which results in tenured allocation.
427 js::MainThreadData<js::gc::Heap> minObjectHeapToTenure_;
428 js::MainThreadData<js::gc::Heap> minStringHeapToTenure_;
429 js::MainThreadData<js::gc::Heap> minBigintHeapToTenure_;
430
431 public:
432 // Script side-tables. These used to be held by Realm, but are now placed
433 // here in order to allow JSScript to access them during finalize (see bug
434 // 1568245; this change in 1575350). The tables are initialized lazily by
435 // JSScript.
436 js::UniquePtr<js::ScriptCountsMap> scriptCountsMap;
437 js::UniquePtr<js::ScriptLCovMap> scriptLCovMap;
438 js::MainThreadData<js::DebugScriptMap*> debugScriptMap;
439 #ifdef MOZ_VTUNE
440 js::UniquePtr<js::ScriptVTuneIdMap> scriptVTuneIdMap;
441 #endif
442 #ifdef JS_CACHEIR_SPEW
443 js::UniquePtr<js::ScriptFinalWarmUpCountMap> scriptFinalWarmUpCountMap;
444 #endif
445
446 js::MainThreadData<js::StringStats> previousGCStringStats;
447 js::MainThreadData<js::StringStats> stringStats;
448
449 #ifdef DEBUG
450 js::MainThreadData<unsigned> gcSweepGroupIndex;
451 #endif
452
453 js::gc::PretenuringZone pretenuring;
454
455 private:
456 // Side map for storing unique ids for cells, independent of address.
457 js::MainThreadOrGCTaskData<js::gc::UniqueIdMap> uniqueIds_;
458
459 // Number of allocations since the most recent minor GC for this thread.
460 uint32_t tenuredAllocsSinceMinorGC_ = 0;
461
462 // Live weakmaps in this zone.
463 js::MainThreadOrGCTaskData<mozilla::LinkedList<js::WeakMapBase>>
464 gcWeakMapList_;
465
466 // The set of compartments in this zone.
467 using CompartmentVector =
468 js::Vector<JS::Compartment*, 1, js::SystemAllocPolicy>;
469 js::MainThreadOrGCTaskData<CompartmentVector> compartments_;
470
471 // All cross-zone string wrappers in the zone.
472 js::MainThreadOrGCTaskData<js::StringWrapperMap> crossZoneStringWrappers_;
473
474 // List of non-ephemeron weak containers to sweep during
475 // beginSweepingSweepGroup.
476 js::MainThreadOrGCTaskData<mozilla::LinkedList<detail::WeakCacheBase>>
477 weakCaches_;
478
479 // Mapping from not yet marked keys to a vector of all values that the key
480 // maps to in any live weak map. Separate tables for nursery and tenured
481 // keys.
482 js::MainThreadOrGCTaskData<js::gc::EphemeronEdgeTable> gcEphemeronEdges_;
483 js::MainThreadOrGCTaskData<js::gc::EphemeronEdgeTable>
484 gcNurseryEphemeronEdges_;
485
486 js::MainThreadData<js::UniquePtr<js::RegExpZone>> regExps_;
487
488 // Bitmap of atoms marked by this zone.
489 js::MainThreadOrGCTaskData<js::SparseBitmap> markedAtoms_;
490
491 // Set of atoms recently used by this Zone. Purged on GC.
492 js::MainThreadOrGCTaskData<js::UniquePtr<js::AtomCacheHashTable>> atomCache_;
493
494 // Cache storing allocated external strings. Purged on GC.
495 js::MainThreadOrGCTaskData<js::ExternalStringCache> externalStringCache_;
496
497 // Cache for Function.prototype.toString. Purged on GC.
498 js::MainThreadOrGCTaskData<js::FunctionToStringCache> functionToStringCache_;
499
500 // Cache for Function.prototype.bind mapping an atom `name` to atom
501 // `"bound " + name`. Purged on GC.
502 using BoundPrefixCache =
503 js::HashMap<JSAtom*, JSAtom*, js::PointerHasher<JSAtom*>,
504 js::SystemAllocPolicy>;
505 js::MainThreadData<BoundPrefixCache> boundPrefixCache_;
506
507 // Information about Shapes and BaseShapes.
508 js::MainThreadData<js::ShapeZone> shapeZone_;
509
510 // Information about finalization registries, created on demand.
511 js::MainThreadOrGCTaskData<js::UniquePtr<js::gc::FinalizationObservers>>
512 finalizationObservers_;
513
514 js::MainThreadOrGCTaskOrIonCompileData<js::jit::JitZone*> jitZone_;
515
516 // Number of realms in this zone that have a non-null object allocation
517 // metadata builder.
518 js::MainThreadOrIonCompileData<size_t> numRealmsWithAllocMetadataBuilder_{0};
519
520 // Last time at which JIT code was discarded for this zone. This is only set
521 // when JitScripts and Baseline code are discarded as well.
522 js::MainThreadData<mozilla::TimeStamp> lastDiscardedCodeTime_;
523
524 js::MainThreadData<bool> gcScheduled_;
525 js::MainThreadData<bool> gcScheduledSaved_;
526 js::MainThreadData<bool> gcPreserveCode_;
527 js::MainThreadData<bool> keepPropMapTables_;
528 js::MainThreadData<bool> wasCollected_;
529
530 // Allow zones to be linked into a list
531 js::MainThreadOrGCTaskData<Zone*> listNext_;
532 static Zone* const NotOnList;
533 friend class js::gc::ZoneList;
534
535 using KeptAliveSet =
536 JS::GCHashSet<js::HeapPtr<JSObject*>,
537 js::StableCellHasher<js::HeapPtr<JSObject*>>,
538 js::ZoneAllocPolicy>;
539 friend class js::WeakRefObject;
540 js::MainThreadOrGCTaskData<KeptAliveSet> keptObjects;
541
542 // To support weak pointers in some special cases we keep a list of objects
543 // that need to be traced weakly on GC. This is currently only used for the
544 // JIT's ShapeListObject. It's assumed that there will not be many of these
545 // objects.
546 using ObjectVector = js::GCVector<JSObject*, 0, js::SystemAllocPolicy>;
547 js::MainThreadOrGCTaskData<ObjectVector> objectsWithWeakPointers;
548
549 public:
550 #ifdef JS_GC_ZEAL
551 // Must come after weakCaches_ above.
552 js::UniquePtr<js::gc::MissingAllocSites> missingSites;
553 #endif // JS_GC_ZEAL
554
555 static JS::Zone* from(ZoneAllocator* zoneAlloc) {
556 return static_cast<Zone*>(zoneAlloc);
557 }
558
559 explicit Zone(JSRuntime* rt, Kind kind = NormalZone);
560 ~Zone();
561
562 [[nodiscard]] bool init();
563
564 void destroy(JS::GCContext* gcx);
565
566 [[nodiscard]] bool findSweepGroupEdges(Zone* atomsZone);
567
568 struct JitDiscardOptions {
569 JitDiscardOptions() {}
570 bool discardJitScripts = false;
571 bool resetNurseryAllocSites = false;
572 bool resetPretenuredAllocSites = false;
573 };
574
575 void maybeDiscardJitCode(JS::GCContext* gcx);
576
577 // Discard JIT code regardless of isPreservingCode().
578 void forceDiscardJitCode(
579 JS::GCContext* gcx,
580 const JitDiscardOptions& options = JitDiscardOptions());
581
582 void resetAllocSitesAndInvalidate(bool resetNurserySites,
583 bool resetPretenuredSites);
584
585 void traceWeakJitScripts(JSTracer* trc);
586
587 bool registerObjectWithWeakPointers(JSObject* obj);
588 void sweepObjectsWithWeakPointers(JSTracer* trc);
589
590 void addSizeOfIncludingThis(
591 mozilla::MallocSizeOf mallocSizeOf, size_t* zoneObject,
592 JS::CodeSizes* code, size_t* regexpZone, size_t* jitZone,
593 size_t* cacheIRStubs, size_t* uniqueIdMap, size_t* initialPropMapTable,
594 size_t* shapeTables, size_t* atomsMarkBitmaps, size_t* compartmentObjects,
595 size_t* crossCompartmentWrappersTables, size_t* compartmentsPrivateData,
596 size_t* scriptCountsMapArg);
597
598 // Iterate over all cells in the zone. See the definition of ZoneCellIter
599 // in gc/GC-inl.h for the possible arguments and documentation.
600 template <typename T, typename... Args>
601 js::gc::ZoneCellIter<T> cellIter(Args&&... args) {
602 return js::gc::ZoneCellIter<T>(const_cast<Zone*>(this),
603 std::forward<Args>(args)...);
604 }
605
606 // As above, but can return about-to-be-finalised things.
607 template <typename T, typename... Args>
608 js::gc::ZoneAllCellIter<T> cellIterUnsafe(Args&&... args) {
609 return js::gc::ZoneAllCellIter<T>(const_cast<Zone*>(this),
610 std::forward<Args>(args)...);
611 }
612
613 bool hasMarkedRealms();
614
615 void scheduleGC() {
616 MOZ_ASSERT(!RuntimeHeapIsBusy());
617 gcScheduled_ = true;
618 }
619 void unscheduleGC() { gcScheduled_ = false; }
620 bool isGCScheduled() { return gcScheduled_; }
621
622 void setPreservingCode(bool preserving) { gcPreserveCode_ = preserving; }
623 bool isPreservingCode() const { return gcPreserveCode_; }
624
625 mozilla::TimeStamp lastDiscardedCodeTime() const {
626 return lastDiscardedCodeTime_;
627 }
628
629 void changeGCState(GCState prev, GCState next);
630
631 bool isCollecting() const {
632 MOZ_ASSERT(js::CurrentThreadCanAccessRuntime(runtimeFromMainThread()));
633 return isCollectingFromAnyThread();
634 }
635
636 inline bool isCollectingFromAnyThread() const {
637 return needsIncrementalBarrier() || wasGCStarted();
638 }
639
640 GCState initialMarkingState() const;
641
642 bool shouldMarkInZone(js::gc::MarkColor color) const {
643 // Check whether the zone is in one or both of the MarkBlackOnly and
644 // MarkBlackAndGray states, depending on the mark color. Also check for
645 // VerifyPreBarriers when the mark color is black (we don't do any gray
646 // marking when verifying pre-barriers).
647 if (color == js::gc::MarkColor::Black) {
648 return isGCMarkingOrVerifyingPreBarriers();
649 }
650
651 return isGCMarkingBlackAndGray();
652 }
653
654 // Was this zone collected in the last GC.
655 bool wasCollected() const { return wasCollected_; }
656 void setWasCollected(bool v) { wasCollected_ = v; }
657
658 void setNeedsIncrementalBarrier(bool needs);
659 const BarrierState* addressOfNeedsIncrementalBarrier() const {
660 return &needsIncrementalBarrier_;
661 }
662
663 static constexpr size_t offsetOfNeedsIncrementalBarrier() {
664 return offsetof(Zone, needsIncrementalBarrier_);
665 }
666 static constexpr size_t offsetOfJitZone() { return offsetof(Zone, jitZone_); }
667
668 js::jit::JitZone* getJitZone(JSContext* cx) {
669 return jitZone_ ? jitZone_ : createJitZone(cx);
670 }
671 js::jit::JitZone* jitZone() { return jitZone_; }
672
673 bool ensureJitZoneExists(JSContext* cx) { return !!getJitZone(cx); }
674
675 void incNumRealmsWithAllocMetadataBuilder() {
676 numRealmsWithAllocMetadataBuilder_++;
677 }
678 void decNumRealmsWithAllocMetadataBuilder() {
679 MOZ_ASSERT(numRealmsWithAllocMetadataBuilder_ > 0);
680 numRealmsWithAllocMetadataBuilder_--;
681 }
682 bool hasRealmWithAllocMetadataBuilder() const {
683 return numRealmsWithAllocMetadataBuilder_ > 0;
684 }
685
686 void traceRootsInMajorGC(JSTracer* trc);
687
688 void sweepAfterMinorGC(JSTracer* trc);
689 void sweepUniqueIds();
690 void sweepCompartments(JS::GCContext* gcx, bool keepAtleastOne,
691 bool destroyingRuntime);
692
693 // Remove dead weak maps from gcWeakMapList_ and remove entries from the
694 // remaining weak maps whose keys are dead.
695 void sweepWeakMaps(JSTracer* trc);
696
697 // Trace all weak maps in this zone. Used to update edges after a moving GC.
698 void traceWeakMaps(JSTracer* trc);
699
700 js::gc::UniqueIdMap& uniqueIds() { return uniqueIds_.ref(); }
701
702 void notifyObservingDebuggers();
703
704 void noteTenuredAlloc() { tenuredAllocsSinceMinorGC_++; }
705
706 uint32_t* addressOfTenuredAllocCount() { return &tenuredAllocsSinceMinorGC_; }
707
708 uint32_t getAndResetTenuredAllocsSinceMinorGC() {
709 uint32_t res = tenuredAllocsSinceMinorGC_;
710 tenuredAllocsSinceMinorGC_ = 0;
711 return res;
712 }
713
714 mozilla::LinkedList<js::WeakMapBase>& gcWeakMapList() {
715 return gcWeakMapList_.ref();
716 }
717
718 CompartmentVector& compartments() { return compartments_.ref(); }
719
720 js::StringWrapperMap& crossZoneStringWrappers() {
721 return crossZoneStringWrappers_.ref();
722 }
723 const js::StringWrapperMap& crossZoneStringWrappers() const {
724 return crossZoneStringWrappers_.ref();
725 }
726
727 void dropStringWrappersOnGC();
728
729 void traceWeakCCWEdges(JSTracer* trc);
730 static void fixupAllCrossCompartmentWrappersAfterMovingGC(JSTracer* trc);
731
732 void prepareForMovingGC();
733 void fixupAfterMovingGC();
734
735 void fixupScriptMapsAfterMovingGC(JSTracer* trc);
736
737 void setNurseryAllocFlags(bool allocObjects, bool allocStrings,
738 bool allocBigInts);
739
740 bool allocKindInNursery(JS::TraceKind kind) const {
741 switch (kind) {
742 case JS::TraceKind::Object:
743 return allocNurseryObjects_;
744 case JS::TraceKind::String:
745 return allocNurseryStrings_;
746 case JS::TraceKind::BigInt:
747 return allocNurseryBigInts_;
748 default:
749 MOZ_CRASH("Unsupported kind for nursery allocation");
750 }
751 }
752 bool allocNurseryObjects() const { return allocNurseryObjects_; }
753
754 // Note that this covers both allocating JSStrings themselves in the nursery,
755 // as well as (possibly) the character data.
756 bool allocNurseryStrings() const { return allocNurseryStrings_; }
757
758 bool allocNurseryBigInts() const { return allocNurseryBigInts_; }
759
760 js::gc::Heap minHeapToTenure(JS::TraceKind kind) const {
761 switch (kind) {
762 case JS::TraceKind::Object:
763 return minObjectHeapToTenure_;
764 case JS::TraceKind::String:
765 return minStringHeapToTenure_;
766 case JS::TraceKind::BigInt:
767 return minBigintHeapToTenure_;
768 default:
769 MOZ_CRASH("Unsupported kind for nursery allocation");
770 }
771 }
772
773 mozilla::LinkedList<detail::WeakCacheBase>& weakCaches() {
774 return weakCaches_.ref();
775 }
776 void registerWeakCache(detail::WeakCacheBase* cachep) {
777 weakCaches().insertBack(cachep);
778 }
779
780 void beforeClearDelegate(JSObject* wrapper, JSObject* delegate) {
781 if (needsIncrementalBarrier()) {
782 beforeClearDelegateInternal(wrapper, delegate);
783 }
784 }
785
786 void beforeClearDelegateInternal(JSObject* wrapper, JSObject* delegate);
787 js::gc::EphemeronEdgeTable& gcEphemeronEdges() {
788 return gcEphemeronEdges_.ref();
789 }
790 js::gc::EphemeronEdgeTable& gcNurseryEphemeronEdges() {
791 return gcNurseryEphemeronEdges_.ref();
792 }
793
794 js::gc::EphemeronEdgeTable& gcEphemeronEdges(const js::gc::Cell* cell) {
795 return cell->isTenured() ? gcEphemeronEdges() : gcNurseryEphemeronEdges();
796 }
797
798 // Perform all pending weakmap entry marking for this zone after
799 // transitioning to weak marking mode.
800 js::gc::IncrementalProgress enterWeakMarkingMode(js::GCMarker* marker,
801 JS::SliceBudget& budget);
802
803 // A set of edges from this zone to other zones used during GC to calculate
804 // sweep groups.
805 NodeSet& gcSweepGroupEdges() {
806 return gcGraphEdges; // Defined in GraphNodeBase base class.
807 }
808 bool hasSweepGroupEdgeTo(Zone* otherZone) const {
809 return gcGraphEdges.has(otherZone);
810 }
811 [[nodiscard]] bool addSweepGroupEdgeTo(Zone* otherZone) {
812 MOZ_ASSERT(otherZone->isGCMarking());
813 return gcSweepGroupEdges().put(otherZone);
814 }
815 void clearSweepGroupEdges() { gcSweepGroupEdges().clear(); }
816
817 js::RegExpZone& regExps() { return *regExps_.ref(); }
818
819 js::SparseBitmap& markedAtoms() { return markedAtoms_.ref(); }
820
821 // The atom cache is "allocate-on-demand". This function can return nullptr if
822 // the allocation failed.
823 js::AtomCacheHashTable* atomCache() {
824 if (atomCache_.ref()) {
825 return atomCache_.ref().get();
826 }
827
828 atomCache_ = js::MakeUnique<js::AtomCacheHashTable>();
829 return atomCache_.ref().get();
830 }
831
832 void purgeAtomCache();
833
834 js::ExternalStringCache& externalStringCache() {
835 return externalStringCache_.ref();
836 };
837
838 js::FunctionToStringCache& functionToStringCache() {
839 return functionToStringCache_.ref();
840 }
841
842 BoundPrefixCache& boundPrefixCache() { return boundPrefixCache_.ref(); }
843
844 js::ShapeZone& shapeZone() { return shapeZone_.ref(); }
845
846 bool keepPropMapTables() const { return keepPropMapTables_; }
847 void setKeepPropMapTables(bool b) { keepPropMapTables_ = b; }
848
849 void clearRootsForShutdownGC();
850 void finishRoots();
851
852 void traceScriptTableRoots(JSTracer* trc);
853
854 void clearScriptCounts(Realm* realm);
855 void clearScriptLCov(Realm* realm);
856
857 // Add the target of JS WeakRef to a kept-alive set maintained by GC.
858 // https://tc39.es/ecma262/#sec-addtokeptobjects
859 bool addToKeptObjects(HandleObject target);
860
861 void traceKeptObjects(JSTracer* trc);
862
863 // Clear the kept-alive set.
864 // See: https://tc39.es/proposal-weakrefs/#sec-clear-kept-objects
865 void clearKeptObjects();
866
867 js::gc::AllocSite* unknownAllocSite(JS::TraceKind kind) {
868 return &pretenuring.unknownAllocSite(kind);
869 }
870 js::gc::AllocSite* optimizedAllocSite() {
871 return &pretenuring.optimizedAllocSite;
872 }
873 js::gc::AllocSite* tenuringAllocSite() {
874 return &pretenuring.tenuringAllocSite;
875 }
876 uint32_t nurseryPromotedCount(JS::TraceKind kind) const {
877 return pretenuring.nurseryPromotedCount(kind);
878 }
879
880 #ifdef JSGC_HASH_TABLE_CHECKS
881 void checkAllCrossCompartmentWrappersAfterMovingGC();
882 void checkStringWrappersAfterMovingGC();
883
884 // Assert that the UniqueId table has been redirected successfully.
885 void checkUniqueIdTableAfterMovingGC();
886
887 void checkScriptMapsAfterMovingGC();
888 #endif
889
890 #ifdef DEBUG
891 // For testing purposes, return the index of the sweep group which this zone
892 // was swept in in the last GC.
893 unsigned lastSweepGroupIndex() { return gcSweepGroupIndex; }
894 #endif
895
896 // Support for invalidating fuses
897 js::DependentScriptGroup fuseDependencies;
898
899 private:
900 js::jit::JitZone* createJitZone(JSContext* cx);
901
902 bool isQueuedForBackgroundSweep() { return isOnList(); }
903
904 void sweepEphemeronTablesAfterMinorGC();
905
906 js::gc::FinalizationObservers* finalizationObservers() {
907 return finalizationObservers_.ref().get();
908 }
909 bool ensureFinalizationObservers();
910
911 bool isOnList() const;
912 Zone* nextZone() const;
913
914 friend bool js::CurrentThreadCanAccessZone(Zone* zone);
915 friend class js::gc::GCRuntime;
916 };
917
918 } // namespace JS
919
920 namespace js::gc {
921 const char* StateName(JS::Zone::GCState state);
922 } // namespace js::gc
923
924 #endif // gc_Zone_h