Debian Codegraph @

js/src/gc/Zone.cpp

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 #include "gc/Zone.h"
8 #include "js/shadow/Zone.h" // JS::shadow::Zone
9
10 #include "mozilla/Sprintf.h"
11 #include "mozilla/TimeStamp.h"
12
13 #include <type_traits>
14
15 #include "gc/FinalizationObservers.h"
16 #include "gc/GCContext.h"
17 #include "gc/PublicIterators.h"
18 #include "jit/BaselineIC.h"
19 #include "jit/BaselineJIT.h"
20 #include "jit/Invalidation.h"
21 #include "jit/JitScript.h"
22 #include "jit/JitZone.h"
23 #include "vm/Runtime.h"
24 #include "vm/Time.h"
25
26 #include "debugger/DebugAPI-inl.h"
27 #include "gc/GC-inl.h"
28 #include "gc/Marking-inl.h"
29 #include "gc/Nursery-inl.h"
30 #include "gc/StableCellHasher-inl.h"
31 #include "gc/WeakMap-inl.h"
32 #include "vm/JSScript-inl.h"
33 #include "vm/Realm-inl.h"
34
35 using namespace js;
36 using namespace js::gc;
37
38 Zone* const Zone::NotOnList = reinterpret_cast<Zone*>(1);
39
40 ZoneAllocator::ZoneAllocator(JSRuntime* rt, Kind kind)
41 : JS::shadow::Zone(rt, rt->gc.marker().tracer(), kind),
42 jitHeapThreshold(size_t(jit::MaxCodeBytesPerProcess * 0.8)) {}
43
44 ZoneAllocator::~ZoneAllocator() {
45 #ifdef DEBUG
46 mallocTracker.checkEmptyOnDestroy();
47 MOZ_ASSERT(gcHeapSize.bytes() == 0);
48 MOZ_ASSERT(mallocHeapSize.bytes() == 0);
49 MOZ_ASSERT(jitHeapSize.bytes() == 0);
50 #endif
51 }
52
53 void ZoneAllocator::fixupAfterMovingGC() {
54 #ifdef DEBUG
55 mallocTracker.fixupAfterMovingGC();
56 #endif
57 }
58
59 void js::ZoneAllocator::updateSchedulingStateOnGCStart() {
60 gcHeapSize.updateOnGCStart();
61 mallocHeapSize.updateOnGCStart();
62 jitHeapSize.updateOnGCStart();
63 perZoneGCTime = mozilla::TimeDuration::Zero();
64 }
65
66 void js::ZoneAllocator::updateGCStartThresholds(GCRuntime& gc) {
67 bool isAtomsZone = JS::Zone::from(this)->isAtomsZone();
68 gcHeapThreshold.updateStartThreshold(
69 gcHeapSize.retainedBytes(), smoothedAllocationRate.ref(),
70 smoothedCollectionRate.ref(), gc.tunables, gc.schedulingState,
71 isAtomsZone);
72
73 mallocHeapThreshold.updateStartThreshold(mallocHeapSize.retainedBytes(),
74 gc.tunables, gc.schedulingState);
75 }
76
77 void js::ZoneAllocator::setGCSliceThresholds(GCRuntime& gc,
78 bool waitingOnBGTask) {
79 gcHeapThreshold.setSliceThreshold(this, gcHeapSize, gc.tunables,
80 waitingOnBGTask);
81 mallocHeapThreshold.setSliceThreshold(this, mallocHeapSize, gc.tunables,
82 waitingOnBGTask);
83 jitHeapThreshold.setSliceThreshold(this, jitHeapSize, gc.tunables,
84 waitingOnBGTask);
85 }
86
87 void js::ZoneAllocator::clearGCSliceThresholds() {
88 gcHeapThreshold.clearSliceThreshold();
89 mallocHeapThreshold.clearSliceThreshold();
90 jitHeapThreshold.clearSliceThreshold();
91 }
92
93 bool ZoneAllocator::addSharedMemory(void* mem, size_t nbytes, MemoryUse use) {
94 // nbytes can be zero here for SharedArrayBuffers.
95
96 MOZ_ASSERT(CurrentThreadCanAccessRuntime(runtime_));
97
98 auto ptr = sharedMemoryUseCounts.lookupForAdd(mem);
99 MOZ_ASSERT_IF(ptr, ptr->value().use == use);
100
101 if (!ptr && !sharedMemoryUseCounts.add(ptr, mem, gc::SharedMemoryUse(use))) {
102 return false;
103 }
104
105 ptr->value().count++;
106
107 // Allocations can grow, so add any increase over the previous size and record
108 // the new size.
109 if (nbytes > ptr->value().nbytes) {
110 mallocHeapSize.addBytes(nbytes - ptr->value().nbytes);
111 ptr->value().nbytes = nbytes;
112 }
113
114 maybeTriggerGCOnMalloc();
115
116 return true;
117 }
118
119 void ZoneAllocator::removeSharedMemory(void* mem, size_t nbytes,
120 MemoryUse use) {
121 // nbytes can be zero here for SharedArrayBuffers.
122
123 MOZ_ASSERT(CurrentThreadCanAccessRuntime(runtime_));
124 MOZ_ASSERT(CurrentThreadIsGCFinalizing());
125
126 auto ptr = sharedMemoryUseCounts.lookup(mem);
127
128 MOZ_ASSERT(ptr);
129 MOZ_ASSERT(ptr->value().count != 0);
130 MOZ_ASSERT(ptr->value().use == use);
131 MOZ_ASSERT(ptr->value().nbytes >= nbytes);
132
133 ptr->value().count--;
134 if (ptr->value().count == 0) {
135 mallocHeapSize.removeBytes(ptr->value().nbytes, true);
136 sharedMemoryUseCounts.remove(ptr);
137 }
138 }
139
140 template <TrackingKind kind>
141 void js::TrackedAllocPolicy<kind>::decMemory(size_t nbytes) {
142 bool updateRetainedSize = false;
143 if constexpr (kind == TrackingKind::Cell) {
144 // Only subtract freed cell memory from retained size for cell associations
145 // during sweeping.
146 JS::GCContext* gcx = TlsGCContext.get();
147 updateRetainedSize = gcx->isFinalizing();
148 }
149
150 zone_->decNonGCMemory(this, nbytes, MemoryUse::TrackedAllocPolicy,
151 updateRetainedSize);
152 }
153
154 namespace js {
155 template class TrackedAllocPolicy<TrackingKind::Zone>;
156 template class TrackedAllocPolicy<TrackingKind::Cell>;
157 } // namespace js
158
159 JS::Zone::Zone(JSRuntime* rt, Kind kind)
160 : ZoneAllocator(rt, kind),
161 arenas(this),
162 bufferAllocator(this),
163 data(nullptr),
164 suppressAllocationMetadataBuilder(false),
165 allocNurseryObjects_(true),
166 allocNurseryStrings_(true),
167 allocNurseryBigInts_(true),
168 pretenuring(this),
169 crossZoneStringWrappers_(this),
170 shapeZone_(this),
171 gcScheduled_(false),
172 gcScheduledSaved_(false),
173 gcPreserveCode_(false),
174 keepPropMapTables_(false),
175 wasCollected_(false),
176 listNext_(NotOnList),
177 keptObjects(this) {
178 /* Ensure that there are no vtables to mess us up here. */
179 MOZ_ASSERT(reinterpret_cast<JS::shadow::Zone*>(this) ==
180 static_cast<JS::shadow::Zone*>(this));
181 MOZ_ASSERT_IF(isAtomsZone(), rt->gc.zones().empty());
182
183 updateGCStartThresholds(rt->gc);
184 rt->gc.nursery().setAllocFlagsForZone(this);
185 }
186
187 Zone::~Zone() {
188 MOZ_ASSERT_IF(regExps_.ref(), regExps().empty());
189
190 MOZ_ASSERT(numRealmsWithAllocMetadataBuilder_ == 0);
191
192 DebugAPI::deleteDebugScriptMap(debugScriptMap);
193 js_delete(finalizationObservers_.ref().release());
194
195 MOZ_ASSERT(gcWeakMapList().isEmpty());
196 MOZ_ASSERT(objectsWithWeakPointers.ref().empty());
197
198 JSRuntime* rt = runtimeFromAnyThread();
199 if (this == rt->gc.systemZone) {
200 MOZ_ASSERT(isSystemZone());
201 rt->gc.systemZone = nullptr;
202 }
203
204 js_delete(jitZone_.ref());
205 }
206
207 bool Zone::init() {
208 regExps_.ref() = make_unique<RegExpZone>(this);
209 return !!regExps_.ref();
210 }
211
212 void Zone::setNeedsIncrementalBarrier(bool needs) {
213 needsIncrementalBarrier_ = needs;
214 }
215
216 void Zone::changeGCState(GCState prev, GCState next) {
217 MOZ_ASSERT(RuntimeHeapIsBusy());
218 MOZ_ASSERT(gcState() == prev);
219
220 // This can be called when barriers have been temporarily disabled by
221 // AutoDisableBarriers. In that case, don't update needsIncrementalBarrier_
222 // and barriers will be re-enabled by ~AutoDisableBarriers() if necessary.
223 bool barriersDisabled = isGCMarking() && !needsIncrementalBarrier();
224
225 gcState_ = next;
226
227 // Update the barriers state when we transition between marking and
228 // non-marking states, unless barriers have been disabled.
229 if (!barriersDisabled) {
230 needsIncrementalBarrier_ = isGCMarking();
231 }
232 }
233
234 template <class Pred>
235 static void EraseIf(js::gc::EphemeronEdgeVector& entries, Pred pred) {
236 auto* begin = entries.begin();
237 auto* const end = entries.end();
238
239 auto* newEnd = begin;
240 for (auto* p = begin; p != end; p++) {
241 if (!pred(*p)) {
242 *newEnd++ = *p;
243 }
244 }
245
246 size_t removed = end - newEnd;
247 entries.shrinkBy(removed);
248 }
249
250 static void SweepEphemeronEdgesWhileMinorSweeping(
251 js::gc::EphemeronEdgeVector& entries) {
252 EraseIf(entries, [](js::gc::EphemeronEdge& edge) -> bool {
253 return IsAboutToBeFinalizedDuringMinorSweep(&edge.target);
254 });
255 }
256
257 void Zone::sweepAfterMinorGC(JSTracer* trc) {
258 sweepEphemeronTablesAfterMinorGC();
259 crossZoneStringWrappers().sweepAfterMinorGC(trc);
260
261 for (CompartmentsInZoneIter comp(this); !comp.done(); comp.next()) {
262 comp->sweepAfterMinorGC(trc);
263 }
264 }
265
266 void Zone::sweepEphemeronTablesAfterMinorGC() {
267 for (auto r = gcNurseryEphemeronEdges().all(); !r.empty(); r.popFront()) {
268 // Sweep gcNurseryEphemeronEdges to move live (forwarded) keys to
269 // gcEphemeronEdges, scanning through all the entries for such keys to
270 // update them.
271 //
272 // Forwarded and dead keys may also appear in their delegates' entries,
273 // so sweep those too (see below.)
274
275 // The tricky case is when the key has a delegate that was already
276 // tenured. Then it will be in its compartment's gcEphemeronEdges, but we
277 // still need to update the key (which will be in the entries
278 // associated with it.)
279 gc::Cell* key = r.front().key();
280 MOZ_ASSERT(!key->isTenured());
281 if (!Nursery::getForwardedPointer(&key)) {
282 // Dead nursery cell => discard.
283 continue;
284 }
285
286 // Key been moved. The value is an array of <color,cell> pairs; update all
287 // cells in that array.
288 EphemeronEdgeVector& entries = r.front().value();
289 SweepEphemeronEdgesWhileMinorSweeping(entries);
290
291 // Live (moved) nursery cell. Append entries to gcEphemeronEdges.
292 EphemeronEdgeTable& tenuredEdges = gcEphemeronEdges();
293 AutoEnterOOMUnsafeRegion oomUnsafe;
294 auto entry = tenuredEdges.lookupForAdd(key);
295 if (!entry) {
296 if (!tenuredEdges.add(entry, key, EphemeronEdgeVector())) {
297 oomUnsafe.crash("Failed to tenure weak keys entry");
298 }
299 }
300 if (!entry->value().appendAll(entries)) {
301 oomUnsafe.crash("Failed to tenure weak keys entry");
302 }
303
304 // If the key has a delegate, then it will map to a WeakKeyEntryVector
305 // containing the key that needs to be updated.
306
307 JSObject* delegate = gc::detail::GetDelegate(key->as<JSObject>());
308 if (!delegate) {
309 continue;
310 }
311 MOZ_ASSERT(delegate->isTenured());
312
313 // If delegate was formerly nursery-allocated, we will sweep its entries
314 // when we visit its gcNurseryEphemeronEdges (if we haven't already). Note
315 // that we don't know the nursery address of the delegate, since the
316 // location it was stored in has already been updated.
317 //
318 // Otherwise, it will be in gcEphemeronEdges and we sweep it here.
319 auto p = delegate->zone()->gcEphemeronEdges().lookup(delegate);
320 if (p) {
321 SweepEphemeronEdgesWhileMinorSweeping(p->value());
322 }
323 }
324
325 gcNurseryEphemeronEdges().clearAndCompact();
326 }
327
328 void Zone::traceWeakCCWEdges(JSTracer* trc) {
329 crossZoneStringWrappers().traceWeak(trc);
330 for (CompartmentsInZoneIter comp(this); !comp.done(); comp.next()) {
331 comp->traceCrossCompartmentObjectWrapperEdges(trc);
332 }
333 }
334
335 /* static */
336 void Zone::fixupAllCrossCompartmentWrappersAfterMovingGC(JSTracer* trc) {
337 MOZ_ASSERT(trc->runtime()->gc.isHeapCompacting());
338
339 for (ZonesIter zone(trc->runtime(), WithAtoms); !zone.done(); zone.next()) {
340 // Trace the wrapper map to update keys (wrapped values) in other
341 // compartments that may have been moved.
342 zone->crossZoneStringWrappers().traceWeak(trc);
343
344 for (CompartmentsInZoneIter comp(zone); !comp.done(); comp.next()) {
345 comp->fixupCrossCompartmentObjectWrappersAfterMovingGC(trc);
346 }
347 }
348 }
349
350 void Zone::dropStringWrappersOnGC() {
351 MOZ_ASSERT(JS::RuntimeHeapIsCollecting());
352 crossZoneStringWrappers().clear();
353 }
354
355 #ifdef JSGC_HASH_TABLE_CHECKS
356
357 void Zone::checkAllCrossCompartmentWrappersAfterMovingGC() {
358 checkStringWrappersAfterMovingGC();
359 for (CompartmentsInZoneIter comp(this); !comp.done(); comp.next()) {
360 comp->checkObjectWrappersAfterMovingGC();
361 }
362 }
363
364 void Zone::checkStringWrappersAfterMovingGC() {
365 CheckTableAfterMovingGC(crossZoneStringWrappers(), [this](const auto& entry) {
366 JSString* key = entry.key().get();
367 CheckGCThingAfterMovingGC(key); // Keys may be in a different zone.
368 CheckGCThingAfterMovingGC(entry.value().unbarrieredGet(), this);
369 return key;
370 });
371 }
372 #endif
373
374 void Zone::maybeDiscardJitCode(JS::GCContext* gcx) {
375 if (!isPreservingCode()) {
376 forceDiscardJitCode(gcx);
377 }
378 }
379
380 void Zone::forceDiscardJitCode(JS::GCContext* gcx,
381 const JitDiscardOptions& options) {
382 if (!jitZone()) {
383 return;
384 }
385
386 if (options.discardJitScripts) {
387 lastDiscardedCodeTime_ = mozilla::TimeStamp::Now();
388 }
389
390 // Copy Baseline IC stubs that are active on the stack to a new LifoAlloc.
391 // After freeing stub memory, these chunks are then transferred to the
392 // zone-wide allocator.
393 jit::ICStubSpace newStubSpace;
394
395 #ifdef DEBUG
396 // Assert no ICScripts are marked as active.
397 jitZone()->forEachJitScript([](jit::JitScript* jitScript) {
398 MOZ_ASSERT(!jitScript->hasActiveICScript());
399 });
400 #endif
401
402 // Mark ICScripts on the stack as active and copy active Baseline stubs.
403 jit::MarkActiveICScriptsAndCopyStubs(this, newStubSpace);
404
405 // Invalidate all Ion code in this zone.
406 jit::InvalidateAll(gcx, this);
407
408 jitZone()->forEachJitScript<jit::IncludeDyingScripts>(
409 [&](jit::JitScript* jitScript) {
410 JSScript* script = jitScript->owningScript();
411 jit::FinishInvalidation(gcx, script);
412
413 // Discard baseline script if it's not marked as active.
414 if (jitScript->hasBaselineScript() &&
415 !jitScript->icScript()->active()) {
416 jit::FinishDiscardBaselineScript(gcx, script);
417 }
418
419 #ifdef JS_CACHEIR_SPEW
420 maybeUpdateWarmUpCount(script);
421 #endif
422
423 // Warm-up counter for scripts are reset on GC. After discarding code we
424 // need to let it warm back up to get information such as which
425 // opcodes are setting array holes or accessing getter properties.
426 script->resetWarmUpCounterForGC();
427
428 // Try to release the script's JitScript. This should happen after
429 // releasing JIT code because we can't do this when the script still has
430 // JIT code.
431 if (options.discardJitScripts) {
432 script->maybeReleaseJitScript(gcx);
433 jitScript = script->maybeJitScript();
434 if (!jitScript) {
435 // If we successfully discarded the JIT script, try to discard the
436 // ScriptCounts too.
437 if (!script->realm()->collectCoverageForDebug() &&
438 !gcx->runtime()->profilingScripts) {
439 script->destroyScriptCounts();
440 }
441 script->realm()->removeFromCompileQueue(script);
442 return; // Continue script loop.
443 }
444 }
445
446 // If we did not release the JitScript, we need to purge IC stubs
447 // because the ICStubSpace will be purged below. Also purge all
448 // trial-inlined ICScripts that are not active on the stack.
449 jitScript->purgeInactiveICScripts();
450 jitScript->purgeStubs(script, newStubSpace);
451
452 if (options.resetNurseryAllocSites ||
453 options.resetPretenuredAllocSites) {
454 jitScript->resetAllocSites(options.resetNurseryAllocSites,
455 options.resetPretenuredAllocSites);
456 }
457
458 // Reset the active flag of each ICScript.
459 jitScript->resetAllActiveFlags();
460 });
461
462 // Also clear references to jit code from RegExpShared cells at this point.
463 // This avoid holding onto ExecutablePools.
464 for (auto regExp = cellIterUnsafe<RegExpShared>(); !regExp.done();
465 regExp.next()) {
466 regExp->discardJitCode();
467 }
468
469 /*
470 * When scripts contain pointers to nursery things, the store buffer
471 * can contain entries that point into the optimized stub space. Since
472 * this method can be called outside the context of a GC, this situation
473 * could result in us trying to mark invalid store buffer entries.
474 *
475 * Defer freeing any allocated blocks until after the next minor GC.
476 */
477 jitZone()->stubSpace()->freeAllAfterMinorGC(this);
478 jitZone()->stubSpace()->transferFrom(newStubSpace);
479 jitZone()->purgeIonCacheIRStubInfo();
480
481 // Generate a profile marker
482 if (gcx->runtime()->geckoProfiler().enabled()) {
483 char discardingJitScript = options.discardJitScripts ? 'Y' : 'N';
484 char discardingBaseline = 'Y';
485 char discardingIon = 'Y';
486
487 char discardingRegExp = 'Y';
488 char discardingNurserySites = options.resetNurseryAllocSites ? 'Y' : 'N';
489 char discardingPretenuredSites =
490 options.resetPretenuredAllocSites ? 'Y' : 'N';
491
492 char buf[100];
493 SprintfLiteral(buf,
494 "JitScript:%c Baseline:%c Ion:%c "
495 "RegExp:%c NurserySites:%c PretenuredSites:%c",
496 discardingJitScript, discardingBaseline, discardingIon,
497 discardingRegExp, discardingNurserySites,
498 discardingPretenuredSites);
499 gcx->runtime()->geckoProfiler().markEvent("DiscardJit", buf);
500 }
501 }
502
503 void JS::Zone::resetAllocSitesAndInvalidate(bool resetNurserySites,
504 bool resetPretenuredSites) {
505 MOZ_ASSERT(resetNurserySites || resetPretenuredSites);
506
507 if (!jitZone()) {
508 return;
509 }
510
511 JSContext* cx = runtime_->mainContextFromOwnThread();
512 jitZone()->forEachJitScript<jit::IncludeDyingScripts>(
513 [&](jit::JitScript* jitScript) {
514 if (jitScript->resetAllocSites(resetNurserySites,
515 resetPretenuredSites)) {
516 JSScript* script = jitScript->owningScript();
517 CancelOffThreadIonCompile(script);
518 if (script->hasIonScript()) {
519 jit::Invalidate(cx, script,
520 /* resetUses = */ true,
521 /* cancelOffThread = */ true);
522 }
523 }
524 });
525 }
526
527 void JS::Zone::traceWeakJitScripts(JSTracer* trc) {
528 if (jitZone()) {
529 jitZone()->forEachJitScript(
530 [&](jit::JitScript* jitScript) { jitScript->traceWeak(trc); });
531 }
532 }
533
534 void JS::Zone::beforeClearDelegateInternal(JSObject* wrapper,
535 JSObject* delegate) {
536 // 'delegate' is no longer the delegate of 'wrapper'.
537 MOZ_ASSERT(js::gc::detail::GetDelegate(wrapper) == delegate);
538 MOZ_ASSERT(needsIncrementalBarrier());
539 MOZ_ASSERT(!RuntimeFromMainThreadIsHeapMajorCollecting(this));
540
541 // If |wrapper| might be a key in a weak map, trigger a barrier to account for
542 // the removal of the automatically added edge from delegate to wrapper.
543 if (HasUniqueId(wrapper)) {
544 PreWriteBarrier(wrapper);
545 }
546 }
547
548 #ifdef JSGC_HASH_TABLE_CHECKS
549 void JS::Zone::checkUniqueIdTableAfterMovingGC() {
550 CheckTableAfterMovingGC(uniqueIds(), [this](const auto& entry) {
551 js::gc::CheckGCThingAfterMovingGC(entry.key(), this);
552 return entry.key();
553 });
554 }
555 #endif
556
557 js::jit::JitZone* Zone::createJitZone(JSContext* cx) {
558 MOZ_ASSERT(!jitZone_);
559 #ifndef ENABLE_PORTABLE_BASELINE_INTERP
560 MOZ_ASSERT(cx->runtime()->hasJitRuntime());
561 #endif
562
563 auto jitZone = cx->make_unique<jit::JitZone>(cx, allocNurseryStrings());
564 if (!jitZone) {
565 return nullptr;
566 }
567
568 jitZone_ = jitZone.release();
569 return jitZone_;
570 }
571
572 bool Zone::hasMarkedRealms() {
573 for (RealmsInZoneIter realm(this); !realm.done(); realm.next()) {
574 if (realm->marked()) {
575 return true;
576 }
577 }
578 return false;
579 }
580
581 void Zone::notifyObservingDebuggers() {
582 AutoAssertNoGC nogc;
583 MOZ_ASSERT(JS::RuntimeHeapIsCollecting(),
584 "This method should be called during GC.");
585
586 JSRuntime* rt = runtimeFromMainThread();
587
588 for (RealmsInZoneIter realms(this); !realms.done(); realms.next()) {
589 GlobalObject* global = realms->unsafeUnbarrieredMaybeGlobal();
590 if (!global) {
591 continue;
592 }
593
594 DebugAPI::notifyParticipatesInGC(global, rt->gc.majorGCCount());
595 }
596 }
597
598 bool Zone::isOnList() const { return listNext_ != NotOnList; }
599
600 Zone* Zone::nextZone() const {
601 MOZ_ASSERT(isOnList());
602 return listNext_;
603 }
604
605 void Zone::prepareForMovingGC() {
606 JS::GCContext* gcx = runtimeFromMainThread()->gcContext();
607
608 MOZ_ASSERT(!isPreservingCode());
609 forceDiscardJitCode(gcx);
610
611 // We must always call fixupAfterMovingGC after this point.
612 bufferAllocator.prepareForMovingGC();
613 }
614
615 void Zone::fixupAfterMovingGC() {
616 ZoneAllocator::fixupAfterMovingGC();
617 shapeZone().fixupPropMapShapeTableAfterMovingGC();
618 bufferAllocator.fixupAfterMovingGC();
619 }
620
621 void Zone::purgeAtomCache() {
622 atomCache_.ref().reset();
623
624 // Also purge the dtoa caches so that subsequent lookups populate atom
625 // cache too.
626 for (RealmsInZoneIter r(this); !r.done(); r.next()) {
627 r->dtoaCache.purge();
628 }
629 }
630
631 void Zone::addSizeOfIncludingThis(
632 mozilla::MallocSizeOf mallocSizeOf, size_t* zoneObject, JS::CodeSizes* code,
633 size_t* regexpZone, size_t* jitZone, size_t* cacheIRStubs,
634 size_t* uniqueIdMap, size_t* initialPropMapTable, size_t* shapeTables,
635 size_t* atomsMarkBitmaps, size_t* compartmentObjects,
636 size_t* crossCompartmentWrappersTables, size_t* compartmentsPrivateData,
637 size_t* scriptCountsMapArg) {
638 *zoneObject += mallocSizeOf(this);
639 *regexpZone += regExps().sizeOfIncludingThis(mallocSizeOf);
640 if (jitZone_) {
641 jitZone_->addSizeOfIncludingThis(mallocSizeOf, code, jitZone, cacheIRStubs);
642 }
643 *uniqueIdMap += uniqueIds().shallowSizeOfExcludingThis(mallocSizeOf);
644 shapeZone().addSizeOfExcludingThis(mallocSizeOf, initialPropMapTable,
645 shapeTables);
646 *atomsMarkBitmaps += markedAtoms().sizeOfExcludingThis(mallocSizeOf);
647 *crossCompartmentWrappersTables +=
648 crossZoneStringWrappers().sizeOfExcludingThis(mallocSizeOf);
649
650 for (CompartmentsInZoneIter comp(this); !comp.done(); comp.next()) {
651 comp->addSizeOfIncludingThis(mallocSizeOf, compartmentObjects,
652 crossCompartmentWrappersTables,
653 compartmentsPrivateData);
654 }
655
656 if (scriptCountsMap) {
657 *scriptCountsMapArg +=
658 scriptCountsMap->shallowSizeOfIncludingThis(mallocSizeOf);
659 for (auto r = scriptCountsMap->all(); !r.empty(); r.popFront()) {
660 *scriptCountsMapArg +=
661 r.front().value()->sizeOfIncludingThis(mallocSizeOf);
662 }
663 }
664 }
665
666 void* ZoneAllocator::onOutOfMemory(js::AllocFunction allocFunc,
667 arena_id_t arena, size_t nbytes,
668 void* reallocPtr) {
669 if (!js::CurrentThreadCanAccessRuntime(runtime_)) {
670 return nullptr;
671 }
672 // The analysis sees that JSRuntime::onOutOfMemory could report an error,
673 // which with a JSErrorInterceptor could GC. But we're passing a null cx (to
674 // a default parameter) so the error will not be reported.
675 JS::AutoSuppressGCAnalysis suppress;
676 return runtimeFromMainThread()->onOutOfMemory(allocFunc, arena, nbytes,
677 reallocPtr);
678 }
679
680 void ZoneAllocator::reportAllocationOverflow() const {
681 js::ReportAllocationOverflow(static_cast<JSContext*>(nullptr));
682 }
683
684 ZoneList::ZoneList() : head(nullptr), tail(nullptr) {}
685
686 ZoneList::ZoneList(Zone* zone) : head(zone), tail(zone) {
687 MOZ_RELEASE_ASSERT(!zone->isOnList());
688 zone->listNext_ = nullptr;
689 }
690
691 ZoneList::~ZoneList() { MOZ_ASSERT(isEmpty()); }
692
693 void ZoneList::check() const {
694 #ifdef DEBUG
695 MOZ_ASSERT((head == nullptr) == (tail == nullptr));
696 if (!head) {
697 return;
698 }
699
700 Zone* zone = head;
701 for (;;) {
702 MOZ_ASSERT(zone && zone->isOnList());
703 if (zone == tail) break;
704 zone = zone->listNext_;
705 }
706 MOZ_ASSERT(!zone->listNext_);
707 #endif
708 }
709
710 bool ZoneList::isEmpty() const { return head == nullptr; }
711
712 Zone* ZoneList::front() const {
713 MOZ_ASSERT(!isEmpty());
714 MOZ_ASSERT(head->isOnList());
715 return head;
716 }
717
718 void ZoneList::prepend(Zone* zone) { prependList(ZoneList(zone)); }
719
720 void ZoneList::append(Zone* zone) { appendList(ZoneList(zone)); }
721
722 void ZoneList::prependList(ZoneList&& other) {
723 check();
724 other.check();
725
726 if (other.isEmpty()) {
727 return;
728 }
729
730 MOZ_ASSERT(tail != other.tail);
731
732 if (!isEmpty()) {
733 other.tail->listNext_ = head;
734 } else {
735 tail = other.tail;
736 }
737 head = other.head;
738
739 other.head = nullptr;
740 other.tail = nullptr;
741 }
742
743 void ZoneList::appendList(ZoneList&& other) {
744 check();
745 other.check();
746
747 if (other.isEmpty()) {
748 return;
749 }
750
751 MOZ_ASSERT(tail != other.tail);
752
753 if (!isEmpty()) {
754 tail->listNext_ = other.head;
755 } else {
756 head = other.head;
757 }
758 tail = other.tail;
759
760 other.head = nullptr;
761 other.tail = nullptr;
762 }
763
764 Zone* ZoneList::removeFront() {
765 MOZ_ASSERT(!isEmpty());
766 check();
767
768 Zone* front = head;
769 head = head->listNext_;
770 if (!head) {
771 tail = nullptr;
772 }
773
774 front->listNext_ = Zone::NotOnList;
775
776 return front;
777 }
778
779 void ZoneList::clear() {
780 while (!isEmpty()) {
781 removeFront();
782 }
783 }
784
785 JS_PUBLIC_API void JS::shadow::RegisterWeakCache(
786 JS::Zone* zone, detail::WeakCacheBase* cachep) {
787 zone->registerWeakCache(cachep);
788 }
789
790 void Zone::traceRootsInMajorGC(JSTracer* trc) {
791 if (trc->isMarkingTracer() && !isGCMarking()) {
792 return;
793 }
794
795 // Trace zone script-table roots. See comment below for justification re:
796 // calling this only during major (non-nursery) collections.
797 traceScriptTableRoots(trc);
798
799 if (FinalizationObservers* observers = finalizationObservers()) {
800 observers->traceRoots(trc);
801 }
802 }
803
804 void Zone::traceScriptTableRoots(JSTracer* trc) {
805 static_assert(std::is_convertible_v<BaseScript*, gc::TenuredCell*>,
806 "BaseScript must not be nursery-allocated for script-table "
807 "tracing to work");
808
809 // Performance optimization: the script-table keys are JSScripts, which
810 // cannot be in the nursery, so we can skip this tracing if we are only in a
811 // minor collection. We static-assert this fact above.
812 MOZ_ASSERT(!JS::RuntimeHeapIsMinorCollecting());
813
814 // N.B.: the script-table keys are weak *except* in an exceptional case: when
815 // then --dump-bytecode command line option or the PCCount JSFriend API is
816 // used, then the scripts for all counts must remain alive. We only trace
817 // when the `trc->runtime()->profilingScripts` flag is set. This flag is
818 // cleared in JSRuntime::destroyRuntime() during shutdown to ensure that
819 // scripts are collected before the runtime goes away completely.
820 if (scriptCountsMap && trc->runtime()->profilingScripts) {
821 for (ScriptCountsMap::Range r = scriptCountsMap->all(); !r.empty();
822 r.popFront()) {
823 BaseScript* script = r.front().key();
824 MOZ_ASSERT(script->hasScriptCounts());
825 TraceRoot(trc, &script, "profilingScripts");
826 }
827 }
828
829 // Trace the debugger's DebugScript weak map.
830 if (debugScriptMap) {
831 DebugAPI::traceDebugScriptMap(trc, debugScriptMap);
832 }
833 }
834
835 void Zone::fixupScriptMapsAfterMovingGC(JSTracer* trc) {
836 // Map entries are removed by BaseScript::finalize, but we need to update the
837 // script pointers here in case they are moved by the GC.
838
839 if (scriptCountsMap) {
840 scriptCountsMap->traceWeak(trc);
841 }
842
843 if (scriptLCovMap) {
844 scriptLCovMap->traceWeak(trc);
845 }
846
847 #ifdef MOZ_VTUNE
848 if (scriptVTuneIdMap) {
849 scriptVTuneIdMap->traceWeak(trc);
850 }
851 #endif
852
853 #ifdef JS_CACHEIR_SPEW
854 if (scriptFinalWarmUpCountMap) {
855 scriptFinalWarmUpCountMap->traceWeak(trc);
856 }
857 #endif
858 }
859
860 #ifdef JSGC_HASH_TABLE_CHECKS
861 void Zone::checkScriptMapsAfterMovingGC() {
862 // |debugScriptMap| is checked automatically because it is s a WeakMap.
863
864 if (scriptCountsMap) {
865 CheckTableAfterMovingGC(*scriptCountsMap, [this](const auto& entry) {
866 BaseScript* script = entry.key();
867 CheckGCThingAfterMovingGC(script, this);
868 return script;
869 });
870 }
871
872 if (scriptLCovMap) {
873 CheckTableAfterMovingGC(*scriptLCovMap, [this](const auto& entry) {
874 BaseScript* script = entry.key();
875 CheckGCThingAfterMovingGC(script, this);
876 return script;
877 });
878 }
879
880 # ifdef MOZ_VTUNE
881 if (scriptVTuneIdMap) {
882 CheckTableAfterMovingGC(*scriptVTuneIdMap, [this](const auto& entry) {
883 BaseScript* script = entry.key();
884 CheckGCThingAfterMovingGC(script, this);
885 return script;
886 });
887 }
888 # endif // MOZ_VTUNE
889
890 # ifdef JS_CACHEIR_SPEW
891 if (scriptFinalWarmUpCountMap) {
892 CheckTableAfterMovingGC(*scriptFinalWarmUpCountMap,
893 [this](const auto& entry) {
894 BaseScript* script = entry.key();
895 CheckGCThingAfterMovingGC(script, this);
896 return script;
897 });
898 }
899 # endif // JS_CACHEIR_SPEW
900 }
901 #endif
902
903 void Zone::clearScriptCounts(Realm* realm) {
904 if (!scriptCountsMap) {
905 return;
906 }
907
908 // Clear all hasScriptCounts_ flags of BaseScript, in order to release all
909 // ScriptCounts entries of the given realm.
910 for (auto i = scriptCountsMap->modIter(); !i.done(); i.next()) {
911 const HeapPtr<BaseScript*>& script = i.get().key();
912 if (IsAboutToBeFinalized(script)) {
913 // Dead scripts may be present during incremental GC until script
914 // finalizers have been run.
915 continue;
916 }
917
918 if (script->realm() != realm) {
919 continue;
920 }
921 // We can't destroy the ScriptCounts yet if the script has Baseline code,
922 // because Baseline code bakes in pointers to the counters. The ScriptCounts
923 // will be destroyed in Zone::discardJitCode when discarding the JitScript.
924 if (script->hasBaselineScript()) {
925 continue;
926 }
927 script->clearHasScriptCounts();
928 i.remove();
929 }
930 }
931
932 void Zone::clearScriptLCov(Realm* realm) {
933 if (!scriptLCovMap) {
934 return;
935 }
936
937 for (auto i = scriptLCovMap->modIter(); !i.done(); i.next()) {
938 const HeapPtr<BaseScript*>& script = i.get().key();
939 if (IsAboutToBeFinalized(script)) {
940 // Dead scripts may be present during incremental GC until script
941 // finalizers have been run.
942 continue;
943 }
944
945 if (script->realm() == realm) {
946 i.remove();
947 }
948 }
949 }
950
951 void Zone::clearRootsForShutdownGC() {
952 // Finalization callbacks are not called if we're shutting down.
953 if (finalizationObservers()) {
954 finalizationObservers()->clearRecords();
955 }
956
957 clearKeptObjects();
958 }
959
960 void Zone::finishRoots() {
961 for (RealmsInZoneIter r(this); !r.done(); r.next()) {
962 r->finishRoots();
963 }
964 }
965
966 void Zone::traceKeptObjects(JSTracer* trc) { keptObjects.ref().trace(trc); }
967
968 bool Zone::addToKeptObjects(HandleObject target) {
969 return keptObjects.ref().put(target);
970 }
971
972 void Zone::clearKeptObjects() { keptObjects.ref().clear(); }
973
974 bool Zone::ensureFinalizationObservers() {
975 if (finalizationObservers_.ref()) {
976 return true;
977 }
978
979 finalizationObservers_ = js::MakeUnique<FinalizationObservers>(this);
980 return bool(finalizationObservers_.ref());
981 }
982
983 bool Zone::registerObjectWithWeakPointers(JSObject* obj) {
984 MOZ_ASSERT(obj->getClass()->hasTrace());
985 MOZ_ASSERT(!IsInsideNursery(obj));
986 return objectsWithWeakPointers.ref().append(obj);
987 }