| 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 |
* [SMDOC] Garbage Collector |
| 9 |
* |
| 10 |
* This code implements an incremental mark-and-sweep garbage collector, with |
| 11 |
* most sweeping carried out in the background on a parallel thread. |
| 12 |
* |
| 13 |
* Full vs. zone GC |
| 14 |
* ---------------- |
| 15 |
* |
| 16 |
* The collector can collect all zones at once, or a subset. These types of |
| 17 |
* collection are referred to as a full GC and a zone GC respectively. |
| 18 |
* |
| 19 |
* It is possible for an incremental collection that started out as a full GC to |
| 20 |
* become a zone GC if new zones are created during the course of the |
| 21 |
* collection. |
| 22 |
* |
| 23 |
* Incremental collection |
| 24 |
* ---------------------- |
| 25 |
* |
| 26 |
* For a collection to be carried out incrementally the following conditions |
| 27 |
* must be met: |
| 28 |
* - the collection must be run by calling js::GCSlice() rather than js::GC() |
| 29 |
* - the GC parameter JSGC_INCREMENTAL_GC_ENABLED must be true. |
| 30 |
* |
| 31 |
* The last condition is an engine-internal mechanism to ensure that incremental |
| 32 |
* collection is not carried out without the correct barriers being implemented. |
| 33 |
* For more information see 'Incremental marking' below. |
| 34 |
* |
| 35 |
* If the collection is not incremental, all foreground activity happens inside |
| 36 |
* a single call to GC() or GCSlice(). However the collection is not complete |
| 37 |
* until the background sweeping activity has finished. |
| 38 |
* |
| 39 |
* An incremental collection proceeds as a series of slices, interleaved with |
| 40 |
* mutator activity, i.e. running JavaScript code. Slices are limited by a time |
| 41 |
* budget. The slice finishes as soon as possible after the requested time has |
| 42 |
* passed. |
| 43 |
* |
| 44 |
* Collector states |
| 45 |
* ---------------- |
| 46 |
* |
| 47 |
* The collector proceeds through the following states, the current state being |
| 48 |
* held in JSRuntime::gcIncrementalState: |
| 49 |
* |
| 50 |
* - Prepare - unmarks GC things, discards JIT code and other setup |
| 51 |
* - MarkRoots - marks the stack and other roots |
| 52 |
* - Mark - incrementally marks reachable things |
| 53 |
* - Sweep - sweeps zones in groups and continues marking unswept zones |
| 54 |
* - Finalize - performs background finalization, concurrent with mutator |
| 55 |
* - Compact - incrementally compacts by zone |
| 56 |
* - Decommit - performs background decommit and chunk removal |
| 57 |
* |
| 58 |
* Roots are marked in the first MarkRoots slice; this is the start of the GC |
| 59 |
* proper. The following states can take place over one or more slices. |
| 60 |
* |
| 61 |
* In other words an incremental collection proceeds like this: |
| 62 |
* |
| 63 |
* Slice 1: Prepare: Starts background task to unmark GC things |
| 64 |
* |
| 65 |
* ... JS code runs, background unmarking finishes ... |
| 66 |
* |
| 67 |
* Slice 2: MarkRoots: Roots are pushed onto the mark stack. |
| 68 |
* Mark: The mark stack is processed by popping an element, |
| 69 |
* marking it, and pushing its children. |
| 70 |
* |
| 71 |
* ... JS code runs ... |
| 72 |
* |
| 73 |
* Slice 3: Mark: More mark stack processing. |
| 74 |
* |
| 75 |
* ... JS code runs ... |
| 76 |
* |
| 77 |
* Slice n-1: Mark: More mark stack processing. |
| 78 |
* |
| 79 |
* ... JS code runs ... |
| 80 |
* |
| 81 |
* Slice n: Mark: Mark stack is completely drained. |
| 82 |
* Sweep: Select first group of zones to sweep and sweep them. |
| 83 |
* |
| 84 |
* ... JS code runs ... |
| 85 |
* |
| 86 |
* Slice n+1: Sweep: Mark objects in unswept zones that were newly |
| 87 |
* identified as alive (see below). Then sweep more zone |
| 88 |
* sweep groups. |
| 89 |
* |
| 90 |
* ... JS code runs ... |
| 91 |
* |
| 92 |
* Slice n+2: Sweep: Mark objects in unswept zones that were newly |
| 93 |
* identified as alive. Then sweep more zones. |
| 94 |
* |
| 95 |
* ... JS code runs ... |
| 96 |
* |
| 97 |
* Slice m: Sweep: Sweeping is finished, and background sweeping |
| 98 |
* started on the helper thread. |
| 99 |
* |
| 100 |
* ... JS code runs, remaining sweeping done on background thread ... |
| 101 |
* |
| 102 |
* When background sweeping finishes the GC is complete. |
| 103 |
* |
| 104 |
* Incremental marking |
| 105 |
* ------------------- |
| 106 |
* |
| 107 |
* Incremental collection requires close collaboration with the mutator (i.e., |
| 108 |
* JS code) to guarantee correctness. |
| 109 |
* |
| 110 |
* - During an incremental GC, if a memory location (except a root) is written |
| 111 |
* to, then the value it previously held must be marked. Write barriers |
| 112 |
* ensure this. |
| 113 |
* |
| 114 |
* - Any object that is allocated during incremental GC must start out marked. |
| 115 |
* |
| 116 |
* - Roots are marked in the first slice and hence don't need write barriers. |
| 117 |
* Roots are things like the C stack and the VM stack. |
| 118 |
* |
| 119 |
* The problem that write barriers solve is that between slices the mutator can |
| 120 |
* change the object graph. We must ensure that it cannot do this in such a way |
| 121 |
* that makes us fail to mark a reachable object (marking an unreachable object |
| 122 |
* is tolerable). |
| 123 |
* |
| 124 |
* We use a snapshot-at-the-beginning algorithm to do this. This means that we |
| 125 |
* promise to mark at least everything that is reachable at the beginning of |
| 126 |
* collection. To implement it we mark the old contents of every non-root memory |
| 127 |
* location written to by the mutator while the collection is in progress, using |
| 128 |
* write barriers. This is described in gc/Barrier.h. |
| 129 |
* |
| 130 |
* Incremental sweeping |
| 131 |
* -------------------- |
| 132 |
* |
| 133 |
* Sweeping is difficult to do incrementally because object finalizers must be |
| 134 |
* run at the start of sweeping, before any mutator code runs. The reason is |
| 135 |
* that some objects use their finalizers to remove themselves from caches. If |
| 136 |
* mutator code was allowed to run after the start of sweeping, it could observe |
| 137 |
* the state of the cache and create a new reference to an object that was just |
| 138 |
* about to be destroyed. |
| 139 |
* |
| 140 |
* Sweeping all finalizable objects in one go would introduce long pauses, so |
| 141 |
* instead sweeping broken up into groups of zones. Zones which are not yet |
| 142 |
* being swept are still marked, so the issue above does not apply. |
| 143 |
* |
| 144 |
* The order of sweeping is restricted by cross compartment pointers - for |
| 145 |
* example say that object |a| from zone A points to object |b| in zone B and |
| 146 |
* neither object was marked when we transitioned to the Sweep phase. Imagine we |
| 147 |
* sweep B first and then return to the mutator. It's possible that the mutator |
| 148 |
* could cause |a| to become alive through a read barrier (perhaps it was a |
| 149 |
* shape that was accessed via a shape table). Then we would need to mark |b|, |
| 150 |
* which |a| points to, but |b| has already been swept. |
| 151 |
* |
| 152 |
* So if there is such a pointer then marking of zone B must not finish before |
| 153 |
* marking of zone A. Pointers which form a cycle between zones therefore |
| 154 |
* restrict those zones to being swept at the same time, and these are found |
| 155 |
* using Tarjan's algorithm for finding the strongly connected components of a |
| 156 |
* graph. |
| 157 |
* |
| 158 |
* GC things without finalizers, and things with finalizers that are able to run |
| 159 |
* in the background, are swept on the background thread. This accounts for most |
| 160 |
* of the sweeping work. |
| 161 |
* |
| 162 |
* Reset |
| 163 |
* ----- |
| 164 |
* |
| 165 |
* During incremental collection it is possible, although unlikely, for |
| 166 |
* conditions to change such that incremental collection is no longer safe. In |
| 167 |
* this case, the collection is 'reset' by resetIncrementalGC(). If we are in |
| 168 |
* the mark state, this just stops marking, but if we have started sweeping |
| 169 |
* already, we continue non-incrementally until we have swept the current sweep |
| 170 |
* group. Following a reset, a new collection is started. |
| 171 |
* |
| 172 |
* Compacting GC |
| 173 |
* ------------- |
| 174 |
* |
| 175 |
* Compacting GC happens at the end of a major GC as part of the last slice. |
| 176 |
* There are three parts: |
| 177 |
* |
| 178 |
* - Arenas are selected for compaction. |
| 179 |
* - The contents of those arenas are moved to new arenas. |
| 180 |
* - All references to moved things are updated. |
| 181 |
* |
| 182 |
* Collecting Atoms |
| 183 |
* ---------------- |
| 184 |
* |
| 185 |
* Atoms are collected differently from other GC things. They are contained in |
| 186 |
* a special zone and things in other zones may have pointers to them that are |
| 187 |
* not recorded in the cross compartment pointer map. Each zone holds a bitmap |
| 188 |
* with the atoms it might be keeping alive, and atoms are only collected if |
| 189 |
* they are not included in any zone's atom bitmap. See AtomMarking.cpp for how |
| 190 |
* this bitmap is managed. |
| 191 |
*/ |
| 192 |
|
| 193 |
#include "gc/GC-inl.h" |
| 194 |
|
| 195 |
#include "mozilla/glue/Debug.h" |
| 196 |
#include "mozilla/Range.h" |
| 197 |
#include "mozilla/ScopeExit.h" |
| 198 |
#include "mozilla/TextUtils.h" |
| 199 |
#include "mozilla/TimeStamp.h" |
| 200 |
|
| 201 |
#include <algorithm> |
| 202 |
#include <initializer_list> |
| 203 |
#include <iterator> |
| 204 |
#include <stdlib.h> |
| 205 |
#include <string.h> |
| 206 |
#include <utility> |
| 207 |
|
| 208 |
#include "jsapi.h" // JS_AbortIfWrongThread |
| 209 |
#include "jstypes.h" |
| 210 |
|
| 211 |
#include "debugger/DebugAPI.h" |
| 212 |
#include "gc/ClearEdgesTracer.h" |
| 213 |
#include "gc/GCContext.h" |
| 214 |
#include "gc/GCInternals.h" |
| 215 |
#include "gc/GCLock.h" |
| 216 |
#include "gc/GCProbes.h" |
| 217 |
#include "gc/Memory.h" |
| 218 |
#include "gc/ParallelMarking.h" |
| 219 |
#include "gc/ParallelWork.h" |
| 220 |
#include "gc/WeakMap.h" |
| 221 |
#include "jit/ExecutableAllocator.h" |
| 222 |
#include "jit/JitCode.h" |
| 223 |
#include "jit/JitRuntime.h" |
| 224 |
#include "jit/ProcessExecutableMemory.h" |
| 225 |
#include "js/HeapAPI.h" // JS::GCCellPtr |
| 226 |
#include "js/Printer.h" |
| 227 |
#include "js/SliceBudget.h" |
| 228 |
#include "util/DifferentialTesting.h" |
| 229 |
#include "vm/BigIntType.h" |
| 230 |
#include "vm/EnvironmentObject.h" |
| 231 |
#include "vm/GetterSetter.h" |
| 232 |
#include "vm/HelperThreadState.h" |
| 233 |
#include "vm/JitActivation.h" |
| 234 |
#include "vm/JSObject.h" |
| 235 |
#include "vm/JSScript.h" |
| 236 |
#include "vm/PropMap.h" |
| 237 |
#include "vm/Realm.h" |
| 238 |
#include "vm/Shape.h" |
| 239 |
#include "vm/StringType.h" |
| 240 |
#include "vm/SymbolType.h" |
| 241 |
#include "vm/Time.h" |
| 242 |
|
| 243 |
#include "gc/Heap-inl.h" |
| 244 |
#include "gc/Nursery-inl.h" |
| 245 |
#include "gc/ObjectKind-inl.h" |
| 246 |
#include "gc/PrivateIterators-inl.h" |
| 247 |
#include "vm/GeckoProfiler-inl.h" |
| 248 |
#include "vm/JSContext-inl.h" |
| 249 |
#include "vm/Realm-inl.h" |
| 250 |
#include "vm/Stack-inl.h" |
| 251 |
#include "vm/StringType-inl.h" |
| 252 |
|
| 253 |
using namespace js; |
| 254 |
using namespace js::gc; |
| 255 |
|
| 256 |
using mozilla::EnumSet; |
| 257 |
using mozilla::MakeScopeExit; |
| 258 |
using mozilla::Maybe; |
| 259 |
using mozilla::Nothing; |
| 260 |
using mozilla::Some; |
| 261 |
using mozilla::TimeDuration; |
| 262 |
using mozilla::TimeStamp; |
| 263 |
|
| 264 |
using JS::SliceBudget; |
| 265 |
using JS::TimeBudget; |
| 266 |
using JS::WorkBudget; |
| 267 |
|
| 268 |
// A table converting an object size in "slots" (increments of |
| 269 |
// sizeof(js::Value)) to the total number of bytes in the corresponding |
| 270 |
// AllocKind. See gc::slotsToThingKind. This primarily allows wasm jit code to |
| 271 |
// remain compliant with the AllocKind system. |
| 272 |
// |
| 273 |
// To use this table, subtract sizeof(NativeObject) from your desired allocation |
| 274 |
// size, divide by sizeof(js::Value) to get the number of "slots", and then |
| 275 |
// index into this table. See gc::GetGCObjectKindForBytes. |
| 276 |
constexpr uint32_t gc::slotsToAllocKindBytes[] = { |
| 277 |
// These entries correspond exactly to gc::slotsToThingKind. The numeric |
| 278 |
// comments therefore indicate the number of slots that the "bytes" would |
| 279 |
// correspond to. |
| 280 |
// clang-format off |
| 281 |
/* 0 */ sizeof(JSObject_Slots0), sizeof(JSObject_Slots2), sizeof(JSObject_Slots2), sizeof(JSObject_Slots4), |
| 282 |
/* 4 */ sizeof(JSObject_Slots4), sizeof(JSObject_Slots8), sizeof(JSObject_Slots8), sizeof(JSObject_Slots8), |
| 283 |
/* 8 */ sizeof(JSObject_Slots8), sizeof(JSObject_Slots12), sizeof(JSObject_Slots12), sizeof(JSObject_Slots12), |
| 284 |
/* 12 */ sizeof(JSObject_Slots12), sizeof(JSObject_Slots16), sizeof(JSObject_Slots16), sizeof(JSObject_Slots16), |
| 285 |
/* 16 */ sizeof(JSObject_Slots16) |
| 286 |
// clang-format on |
| 287 |
}; |
| 288 |
|
| 289 |
static_assert(std::size(slotsToAllocKindBytes) == std::size(slotsToThingKind)); |
| 290 |
|
| 291 |
MOZ_THREAD_LOCAL(JS::GCContext*) js::TlsGCContext; |
| 292 |
|
| 293 |
JS::GCContext::GCContext(JSRuntime* runtime) : runtime_(runtime) {} |
| 294 |
|
| 295 |
JS::GCContext::~GCContext() { |
| 296 |
MOZ_ASSERT(!hasJitCodeToPoison()); |
| 297 |
MOZ_ASSERT(!isCollecting()); |
| 298 |
MOZ_ASSERT(gcUse() == GCUse::None); |
| 299 |
MOZ_ASSERT(!gcSweepZone()); |
| 300 |
MOZ_ASSERT(!isTouchingGrayThings()); |
| 301 |
MOZ_ASSERT(isPreWriteBarrierAllowed()); |
| 302 |
} |
| 303 |
|
| 304 |
void JS::GCContext::poisonJitCode() { |
| 305 |
if (hasJitCodeToPoison()) { |
| 306 |
jit::ExecutableAllocator::poisonCode(runtime(), jitPoisonRanges); |
| 307 |
jitPoisonRanges.clearAndFree(); |
| 308 |
} |
| 309 |
} |
| 310 |
|
| 311 |
#ifdef DEBUG |
| 312 |
void GCRuntime::verifyAllChunks() { |
| 313 |
AutoLockGC lock(this); |
| 314 |
fullChunks(lock).verifyChunks(); |
| 315 |
availableChunks(lock).verifyChunks(); |
| 316 |
emptyChunks(lock).verifyChunks(); |
| 317 |
if (currentChunk_) { |
| 318 |
MOZ_ASSERT(currentChunk_->info.isCurrentChunk); |
| 319 |
currentChunk_->verify(); |
| 320 |
} else { |
| 321 |
MOZ_ASSERT(pendingFreeCommittedArenas.ref().IsEmpty()); |
| 322 |
} |
| 323 |
} |
| 324 |
#endif |
| 325 |
|
| 326 |
void GCRuntime::setMinEmptyChunkCount(uint32_t value, const AutoLockGC& lock) { |
| 327 |
minEmptyChunkCount_ = value; |
| 328 |
} |
| 329 |
|
| 330 |
inline bool GCRuntime::tooManyEmptyChunks(const AutoLockGC& lock) { |
| 331 |
return emptyChunks(lock).count() > minEmptyChunkCount(lock); |
| 332 |
} |
| 333 |
|
| 334 |
ChunkPool GCRuntime::expireEmptyChunkPool(const AutoLockGC& lock) { |
| 335 |
MOZ_ASSERT(emptyChunks(lock).verify()); |
| 336 |
|
| 337 |
ChunkPool expired; |
| 338 |
if (isShrinkingGC()) { |
| 339 |
std::swap(expired, emptyChunks(lock)); |
| 340 |
} else { |
| 341 |
while (tooManyEmptyChunks(lock)) { |
| 342 |
ArenaChunk* chunk = emptyChunks(lock).pop(); |
| 343 |
prepareToFreeChunk(chunk->info); |
| 344 |
expired.push(chunk); |
| 345 |
} |
| 346 |
} |
| 347 |
|
| 348 |
MOZ_ASSERT(expired.verify()); |
| 349 |
MOZ_ASSERT(emptyChunks(lock).verify()); |
| 350 |
MOZ_ASSERT(emptyChunks(lock).count() <= minEmptyChunkCount(lock)); |
| 351 |
return expired; |
| 352 |
} |
| 353 |
|
| 354 |
static void FreeChunkPool(ChunkPool& pool) { |
| 355 |
for (ChunkPool::Iter iter(pool); !iter.done();) { |
| 356 |
ArenaChunk* chunk = iter.get(); |
| 357 |
iter.next(); |
| 358 |
pool.remove(chunk); |
| 359 |
MOZ_ASSERT(chunk->isEmpty()); |
| 360 |
UnmapPages(static_cast<void*>(chunk), ChunkSize); |
| 361 |
} |
| 362 |
MOZ_ASSERT(pool.count() == 0); |
| 363 |
} |
| 364 |
|
| 365 |
void GCRuntime::freeEmptyChunks(const AutoLockGC& lock) { |
| 366 |
FreeChunkPool(emptyChunks(lock)); |
| 367 |
} |
| 368 |
|
| 369 |
inline void GCRuntime::prepareToFreeChunk(ArenaChunkInfo& info) { |
| 370 |
MOZ_ASSERT(info.numArenasFree == ArenasPerChunk); |
| 371 |
stats().count(gcstats::COUNT_DESTROY_CHUNK); |
| 372 |
#ifdef DEBUG |
| 373 |
// Let FreeChunkPool detect a missing prepareToFreeChunk call before it frees |
| 374 |
// chunk. |
| 375 |
info.numArenasFreeCommitted = 0; |
| 376 |
#endif |
| 377 |
} |
| 378 |
|
| 379 |
void GCRuntime::releaseArenaList(ArenaList& arenaList, const AutoLockGC& lock) { |
| 380 |
releaseArenas(arenaList.release(), lock); |
| 381 |
} |
| 382 |
|
| 383 |
void GCRuntime::releaseArenas(Arena* arena, const AutoLockGC& lock) { |
| 384 |
Arena* next; |
| 385 |
for (; arena; arena = next) { |
| 386 |
next = arena->next; |
| 387 |
releaseArena(arena, lock); |
| 388 |
} |
| 389 |
} |
| 390 |
|
| 391 |
void GCRuntime::releaseArena(Arena* arena, const AutoLockGC& lock) { |
| 392 |
MOZ_ASSERT(arena->allocated()); |
| 393 |
MOZ_ASSERT(!arena->onDelayedMarkingList()); |
| 394 |
MOZ_ASSERT(TlsGCContext.get()->isFinalizing()); |
| 395 |
|
| 396 |
if (IsBufferAllocKind(arena->getAllocKind())) { |
| 397 |
size_t usableBytes = ArenaSize - arena->getFirstThingOffset(); |
| 398 |
arena->zone()->mallocHeapSize.removeBytes(usableBytes, true); |
| 399 |
} else { |
| 400 |
arena->zone()->gcHeapSize.removeBytes(ArenaSize, true, heapSize); |
| 401 |
} |
| 402 |
if (arena->zone()->isAtomsZone()) { |
| 403 |
arena->freeAtomMarkingBitmapIndex(this, lock); |
| 404 |
} |
| 405 |
arena->release(); |
| 406 |
arena->chunk()->releaseArena(this, arena, lock); |
| 407 |
} |
| 408 |
|
| 409 |
GCRuntime::GCRuntime(JSRuntime* rt) |
| 410 |
: rt(rt), |
| 411 |
systemZone(nullptr), |
| 412 |
mainThreadContext(rt), |
| 413 |
heapState_(JS::HeapState::Idle), |
| 414 |
stats_(this), |
| 415 |
sweepingTracer(rt), |
| 416 |
fullGCRequested(false), |
| 417 |
helperThreadRatio(TuningDefaults::HelperThreadRatio), |
| 418 |
maxHelperThreads(TuningDefaults::MaxHelperThreads), |
| 419 |
helperThreadCount(1), |
| 420 |
maxMarkingThreads(TuningDefaults::MaxMarkingThreads), |
| 421 |
markingThreadCount(1), |
| 422 |
createBudgetCallback(nullptr), |
| 423 |
minEmptyChunkCount_(TuningDefaults::MinEmptyChunkCount), |
| 424 |
rootsHash(256), |
| 425 |
nextCellUniqueId_(LargestTaggedNullCellPointer + |
| 426 |
1), // Ensure disjoint from null tagged pointers. |
| 427 |
verifyPreData(nullptr), |
| 428 |
lastGCStartTime_(TimeStamp::Now()), |
| 429 |
lastGCEndTime_(TimeStamp::Now()), |
| 430 |
incrementalGCEnabled(TuningDefaults::IncrementalGCEnabled), |
| 431 |
perZoneGCEnabled(TuningDefaults::PerZoneGCEnabled), |
| 432 |
numActiveZoneIters(0), |
| 433 |
grayBitsValid(true), |
| 434 |
majorGCTriggerReason(JS::GCReason::NO_REASON), |
| 435 |
minorGCNumber(0), |
| 436 |
majorGCNumber(0), |
| 437 |
number(0), |
| 438 |
sliceNumber(0), |
| 439 |
isFull(false), |
| 440 |
incrementalState(gc::State::NotActive), |
| 441 |
initialState(gc::State::NotActive), |
| 442 |
useZeal(false), |
| 443 |
lastMarkSlice(false), |
| 444 |
safeToYield(true), |
| 445 |
markOnBackgroundThreadDuringSweeping(false), |
| 446 |
useBackgroundThreads(false), |
| 447 |
#ifdef DEBUG |
| 448 |
hadShutdownGC(false), |
| 449 |
#endif |
| 450 |
requestSliceAfterBackgroundTask(false), |
| 451 |
lifoBlocksToFree((size_t)JSContext::TEMP_LIFO_ALLOC_PRIMARY_CHUNK_SIZE, |
| 452 |
js::BackgroundMallocArena), |
| 453 |
lifoBlocksToFreeAfterFullMinorGC( |
| 454 |
(size_t)JSContext::TEMP_LIFO_ALLOC_PRIMARY_CHUNK_SIZE, |
| 455 |
js::BackgroundMallocArena), |
| 456 |
lifoBlocksToFreeAfterNextMinorGC( |
| 457 |
(size_t)JSContext::TEMP_LIFO_ALLOC_PRIMARY_CHUNK_SIZE, |
| 458 |
js::BackgroundMallocArena), |
| 459 |
sweepGroupIndex(0), |
| 460 |
sweepGroups(nullptr), |
| 461 |
currentSweepGroup(nullptr), |
| 462 |
sweepZone(nullptr), |
| 463 |
abortSweepAfterCurrentGroup(false), |
| 464 |
sweepMarkResult(IncrementalProgress::NotFinished), |
| 465 |
#ifdef DEBUG |
| 466 |
testMarkQueue(rt), |
| 467 |
#endif |
| 468 |
startedCompacting(false), |
| 469 |
zonesCompacted(0), |
| 470 |
#ifdef DEBUG |
| 471 |
relocatedArenasToRelease(nullptr), |
| 472 |
#endif |
| 473 |
#ifdef JS_GC_ZEAL |
| 474 |
markingValidator(nullptr), |
| 475 |
#endif |
| 476 |
defaultTimeBudgetMS_(TuningDefaults::DefaultTimeBudgetMS), |
| 477 |
compactingEnabled(TuningDefaults::CompactingEnabled), |
| 478 |
nurseryEnabled(TuningDefaults::NurseryEnabled), |
| 479 |
parallelMarkingEnabled(TuningDefaults::ParallelMarkingEnabled), |
| 480 |
rootsRemoved(false), |
| 481 |
#ifdef JS_GC_ZEAL |
| 482 |
zealModeBits(0), |
| 483 |
zealFrequency(0), |
| 484 |
nextScheduled(0), |
| 485 |
deterministicOnly(false), |
| 486 |
zealSliceBudget(0), |
| 487 |
selectedForMarking(rt), |
| 488 |
#endif |
| 489 |
fullCompartmentChecks(false), |
| 490 |
gcCallbackDepth(0), |
| 491 |
alwaysPreserveCode(false), |
| 492 |
lowMemoryState(false), |
| 493 |
lock(mutexid::GCLock), |
| 494 |
storeBufferLock(mutexid::StoreBuffer), |
| 495 |
delayedMarkingLock(mutexid::GCDelayedMarkingLock), |
| 496 |
bufferAllocatorLock(mutexid::BufferAllocator), |
| 497 |
allocTask(this, emptyChunks_.ref()), |
| 498 |
unmarkTask(this), |
| 499 |
markTask(this), |
| 500 |
sweepTask(this), |
| 501 |
freeTask(this), |
| 502 |
decommitTask(this), |
| 503 |
nursery_(this), |
| 504 |
storeBuffer_(rt), |
| 505 |
lastAllocRateUpdateTime(TimeStamp::Now()) { |
| 506 |
} |
| 507 |
|
| 508 |
bool js::gc::SplitStringBy(const char* text, char delimiter, |
| 509 |
CharRangeVector* result) { |
| 510 |
return SplitStringBy(CharRange(text, strlen(text)), delimiter, result); |
| 511 |
} |
| 512 |
|
| 513 |
bool js::gc::SplitStringBy(const CharRange& text, char delimiter, |
| 514 |
CharRangeVector* result) { |
| 515 |
auto start = text.begin(); |
| 516 |
for (auto ptr = start; ptr != text.end(); ptr++) { |
| 517 |
if (*ptr == delimiter) { |
| 518 |
if (!result->emplaceBack(start, ptr)) { |
| 519 |
return false; |
| 520 |
} |
| 521 |
start = ptr + 1; |
| 522 |
} |
| 523 |
} |
| 524 |
|
| 525 |
return result->emplaceBack(start, text.end()); |
| 526 |
} |
| 527 |
|
| 528 |
static bool ParseTimeDuration(const CharRange& text, |
| 529 |
TimeDuration* durationOut) { |
| 530 |
const char* str = text.begin().get(); |
| 531 |
char* end; |
| 532 |
long millis = strtol(str, &end, 10); |
| 533 |
*durationOut = TimeDuration::FromMilliseconds(double(millis)); |
| 534 |
return str != end && end == text.end().get(); |
| 535 |
} |
| 536 |
|
| 537 |
static void PrintProfileHelpAndExit(const char* envName, const char* helpText) { |
| 538 |
fprintf(stderr, "%s=N[,(main|all)]\n", envName); |
| 539 |
fprintf(stderr, "%s", helpText); |
| 540 |
exit(0); |
| 541 |
} |
| 542 |
|
| 543 |
void js::gc::ReadProfileEnv(const char* envName, const char* helpText, |
| 544 |
bool* enableOut, bool* workersOut, |
| 545 |
TimeDuration* thresholdOut) { |
| 546 |
*enableOut = false; |
| 547 |
*workersOut = false; |
| 548 |
*thresholdOut = TimeDuration::Zero(); |
| 549 |
|
| 550 |
const char* env = getenv(envName); |
| 551 |
if (!env) { |
| 552 |
return; |
| 553 |
} |
| 554 |
|
| 555 |
if (strcmp(env, "help") == 0) { |
| 556 |
PrintProfileHelpAndExit(envName, helpText); |
| 557 |
} |
| 558 |
|
| 559 |
CharRangeVector parts; |
| 560 |
if (!SplitStringBy(env, ',', &parts)) { |
| 561 |
MOZ_CRASH("OOM parsing environment variable"); |
| 562 |
} |
| 563 |
|
| 564 |
if (parts.length() == 0 || parts.length() > 2) { |
| 565 |
PrintProfileHelpAndExit(envName, helpText); |
| 566 |
} |
| 567 |
|
| 568 |
*enableOut = true; |
| 569 |
|
| 570 |
if (!ParseTimeDuration(parts[0], thresholdOut)) { |
| 571 |
PrintProfileHelpAndExit(envName, helpText); |
| 572 |
} |
| 573 |
|
| 574 |
if (parts.length() == 2) { |
| 575 |
const char* threads = parts[1].begin().get(); |
| 576 |
if (strcmp(threads, "all") == 0) { |
| 577 |
*workersOut = true; |
| 578 |
} else if (strcmp(threads, "main") != 0) { |
| 579 |
PrintProfileHelpAndExit(envName, helpText); |
| 580 |
} |
| 581 |
} |
| 582 |
} |
| 583 |
|
| 584 |
bool js::gc::ShouldPrintProfile(JSRuntime* runtime, bool enable, |
| 585 |
bool profileWorkers, TimeDuration threshold, |
| 586 |
TimeDuration duration) { |
| 587 |
return enable && (runtime->isMainRuntime() || profileWorkers) && |
| 588 |
duration >= threshold; |
| 589 |
} |
| 590 |
|
| 591 |
#ifdef JS_GC_ZEAL |
| 592 |
|
| 593 |
void GCRuntime::getZealBits(uint32_t* zealBits, uint32_t* frequency, |
| 594 |
uint32_t* scheduled) { |
| 595 |
*zealBits = zealModeBits; |
| 596 |
*frequency = zealFrequency; |
| 597 |
*scheduled = nextScheduled; |
| 598 |
} |
| 599 |
|
| 600 |
// Please also update jit-test/tests/gc/gczeal.js when updating this help text. |
| 601 |
// clang-format off |
| 602 |
const char gc::ZealModeHelpText[] = |
| 603 |
" Specifies how zealous the garbage collector should be. Some of these modes\n" |
| 604 |
" can be set simultaneously, by passing multiple level options, e.g. \"2;4\"\n" |
| 605 |
" will activate both modes 2 and 4. Modes can be specified by name or\n" |
| 606 |
" number.\n" |
| 607 |
" \n" |
| 608 |
" Values:\n" |
| 609 |
" 0: (None) Normal amount of collection (resets all modes)\n" |
| 610 |
" 1: (RootsChange) Collect when roots are added or removed\n" |
| 611 |
" 2: (Alloc) Collect when every N allocations (default: 100)\n" |
| 612 |
" 4: (VerifierPre) Verify pre write barriers between instructions\n" |
| 613 |
" 5: (VerifierPost) Verify post write barriers after minor GC\n" |
| 614 |
" 6: (YieldBeforeRootMarking) Incremental GC in two slices that yields\n" |
| 615 |
" before root marking\n" |
| 616 |
" 7: (GenerationalGC) Collect the nursery every N nursery allocations\n" |
| 617 |
" 8: (YieldBeforeMarking) Incremental GC in two slices that yields\n" |
| 618 |
" between the root marking and marking phases\n" |
| 619 |
" 9: (YieldBeforeSweeping) Incremental GC in two slices that yields\n" |
| 620 |
" between the marking and sweeping phases\n" |
| 621 |
" 10: (IncrementalMultipleSlices) Incremental GC in many slices\n" |
| 622 |
" 11: (IncrementalMarkingValidator) Verify incremental marking\n" |
| 623 |
" 12: (ElementsBarrier) Use the individual element post-write barrier\n" |
| 624 |
" regardless of elements size\n" |
| 625 |
" 13: (CheckHashTablesOnMinorGC) Check internal hashtables on minor GC\n" |
| 626 |
" 14: (Compact) Perform a shrinking collection every N allocations\n" |
| 627 |
" 15: (CheckHeapAfterGC) Walk the heap to check its integrity after every\n" |
| 628 |
" GC\n" |
| 629 |
" 17: (YieldBeforeSweepingAtoms) Incremental GC in two slices that yields\n" |
| 630 |
" before sweeping the atoms table\n" |
| 631 |
" 18: (CheckGrayMarking) Check gray marking invariants after every GC\n" |
| 632 |
" 19: (YieldBeforeSweepingCaches) Incremental GC in two slices that yields\n" |
| 633 |
" before sweeping weak caches\n" |
| 634 |
" 21: (YieldBeforeSweepingObjects) Incremental GC that yields once per\n" |
| 635 |
" zone before sweeping foreground finalized objects\n" |
| 636 |
" 22: (YieldBeforeSweepingNonObjects) Incremental GC that yields once per\n" |
| 637 |
" zone before sweeping non-object GC things\n" |
| 638 |
" 23: (YieldBeforeSweepingPropMapTrees) Incremental GC that yields once\n" |
| 639 |
" per zone before sweeping shape trees\n" |
| 640 |
" 24: (CheckWeakMapMarking) Check weak map marking invariants after every\n" |
| 641 |
" GC\n" |
| 642 |
" 25: (YieldWhileGrayMarking) Incremental GC in two slices that yields\n" |
| 643 |
" during gray marking\n" |
| 644 |
" 26: (CheckHeapBeforeMinorGC) Check for invariant violations before every\n" |
| 645 |
" minor GC\n"; |
| 646 |
// clang-format on |
| 647 |
|
| 648 |
// The set of zeal modes that yield at specific points in collection. |
| 649 |
static constexpr EnumSet<ZealMode> YieldPointZealModes = { |
| 650 |
ZealMode::YieldBeforeRootMarking, |
| 651 |
ZealMode::YieldBeforeMarking, |
| 652 |
ZealMode::YieldBeforeSweeping, |
| 653 |
ZealMode::YieldBeforeSweepingAtoms, |
| 654 |
ZealMode::YieldBeforeSweepingCaches, |
| 655 |
ZealMode::YieldBeforeSweepingObjects, |
| 656 |
ZealMode::YieldBeforeSweepingNonObjects, |
| 657 |
ZealMode::YieldBeforeSweepingPropMapTrees, |
| 658 |
ZealMode::YieldWhileGrayMarking}; |
| 659 |
|
| 660 |
// The set of zeal modes that control incremental slices. |
| 661 |
static constexpr EnumSet<ZealMode> IncrementalSliceZealModes = |
| 662 |
YieldPointZealModes + |
| 663 |
EnumSet<ZealMode>{ZealMode::IncrementalMultipleSlices}; |
| 664 |
|
| 665 |
// The set of zeal modes that trigger GC periodically. |
| 666 |
static constexpr EnumSet<ZealMode> PeriodicGCZealModes = |
| 667 |
IncrementalSliceZealModes + |
| 668 |
EnumSet<ZealMode>{ZealMode::Alloc, ZealMode::VerifierPost, |
| 669 |
ZealMode::GenerationalGC, ZealMode::Compact}; |
| 670 |
|
| 671 |
// The set of zeal modes that are mutually exclusive. All of these trigger GC |
| 672 |
// except VerifierPre. |
| 673 |
static constexpr EnumSet<ZealMode> ExclusiveZealModes = |
| 674 |
PeriodicGCZealModes + EnumSet<ZealMode>{ZealMode::VerifierPre}; |
| 675 |
|
| 676 |
void GCRuntime::setZeal(uint8_t zeal, uint32_t frequency) { |
| 677 |
MOZ_ASSERT(zeal <= unsigned(ZealMode::Limit)); |
| 678 |
|
| 679 |
if (verifyPreData) { |
| 680 |
VerifyBarriers(rt, PreBarrierVerifier); |
| 681 |
} |
| 682 |
|
| 683 |
if (zeal == 0) { |
| 684 |
if (hasZealMode(ZealMode::GenerationalGC)) { |
| 685 |
clearZealMode(ZealMode::GenerationalGC); |
| 686 |
} |
| 687 |
|
| 688 |
if (isIncrementalGCInProgress()) { |
| 689 |
finishGC(JS::GCReason::DEBUG_GC); |
| 690 |
} |
| 691 |
|
| 692 |
zealModeBits = 0; |
| 693 |
zealFrequency = 0; |
| 694 |
nextScheduled = 0; |
| 695 |
return; |
| 696 |
} |
| 697 |
|
| 698 |
// Modes that trigger periodically are mutually exclusive. If we're setting |
| 699 |
// one of those, we first reset all of them. |
| 700 |
ZealMode zealMode = ZealMode(zeal); |
| 701 |
if (ExclusiveZealModes.contains(zealMode)) { |
| 702 |
for (auto mode : ExclusiveZealModes) { |
| 703 |
if (hasZealMode(mode)) { |
| 704 |
clearZealMode(mode); |
| 705 |
} |
| 706 |
} |
| 707 |
} |
| 708 |
|
| 709 |
if (zealMode == ZealMode::GenerationalGC) { |
| 710 |
evictNursery(JS::GCReason::EVICT_NURSERY); |
| 711 |
nursery().enterZealMode(); |
| 712 |
} |
| 713 |
|
| 714 |
zealModeBits |= 1 << zeal; |
| 715 |
zealFrequency = frequency; |
| 716 |
|
| 717 |
if (PeriodicGCZealModes.contains(zealMode)) { |
| 718 |
nextScheduled = frequency; |
| 719 |
} |
| 720 |
} |
| 721 |
|
| 722 |
void GCRuntime::unsetZeal(uint8_t zeal) { |
| 723 |
MOZ_ASSERT(zeal <= unsigned(ZealMode::Limit)); |
| 724 |
ZealMode zealMode = ZealMode(zeal); |
| 725 |
|
| 726 |
if (!hasZealMode(zealMode)) { |
| 727 |
return; |
| 728 |
} |
| 729 |
|
| 730 |
if (verifyPreData) { |
| 731 |
VerifyBarriers(rt, PreBarrierVerifier); |
| 732 |
} |
| 733 |
|
| 734 |
clearZealMode(zealMode); |
| 735 |
|
| 736 |
if (zealModeBits == 0) { |
| 737 |
if (isIncrementalGCInProgress()) { |
| 738 |
finishGC(JS::GCReason::DEBUG_GC); |
| 739 |
} |
| 740 |
|
| 741 |
zealFrequency = 0; |
| 742 |
nextScheduled = 0; |
| 743 |
} |
| 744 |
} |
| 745 |
|
| 746 |
void GCRuntime::setNextScheduled(uint32_t count) { nextScheduled = count; } |
| 747 |
|
| 748 |
static bool ParseZealModeName(const CharRange& text, uint32_t* modeOut) { |
| 749 |
struct ModeInfo { |
| 750 |
const char* name; |
| 751 |
size_t length; |
| 752 |
uint32_t value; |
| 753 |
}; |
| 754 |
|
| 755 |
static const ModeInfo zealModes[] = {{"None", 0}, |
| 756 |
# define ZEAL_MODE(name, value) {#name, strlen(#name), value}, |
| 757 |
JS_FOR_EACH_ZEAL_MODE(ZEAL_MODE) |
| 758 |
# undef ZEAL_MODE |
| 759 |
}; |
| 760 |
|
| 761 |
for (auto mode : zealModes) { |
| 762 |
if (text.length() == mode.length && |
| 763 |
memcmp(text.begin().get(), mode.name, mode.length) == 0) { |
| 764 |
*modeOut = mode.value; |
| 765 |
return true; |
| 766 |
} |
| 767 |
} |
| 768 |
|
| 769 |
return false; |
| 770 |
} |
| 771 |
|
| 772 |
static bool ParseZealModeNumericParam(const CharRange& text, |
| 773 |
uint32_t* paramOut) { |
| 774 |
if (text.length() == 0) { |
| 775 |
return false; |
| 776 |
} |
| 777 |
|
| 778 |
for (auto c : text) { |
| 779 |
if (!mozilla::IsAsciiDigit(c)) { |
| 780 |
return false; |
| 781 |
} |
| 782 |
} |
| 783 |
|
| 784 |
*paramOut = atoi(text.begin().get()); |
| 785 |
return true; |
| 786 |
} |
| 787 |
|
| 788 |
static bool PrintZealHelpAndFail() { |
| 789 |
fprintf(stderr, "Format: JS_GC_ZEAL=level(;level)*[,N]\n"); |
| 790 |
fputs(ZealModeHelpText, stderr); |
| 791 |
return false; |
| 792 |
} |
| 793 |
|
| 794 |
bool GCRuntime::parseZeal(const char* str, size_t len, ZealSettings* zeal, |
| 795 |
bool* invalid) { |
| 796 |
CharRange text(str, len); |
| 797 |
|
| 798 |
// The zeal mode setting is a string consisting of one or more mode |
| 799 |
// specifiers separated by ';', optionally followed by a ',' and the trigger |
| 800 |
// frequency. The mode specifiers can by a mode name or its number. |
| 801 |
|
| 802 |
*invalid = false; |
| 803 |
|
| 804 |
CharRangeVector parts; |
| 805 |
if (!SplitStringBy(text, ',', &parts)) { |
| 806 |
return false; |
| 807 |
} |
| 808 |
|
| 809 |
if (parts.length() == 0 || parts.length() > 2) { |
| 810 |
*invalid = true; |
| 811 |
return true; |
| 812 |
} |
| 813 |
|
| 814 |
uint32_t frequency = JS::ShellDefaultGCZealFrequency; |
| 815 |
if (parts.length() == 2 && !ParseZealModeNumericParam(parts[1], &frequency)) { |
| 816 |
*invalid = true; |
| 817 |
return true; |
| 818 |
} |
| 819 |
|
| 820 |
CharRangeVector modes; |
| 821 |
if (!SplitStringBy(parts[0], ';', &modes)) { |
| 822 |
return false; |
| 823 |
} |
| 824 |
|
| 825 |
for (const auto& descr : modes) { |
| 826 |
uint32_t mode; |
| 827 |
if (!ParseZealModeName(descr, &mode) && |
| 828 |
!(ParseZealModeNumericParam(descr, &mode) && |
| 829 |
mode <= unsigned(ZealMode::Limit))) { |
| 830 |
*invalid = true; |
| 831 |
return true; |
| 832 |
} |
| 833 |
|
| 834 |
if (!zeal->append(ZealSetting{uint8_t(mode), frequency})) { |
| 835 |
return false; |
| 836 |
} |
| 837 |
} |
| 838 |
|
| 839 |
return true; |
| 840 |
} |
| 841 |
|
| 842 |
bool GCRuntime::parseAndSetZeal(const char* str) { |
| 843 |
ZealSettings zeal; |
| 844 |
bool invalid = false; |
| 845 |
if (!parseZeal(str, strlen(str), &zeal, &invalid)) { |
| 846 |
return false; |
| 847 |
} |
| 848 |
|
| 849 |
if (invalid) { |
| 850 |
return PrintZealHelpAndFail(); |
| 851 |
} |
| 852 |
|
| 853 |
for (auto [mode, frequency] : zeal) { |
| 854 |
setZeal(mode, frequency); |
| 855 |
} |
| 856 |
|
| 857 |
return true; |
| 858 |
} |
| 859 |
|
| 860 |
bool GCRuntime::needZealousGC() { |
| 861 |
if (nextScheduled > 0 && --nextScheduled == 0) { |
| 862 |
if (hasAnyZealModeOf(PeriodicGCZealModes)) { |
| 863 |
nextScheduled = zealFrequency; |
| 864 |
} |
| 865 |
return true; |
| 866 |
} |
| 867 |
return false; |
| 868 |
} |
| 869 |
|
| 870 |
bool GCRuntime::zealModeControlsYieldPoint() const { |
| 871 |
// Indicates whether a zeal mode is enabled that controls the point at which |
| 872 |
// the collector yields to the mutator. Yield can happen once per collection |
| 873 |
// or once per zone depending on the mode. |
| 874 |
return hasAnyZealModeOf(YieldPointZealModes); |
| 875 |
} |
| 876 |
|
| 877 |
bool GCRuntime::hasZealMode(ZealMode mode) const { |
| 878 |
static_assert(size_t(ZealMode::Limit) < sizeof(zealModeBits) * 8, |
| 879 |
"Zeal modes must fit in zealModeBits"); |
| 880 |
return zealModeBits & (1 << uint32_t(mode)); |
| 881 |
} |
| 882 |
|
| 883 |
bool GCRuntime::hasAnyZealModeOf(EnumSet<ZealMode> modes) const { |
| 884 |
return zealModeBits & modes.serialize(); |
| 885 |
} |
| 886 |
|
| 887 |
void GCRuntime::clearZealMode(ZealMode mode) { |
| 888 |
MOZ_ASSERT(hasZealMode(mode)); |
| 889 |
|
| 890 |
if (mode == ZealMode::GenerationalGC) { |
| 891 |
evictNursery(); |
| 892 |
nursery().leaveZealMode(); |
| 893 |
} |
| 894 |
|
| 895 |
zealModeBits &= ~(1 << uint32_t(mode)); |
| 896 |
MOZ_ASSERT(!hasZealMode(mode)); |
| 897 |
} |
| 898 |
|
| 899 |
void js::gc::DumpArenaInfo() { |
| 900 |
fprintf(stderr, "Arena header size: %zu\n\n", ArenaHeaderSize); |
| 901 |
|
| 902 |
fprintf(stderr, "GC thing kinds:\n"); |
| 903 |
fprintf(stderr, "%25s %8s %8s %8s\n", |
| 904 |
"AllocKind:", "Size:", "Count:", "Padding:"); |
| 905 |
for (auto kind : AllAllocKinds()) { |
| 906 |
fprintf(stderr, "%25s %8zu %8zu %8zu\n", AllocKindName(kind), |
| 907 |
Arena::thingSize(kind), Arena::thingsPerArena(kind), |
| 908 |
Arena::firstThingOffset(kind) - ArenaHeaderSize); |
| 909 |
} |
| 910 |
} |
| 911 |
|
| 912 |
#endif // JS_GC_ZEAL |
| 913 |
// |
| 914 |
const char* js::gc::AllocKindName(AllocKind kind) { |
| 915 |
static const char* const names[] = { |
| 916 |
#define EXPAND_THING_NAME(allocKind, _1, _2, _3, _4, _5, _6) #allocKind, |
| 917 |
FOR_EACH_ALLOCKIND(EXPAND_THING_NAME) |
| 918 |
#undef EXPAND_THING_NAME |
| 919 |
}; |
| 920 |
static_assert(std::size(names) == AllocKindCount, |
| 921 |
"names array should have an entry for every AllocKind"); |
| 922 |
|
| 923 |
size_t i = size_t(kind); |
| 924 |
MOZ_ASSERT(i < std::size(names)); |
| 925 |
return names[i]; |
| 926 |
} |
| 927 |
|
| 928 |
bool GCRuntime::init(uint32_t maxbytes) { |
| 929 |
MOZ_ASSERT(!wasInitialized()); |
| 930 |
|
| 931 |
MOZ_ASSERT(SystemPageSize()); |
| 932 |
Arena::staticAsserts(); |
| 933 |
Arena::checkLookupTables(); |
| 934 |
|
| 935 |
if (!TlsGCContext.init()) { |
| 936 |
return false; |
| 937 |
} |
| 938 |
TlsGCContext.set(&mainThreadContext.ref()); |
| 939 |
|
| 940 |
updateHelperThreadCount(); |
| 941 |
|
| 942 |
#ifdef JS_GC_ZEAL |
| 943 |
const char* size = getenv("JSGC_MARK_STACK_LIMIT"); |
| 944 |
if (size) { |
| 945 |
maybeMarkStackLimit = atoi(size); |
| 946 |
} |
| 947 |
#endif |
| 948 |
|
| 949 |
if (!updateMarkersVector()) { |
| 950 |
return false; |
| 951 |
} |
| 952 |
|
| 953 |
{ |
| 954 |
AutoLockGCBgAlloc lock(this); |
| 955 |
|
| 956 |
MOZ_ALWAYS_TRUE(tunables.setParameter(JSGC_MAX_BYTES, maxbytes)); |
| 957 |
|
| 958 |
if (!nursery().init(lock)) { |
| 959 |
return false; |
| 960 |
} |
| 961 |
} |
| 962 |
|
| 963 |
#ifdef JS_GC_ZEAL |
| 964 |
const char* zealSpec = getenv("JS_GC_ZEAL"); |
| 965 |
if (zealSpec && zealSpec[0] && !parseAndSetZeal(zealSpec)) { |
| 966 |
return false; |
| 967 |
} |
| 968 |
#endif |
| 969 |
|
| 970 |
for (auto& marker : markers) { |
| 971 |
if (!marker->init()) { |
| 972 |
return false; |
| 973 |
} |
| 974 |
} |
| 975 |
|
| 976 |
if (!initSweepActions()) { |
| 977 |
return false; |
| 978 |
} |
| 979 |
|
| 980 |
UniquePtr<Zone> zone = MakeUnique<Zone>(rt, Zone::AtomsZone); |
| 981 |
if (!zone || !zone->init()) { |
| 982 |
return false; |
| 983 |
} |
| 984 |
|
| 985 |
// The atoms zone is stored as the first element of the zones vector. |
| 986 |
MOZ_ASSERT(zone->isAtomsZone()); |
| 987 |
MOZ_ASSERT(zones().empty()); |
| 988 |
MOZ_ALWAYS_TRUE(zones().reserve(1)); // ZonesVector has inline capacity 4. |
| 989 |
zones().infallibleAppend(zone.release()); |
| 990 |
|
| 991 |
gcprobes::Init(this); |
| 992 |
|
| 993 |
initialized = true; |
| 994 |
return true; |
| 995 |
} |
| 996 |
|
| 997 |
void GCRuntime::finish() { |
| 998 |
MOZ_ASSERT(inPageLoadCount == 0); |
| 999 |
MOZ_ASSERT(!sharedAtomsZone_); |
| 1000 |
|
| 1001 |
// Wait for nursery background free to end and disable it to release memory. |
| 1002 |
if (nursery().isEnabled()) { |
| 1003 |
nursery().disable(); |
| 1004 |
} |
| 1005 |
|
| 1006 |
// Wait until the background finalization and allocation stops and the |
| 1007 |
// helper thread shuts down before we forcefully release any remaining GC |
| 1008 |
// memory. |
| 1009 |
sweepTask.join(); |
| 1010 |
markTask.join(); |
| 1011 |
freeTask.join(); |
| 1012 |
allocTask.cancelAndWait(); |
| 1013 |
decommitTask.cancelAndWait(); |
| 1014 |
#ifdef DEBUG |
| 1015 |
{ |
| 1016 |
MOZ_ASSERT(dispatchedParallelTasks == 0); |
| 1017 |
AutoLockHelperThreadState lock; |
| 1018 |
MOZ_ASSERT(queuedParallelTasks.ref().isEmpty(lock)); |
| 1019 |
} |
| 1020 |
#endif |
| 1021 |
|
| 1022 |
releaseMarkingThreads(); |
| 1023 |
|
| 1024 |
#ifdef JS_GC_ZEAL |
| 1025 |
// Free memory associated with GC verification. |
| 1026 |
finishVerifier(); |
| 1027 |
#endif |
| 1028 |
|
| 1029 |
// Delete all remaining zones. |
| 1030 |
for (ZonesIter zone(this, WithAtoms); !zone.done(); zone.next()) { |
| 1031 |
AutoSetThreadIsSweeping threadIsSweeping(rt->gcContext(), zone); |
| 1032 |
for (CompartmentsInZoneIter comp(zone); !comp.done(); comp.next()) { |
| 1033 |
for (RealmsInCompartmentIter realm(comp); !realm.done(); realm.next()) { |
| 1034 |
js_delete(realm.get()); |
| 1035 |
} |
| 1036 |
comp->realms().clear(); |
| 1037 |
js_delete(comp.get()); |
| 1038 |
} |
| 1039 |
zone->compartments().clear(); |
| 1040 |
js_delete(zone.get()); |
| 1041 |
} |
| 1042 |
|
| 1043 |
zones().clear(); |
| 1044 |
|
| 1045 |
{ |
| 1046 |
AutoLockGC lock(this); |
| 1047 |
clearCurrentChunk(lock); |
| 1048 |
} |
| 1049 |
|
| 1050 |
FreeChunkPool(fullChunks_.ref()); |
| 1051 |
FreeChunkPool(availableChunks_.ref()); |
| 1052 |
FreeChunkPool(emptyChunks_.ref()); |
| 1053 |
|
| 1054 |
TlsGCContext.set(nullptr); |
| 1055 |
|
| 1056 |
gcprobes::Finish(this); |
| 1057 |
|
| 1058 |
nursery().printTotalProfileTimes(); |
| 1059 |
stats().printTotalProfileTimes(); |
| 1060 |
} |
| 1061 |
|
| 1062 |
bool GCRuntime::freezeSharedAtomsZone() { |
| 1063 |
// This is called just after permanent atoms and well-known symbols have been |
| 1064 |
// created. At this point all existing atoms and symbols are permanent. |
| 1065 |
// |
| 1066 |
// This method makes the current atoms zone into a shared atoms zone and |
| 1067 |
// removes it from the zones list. Everything in it is marked black. A new |
| 1068 |
// empty atoms zone is created, where all atoms local to this runtime will |
| 1069 |
// live. |
| 1070 |
// |
| 1071 |
// The shared atoms zone will not be collected until shutdown when it is |
| 1072 |
// returned to the zone list by restoreSharedAtomsZone(). |
| 1073 |
|
| 1074 |
MOZ_ASSERT(rt->isMainRuntime()); |
| 1075 |
MOZ_ASSERT(!sharedAtomsZone_); |
| 1076 |
MOZ_ASSERT(zones().length() == 1); |
| 1077 |
MOZ_ASSERT(atomsZone()); |
| 1078 |
MOZ_ASSERT(!atomsZone()->wasGCStarted()); |
| 1079 |
MOZ_ASSERT(!atomsZone()->needsIncrementalBarrier()); |
| 1080 |
|
| 1081 |
AutoAssertEmptyNursery nurseryIsEmpty(rt->mainContextFromOwnThread()); |
| 1082 |
|
| 1083 |
atomsZone()->arenas.clearFreeLists(); |
| 1084 |
|
| 1085 |
for (auto kind : AllAllocKinds()) { |
| 1086 |
for (auto thing = |
| 1087 |
atomsZone()->cellIterUnsafe<TenuredCell>(kind, nurseryIsEmpty); |
| 1088 |
!thing.done(); thing.next()) { |
| 1089 |
TenuredCell* cell = thing.getCell(); |
| 1090 |
MOZ_ASSERT((cell->is<JSString>() && |
| 1091 |
cell->as<JSString>()->isPermanentAndMayBeShared()) || |
| 1092 |
(cell->is<JS::Symbol>() && |
| 1093 |
cell->as<JS::Symbol>()->isPermanentAndMayBeShared())); |
| 1094 |
cell->markBlack(); |
| 1095 |
} |
| 1096 |
} |
| 1097 |
|
| 1098 |
sharedAtomsZone_ = atomsZone(); |
| 1099 |
zones().clear(); |
| 1100 |
|
| 1101 |
UniquePtr<Zone> zone = MakeUnique<Zone>(rt, Zone::AtomsZone); |
| 1102 |
if (!zone || !zone->init()) { |
| 1103 |
return false; |
| 1104 |
} |
| 1105 |
|
| 1106 |
MOZ_ASSERT(zone->isAtomsZone()); |
| 1107 |
zones().infallibleAppend(zone.release()); |
| 1108 |
|
| 1109 |
return true; |
| 1110 |
} |
| 1111 |
|
| 1112 |
void GCRuntime::restoreSharedAtomsZone() { |
| 1113 |
// Return the shared atoms zone to the zone list. This allows the contents of |
| 1114 |
// the shared atoms zone to be collected when the parent runtime is shut down. |
| 1115 |
|
| 1116 |
if (!sharedAtomsZone_) { |
| 1117 |
return; |
| 1118 |
} |
| 1119 |
|
| 1120 |
MOZ_ASSERT(rt->isMainRuntime()); |
| 1121 |
MOZ_ASSERT(rt->childRuntimeCount == 0); |
| 1122 |
|
| 1123 |
// Insert at start to preserve invariant that atoms zones come first. |
| 1124 |
AutoEnterOOMUnsafeRegion oomUnsafe; |
| 1125 |
if (!zones().insert(zones().begin(), sharedAtomsZone_)) { |
| 1126 |
oomUnsafe.crash("restoreSharedAtomsZone"); |
| 1127 |
} |
| 1128 |
|
| 1129 |
sharedAtomsZone_ = nullptr; |
| 1130 |
} |
| 1131 |
|
| 1132 |
bool GCRuntime::setParameter(JSContext* cx, JSGCParamKey key, uint32_t value) { |
| 1133 |
MOZ_ASSERT(CurrentThreadCanAccessRuntime(rt)); |
| 1134 |
|
| 1135 |
AutoStopVerifyingBarriers pauseVerification(rt, false); |
| 1136 |
FinishGC(cx); |
| 1137 |
waitBackgroundSweepEnd(); |
| 1138 |
|
| 1139 |
// Special case: if there is still an `AutoDisableGenerationalGC` active (eg |
| 1140 |
// from the --no-ggc command-line flag), then do not allow controlling the |
| 1141 |
// state of the nursery. Done here where cx is available. |
| 1142 |
if (key == JSGC_NURSERY_ENABLED && cx->generationalDisabled > 0) { |
| 1143 |
return false; |
| 1144 |
} |
| 1145 |
|
| 1146 |
AutoLockGC lock(this); |
| 1147 |
return setParameter(key, value, lock); |
| 1148 |
} |
| 1149 |
|
| 1150 |
static bool IsGCThreadParameter(JSGCParamKey key) { |
| 1151 |
return key == JSGC_HELPER_THREAD_RATIO || key == JSGC_MAX_HELPER_THREADS || |
| 1152 |
key == JSGC_MAX_MARKING_THREADS; |
| 1153 |
} |
| 1154 |
|
| 1155 |
bool GCRuntime::setParameter(JSGCParamKey key, uint32_t value, |
| 1156 |
AutoLockGC& lock) { |
| 1157 |
switch (key) { |
| 1158 |
case JSGC_SLICE_TIME_BUDGET_MS: |
| 1159 |
defaultTimeBudgetMS_ = value; |
| 1160 |
break; |
| 1161 |
case JSGC_INCREMENTAL_GC_ENABLED: |
| 1162 |
setIncrementalGCEnabled(value != 0); |
| 1163 |
break; |
| 1164 |
case JSGC_PER_ZONE_GC_ENABLED: |
| 1165 |
perZoneGCEnabled = value != 0; |
| 1166 |
break; |
| 1167 |
case JSGC_COMPACTING_ENABLED: |
| 1168 |
compactingEnabled = value != 0; |
| 1169 |
break; |
| 1170 |
case JSGC_NURSERY_ENABLED: { |
| 1171 |
AutoUnlockGC unlock(lock); |
| 1172 |
setNurseryEnabled(value != 0); |
| 1173 |
break; |
| 1174 |
} |
| 1175 |
case JSGC_PARALLEL_MARKING_ENABLED: |
| 1176 |
setParallelMarkingEnabled(value != 0); |
| 1177 |
break; |
| 1178 |
case JSGC_INCREMENTAL_WEAKMAP_ENABLED: |
| 1179 |
for (auto& marker : markers) { |
| 1180 |
marker->incrementalWeakMapMarkingEnabled = value != 0; |
| 1181 |
} |
| 1182 |
break; |
| 1183 |
case JSGC_SEMISPACE_NURSERY_ENABLED: { |
| 1184 |
AutoUnlockGC unlock(lock); |
| 1185 |
nursery().setSemispaceEnabled(value); |
| 1186 |
break; |
| 1187 |
} |
| 1188 |
case JSGC_MIN_EMPTY_CHUNK_COUNT: |
| 1189 |
setMinEmptyChunkCount(value, lock); |
| 1190 |
break; |
| 1191 |
default: |
| 1192 |
if (IsGCThreadParameter(key)) { |
| 1193 |
return setThreadParameter(key, value, lock); |
| 1194 |
} |
| 1195 |
|
| 1196 |
if (!tunables.setParameter(key, value)) { |
| 1197 |
return false; |
| 1198 |
} |
| 1199 |
updateAllGCStartThresholds(); |
| 1200 |
} |
| 1201 |
|
| 1202 |
return true; |
| 1203 |
} |
| 1204 |
|
| 1205 |
bool GCRuntime::setThreadParameter(JSGCParamKey key, uint32_t value, |
| 1206 |
AutoLockGC& lock) { |
| 1207 |
if (rt->parentRuntime) { |
| 1208 |
// Don't allow these to be set for worker runtimes. |
| 1209 |
return false; |
| 1210 |
} |
| 1211 |
|
| 1212 |
switch (key) { |
| 1213 |
case JSGC_HELPER_THREAD_RATIO: |
| 1214 |
if (value == 0) { |
| 1215 |
return false; |
| 1216 |
} |
| 1217 |
helperThreadRatio = double(value) / 100.0; |
| 1218 |
break; |
| 1219 |
case JSGC_MAX_HELPER_THREADS: |
| 1220 |
if (value == 0) { |
| 1221 |
return false; |
| 1222 |
} |
| 1223 |
maxHelperThreads = value; |
| 1224 |
break; |
| 1225 |
case JSGC_MAX_MARKING_THREADS: |
| 1226 |
maxMarkingThreads = std::min(size_t(value), MaxParallelWorkers); |
| 1227 |
break; |
| 1228 |
default: |
| 1229 |
MOZ_CRASH("Unexpected parameter key"); |
| 1230 |
} |
| 1231 |
|
| 1232 |
updateHelperThreadCount(); |
| 1233 |
initOrDisableParallelMarking(); |
| 1234 |
|
| 1235 |
return true; |
| 1236 |
} |
| 1237 |
|
| 1238 |
void GCRuntime::resetParameter(JSContext* cx, JSGCParamKey key) { |
| 1239 |
MOZ_ASSERT(CurrentThreadCanAccessRuntime(rt)); |
| 1240 |
|
| 1241 |
AutoStopVerifyingBarriers pauseVerification(rt, false); |
| 1242 |
FinishGC(cx); |
| 1243 |
waitBackgroundSweepEnd(); |
| 1244 |
|
| 1245 |
AutoLockGC lock(this); |
| 1246 |
resetParameter(key, lock); |
| 1247 |
} |
| 1248 |
|
| 1249 |
void GCRuntime::resetParameter(JSGCParamKey key, AutoLockGC& lock) { |
| 1250 |
switch (key) { |
| 1251 |
case JSGC_SLICE_TIME_BUDGET_MS: |
| 1252 |
defaultTimeBudgetMS_ = TuningDefaults::DefaultTimeBudgetMS; |
| 1253 |
break; |
| 1254 |
case JSGC_INCREMENTAL_GC_ENABLED: |
| 1255 |
setIncrementalGCEnabled(TuningDefaults::IncrementalGCEnabled); |
| 1256 |
break; |
| 1257 |
case JSGC_PER_ZONE_GC_ENABLED: |
| 1258 |
perZoneGCEnabled = TuningDefaults::PerZoneGCEnabled; |
| 1259 |
break; |
| 1260 |
case JSGC_COMPACTING_ENABLED: |
| 1261 |
compactingEnabled = TuningDefaults::CompactingEnabled; |
| 1262 |
break; |
| 1263 |
case JSGC_NURSERY_ENABLED: |
| 1264 |
setNurseryEnabled(TuningDefaults::NurseryEnabled); |
| 1265 |
break; |
| 1266 |
case JSGC_PARALLEL_MARKING_ENABLED: |
| 1267 |
setParallelMarkingEnabled(TuningDefaults::ParallelMarkingEnabled); |
| 1268 |
break; |
| 1269 |
case JSGC_INCREMENTAL_WEAKMAP_ENABLED: |
| 1270 |
for (auto& marker : markers) { |
| 1271 |
marker->incrementalWeakMapMarkingEnabled = |
| 1272 |
TuningDefaults::IncrementalWeakMapMarkingEnabled; |
| 1273 |
} |
| 1274 |
break; |
| 1275 |
case JSGC_SEMISPACE_NURSERY_ENABLED: { |
| 1276 |
AutoUnlockGC unlock(lock); |
| 1277 |
nursery().setSemispaceEnabled(TuningDefaults::SemispaceNurseryEnabled); |
| 1278 |
break; |
| 1279 |
} |
| 1280 |
case JSGC_MIN_EMPTY_CHUNK_COUNT: |
| 1281 |
setMinEmptyChunkCount(TuningDefaults::MinEmptyChunkCount, lock); |
| 1282 |
break; |
| 1283 |
default: |
| 1284 |
if (IsGCThreadParameter(key)) { |
| 1285 |
resetThreadParameter(key, lock); |
| 1286 |
return; |
| 1287 |
} |
| 1288 |
|
| 1289 |
tunables.resetParameter(key); |
| 1290 |
updateAllGCStartThresholds(); |
| 1291 |
} |
| 1292 |
} |
| 1293 |
|
| 1294 |
void GCRuntime::resetThreadParameter(JSGCParamKey key, AutoLockGC& lock) { |
| 1295 |
if (rt->parentRuntime) { |
| 1296 |
return; |
| 1297 |
} |
| 1298 |
|
| 1299 |
switch (key) { |
| 1300 |
case JSGC_HELPER_THREAD_RATIO: |
| 1301 |
helperThreadRatio = TuningDefaults::HelperThreadRatio; |
| 1302 |
break; |
| 1303 |
case JSGC_MAX_HELPER_THREADS: |
| 1304 |
maxHelperThreads = TuningDefaults::MaxHelperThreads; |
| 1305 |
break; |
| 1306 |
case JSGC_MAX_MARKING_THREADS: |
| 1307 |
maxMarkingThreads = TuningDefaults::MaxMarkingThreads; |
| 1308 |
break; |
| 1309 |
default: |
| 1310 |
MOZ_CRASH("Unexpected parameter key"); |
| 1311 |
} |
| 1312 |
|
| 1313 |
updateHelperThreadCount(); |
| 1314 |
initOrDisableParallelMarking(); |
| 1315 |
} |
| 1316 |
|
| 1317 |
uint32_t GCRuntime::getParameter(JSGCParamKey key) { |
| 1318 |
MOZ_ASSERT(CurrentThreadCanAccessRuntime(rt)); |
| 1319 |
AutoLockGC lock(this); |
| 1320 |
return getParameter(key, lock); |
| 1321 |
} |
| 1322 |
|
| 1323 |
uint32_t GCRuntime::getParameter(JSGCParamKey key, const AutoLockGC& lock) { |
| 1324 |
switch (key) { |
| 1325 |
case JSGC_BYTES: |
| 1326 |
return uint32_t(heapSize.bytes()); |
| 1327 |
case JSGC_NURSERY_BYTES: |
| 1328 |
return nursery().capacity(); |
| 1329 |
case JSGC_NUMBER: |
| 1330 |
return uint32_t(number); |
| 1331 |
case JSGC_MAJOR_GC_NUMBER: |
| 1332 |
return uint32_t(majorGCNumber); |
| 1333 |
case JSGC_MINOR_GC_NUMBER: |
| 1334 |
return uint32_t(minorGCNumber); |
| 1335 |
case JSGC_SLICE_NUMBER: |
| 1336 |
return uint32_t(sliceNumber); |
| 1337 |
case JSGC_INCREMENTAL_GC_ENABLED: |
| 1338 |
return incrementalGCEnabled; |
| 1339 |
case JSGC_PER_ZONE_GC_ENABLED: |
| 1340 |
return perZoneGCEnabled; |
| 1341 |
case JSGC_UNUSED_CHUNKS: |
| 1342 |
clearCurrentChunk(lock); |
| 1343 |
return uint32_t(emptyChunks(lock).count()); |
| 1344 |
case JSGC_TOTAL_CHUNKS: |
| 1345 |
clearCurrentChunk(lock); |
| 1346 |
return uint32_t(fullChunks(lock).count() + availableChunks(lock).count() + |
| 1347 |
emptyChunks(lock).count()); |
| 1348 |
case JSGC_SLICE_TIME_BUDGET_MS: |
| 1349 |
MOZ_RELEASE_ASSERT(defaultTimeBudgetMS_ >= 0); |
| 1350 |
MOZ_RELEASE_ASSERT(defaultTimeBudgetMS_ <= UINT32_MAX); |
| 1351 |
return uint32_t(defaultTimeBudgetMS_); |
| 1352 |
case JSGC_MIN_EMPTY_CHUNK_COUNT: |
| 1353 |
return minEmptyChunkCount(lock); |
| 1354 |
case JSGC_COMPACTING_ENABLED: |
| 1355 |
return compactingEnabled; |
| 1356 |
case JSGC_NURSERY_ENABLED: |
| 1357 |
return nursery().isEnabled(); |
| 1358 |
case JSGC_PARALLEL_MARKING_ENABLED: |
| 1359 |
return parallelMarkingEnabled; |
| 1360 |
case JSGC_INCREMENTAL_WEAKMAP_ENABLED: |
| 1361 |
return marker().incrementalWeakMapMarkingEnabled; |
| 1362 |
case JSGC_SEMISPACE_NURSERY_ENABLED: |
| 1363 |
return nursery().semispaceEnabled(); |
| 1364 |
case JSGC_CHUNK_BYTES: |
| 1365 |
return ChunkSize; |
| 1366 |
case JSGC_HELPER_THREAD_RATIO: |
| 1367 |
MOZ_ASSERT(helperThreadRatio > 0.0); |
| 1368 |
return uint32_t(helperThreadRatio * 100.0); |
| 1369 |
case JSGC_MAX_HELPER_THREADS: |
| 1370 |
MOZ_ASSERT(maxHelperThreads <= UINT32_MAX); |
| 1371 |
return maxHelperThreads; |
| 1372 |
case JSGC_HELPER_THREAD_COUNT: |
| 1373 |
return helperThreadCount; |
| 1374 |
case JSGC_MAX_MARKING_THREADS: |
| 1375 |
return maxMarkingThreads; |
| 1376 |
case JSGC_MARKING_THREAD_COUNT: |
| 1377 |
return markingThreadCount; |
| 1378 |
case JSGC_SYSTEM_PAGE_SIZE_KB: |
| 1379 |
return SystemPageSize() / 1024; |
| 1380 |
case JSGC_HIGH_FREQUENCY_MODE: |
| 1381 |
return schedulingState.inHighFrequencyGCMode(); |
| 1382 |
default: |
| 1383 |
return tunables.getParameter(key); |
| 1384 |
} |
| 1385 |
} |
| 1386 |
|
| 1387 |
#ifdef JS_GC_ZEAL |
| 1388 |
void GCRuntime::setMarkStackLimit(size_t limit, AutoLockGC& lock) { |
| 1389 |
MOZ_ASSERT(!JS::RuntimeHeapIsBusy()); |
| 1390 |
|
| 1391 |
maybeMarkStackLimit = limit; |
| 1392 |
|
| 1393 |
AutoUnlockGC unlock(lock); |
| 1394 |
AutoStopVerifyingBarriers pauseVerification(rt, false); |
| 1395 |
for (auto& marker : markers) { |
| 1396 |
marker->setMaxCapacity(limit); |
| 1397 |
} |
| 1398 |
} |
| 1399 |
#endif |
| 1400 |
|
| 1401 |
void GCRuntime::setIncrementalGCEnabled(bool enabled) { |
| 1402 |
incrementalGCEnabled = enabled; |
| 1403 |
} |
| 1404 |
|
| 1405 |
void GCRuntime::setNurseryEnabled(bool enabled) { |
| 1406 |
if (enabled) { |
| 1407 |
nursery().enable(); |
| 1408 |
} else { |
| 1409 |
if (nursery().isEnabled()) { |
| 1410 |
minorGC(JS::GCReason::EVICT_NURSERY); |
| 1411 |
nursery().disable(); |
| 1412 |
} |
| 1413 |
} |
| 1414 |
} |
| 1415 |
|
| 1416 |
void GCRuntime::updateHelperThreadCount() { |
| 1417 |
if (!CanUseExtraThreads()) { |
| 1418 |
// startTask will run the work on the main thread if the count is 1. |
| 1419 |
MOZ_ASSERT(helperThreadCount == 1); |
| 1420 |
markingThreadCount = 1; |
| 1421 |
|
| 1422 |
AutoLockHelperThreadState lock; |
| 1423 |
maxParallelThreads = 1; |
| 1424 |
return; |
| 1425 |
} |
| 1426 |
|
| 1427 |
// Number of extra threads required during parallel marking to ensure we can |
| 1428 |
// start the necessary marking tasks. Background free and background |
| 1429 |
// allocation may already be running and we want to avoid these tasks blocking |
| 1430 |
// marking. In real configurations there will be enough threads that this |
| 1431 |
// won't affect anything. |
| 1432 |
static constexpr size_t SpareThreadsDuringParallelMarking = 2; |
| 1433 |
|
| 1434 |
// Calculate the target thread count for GC parallel tasks. |
| 1435 |
size_t cpuCount = GetHelperThreadCPUCount(); |
| 1436 |
helperThreadCount = |
| 1437 |
std::clamp(size_t(double(cpuCount) * helperThreadRatio.ref()), size_t(1), |
| 1438 |
maxHelperThreads.ref()); |
| 1439 |
|
| 1440 |
// Calculate the target thread count for parallel marking, which uses separate |
| 1441 |
// parameters to let us adjust this independently. |
| 1442 |
markingThreadCount = std::min(cpuCount / 2, maxMarkingThreads.ref()); |
| 1443 |
|
| 1444 |
// Calculate the overall target thread count taking into account the separate |
| 1445 |
// target for parallel marking threads. Add spare threads to avoid blocking |
| 1446 |
// parallel marking when there is other GC work happening. |
| 1447 |
size_t targetCount = |
| 1448 |
std::max(helperThreadCount.ref(), |
| 1449 |
markingThreadCount.ref() + SpareThreadsDuringParallelMarking); |
| 1450 |
|
| 1451 |
// Attempt to create extra threads if possible. This is not supported when |
| 1452 |
// using an external thread pool. |
| 1453 |
AutoLockHelperThreadState lock; |
| 1454 |
(void)HelperThreadState().ensureThreadCount(targetCount, lock); |
| 1455 |
|
| 1456 |
// Limit all thread counts based on the number of threads available, which may |
| 1457 |
// be fewer than requested. |
| 1458 |
size_t availableThreadCount = GetHelperThreadCount(); |
| 1459 |
MOZ_ASSERT(availableThreadCount != 0); |
| 1460 |
targetCount = std::min(targetCount, availableThreadCount); |
| 1461 |
helperThreadCount = std::min(helperThreadCount.ref(), availableThreadCount); |
| 1462 |
if (availableThreadCount < SpareThreadsDuringParallelMarking) { |
| 1463 |
markingThreadCount = 1; |
| 1464 |
} else { |
| 1465 |
markingThreadCount = |
| 1466 |
std::min(markingThreadCount.ref(), |
| 1467 |
availableThreadCount - SpareThreadsDuringParallelMarking); |
| 1468 |
} |
| 1469 |
|
| 1470 |
// Update the maximum number of threads that will be used for GC work. |
| 1471 |
maxParallelThreads = targetCount; |
| 1472 |
} |
| 1473 |
|
| 1474 |
size_t GCRuntime::markingWorkerCount() const { |
| 1475 |
if (!CanUseExtraThreads() || !parallelMarkingEnabled) { |
| 1476 |
return 1; |
| 1477 |
} |
| 1478 |
|
| 1479 |
if (markingThreadCount) { |
| 1480 |
return markingThreadCount; |
| 1481 |
} |
| 1482 |
|
| 1483 |
// Limit parallel marking to use at most two threads initially. |
| 1484 |
return 2; |
| 1485 |
} |
| 1486 |
|
| 1487 |
#ifdef DEBUG |
| 1488 |
void GCRuntime::assertNoMarkingWork() const { |
| 1489 |
for (const auto& marker : markers) { |
| 1490 |
MOZ_ASSERT(marker->isDrained()); |
| 1491 |
} |
| 1492 |
MOZ_ASSERT(!hasDelayedMarking()); |
| 1493 |
} |
| 1494 |
#endif |
| 1495 |
|
| 1496 |
bool GCRuntime::setParallelMarkingEnabled(bool enabled) { |
| 1497 |
if (enabled == parallelMarkingEnabled) { |
| 1498 |
return true; |
| 1499 |
} |
| 1500 |
|
| 1501 |
parallelMarkingEnabled = enabled; |
| 1502 |
return initOrDisableParallelMarking(); |
| 1503 |
} |
| 1504 |
|
| 1505 |
bool GCRuntime::initOrDisableParallelMarking() { |
| 1506 |
// Attempt to initialize parallel marking state or disable it on failure. This |
| 1507 |
// is called when parallel marking is enabled or disabled. |
| 1508 |
|
| 1509 |
MOZ_ASSERT(markers.length() != 0); |
| 1510 |
|
| 1511 |
if (updateMarkersVector()) { |
| 1512 |
return true; |
| 1513 |
} |
| 1514 |
|
| 1515 |
// Failed to initialize parallel marking so disable it instead. |
| 1516 |
MOZ_ASSERT(parallelMarkingEnabled); |
| 1517 |
parallelMarkingEnabled = false; |
| 1518 |
MOZ_ALWAYS_TRUE(updateMarkersVector()); |
| 1519 |
return false; |
| 1520 |
} |
| 1521 |
|
| 1522 |
void GCRuntime::releaseMarkingThreads() { |
| 1523 |
MOZ_ALWAYS_TRUE(reserveMarkingThreads(0)); |
| 1524 |
} |
| 1525 |
|
| 1526 |
bool GCRuntime::reserveMarkingThreads(size_t newCount) { |
| 1527 |
if (reservedMarkingThreads == newCount) { |
| 1528 |
return true; |
| 1529 |
} |
| 1530 |
|
| 1531 |
// Update the helper thread system's global count by subtracting this |
| 1532 |
// runtime's current contribution |reservedMarkingThreads| and adding the new |
| 1533 |
// contribution |newCount|. |
| 1534 |
|
| 1535 |
AutoLockHelperThreadState lock; |
| 1536 |
auto& globalCount = HelperThreadState().gcParallelMarkingThreads; |
| 1537 |
MOZ_ASSERT(globalCount >= reservedMarkingThreads); |
| 1538 |
size_t newGlobalCount = globalCount - reservedMarkingThreads + newCount; |
| 1539 |
if (newGlobalCount > HelperThreadState().threadCount) { |
| 1540 |
// Not enough total threads. |
| 1541 |
return false; |
| 1542 |
} |
| 1543 |
|
| 1544 |
globalCount = newGlobalCount; |
| 1545 |
reservedMarkingThreads = newCount; |
| 1546 |
return true; |
| 1547 |
} |
| 1548 |
|
| 1549 |
size_t GCRuntime::getMaxParallelThreads() const { |
| 1550 |
AutoLockHelperThreadState lock; |
| 1551 |
return maxParallelThreads.ref(); |
| 1552 |
} |
| 1553 |
|
| 1554 |
bool GCRuntime::updateMarkersVector() { |
| 1555 |
MOZ_ASSERT(helperThreadCount >= 1, |
| 1556 |
"There must always be at least one mark task"); |
| 1557 |
MOZ_ASSERT(CurrentThreadCanAccessRuntime(rt)); |
| 1558 |
assertNoMarkingWork(); |
| 1559 |
|
| 1560 |
// Limit worker count to number of GC parallel tasks that can run |
| 1561 |
// concurrently, otherwise one thread can deadlock waiting on another. |
| 1562 |
size_t targetCount = std::min(markingWorkerCount(), getMaxParallelThreads()); |
| 1563 |
|
| 1564 |
if (rt->isMainRuntime()) { |
| 1565 |
// For the main runtime, reserve helper threads as long as parallel marking |
| 1566 |
// is enabled. Worker runtimes may not mark in parallel if there are |
| 1567 |
// insufficient threads available at the time. |
| 1568 |
size_t threadsToReserve = targetCount > 1 ? targetCount : 0; |
| 1569 |
if (!reserveMarkingThreads(threadsToReserve)) { |
| 1570 |
return false; |
| 1571 |
} |
| 1572 |
} |
| 1573 |
|
| 1574 |
if (markers.length() > targetCount) { |
| 1575 |
return markers.resize(targetCount); |
| 1576 |
} |
| 1577 |
|
| 1578 |
while (markers.length() < targetCount) { |
| 1579 |
auto marker = MakeUnique<GCMarker>(rt); |
| 1580 |
if (!marker) { |
| 1581 |
return false; |
| 1582 |
} |
| 1583 |
|
| 1584 |
#ifdef JS_GC_ZEAL |
| 1585 |
if (maybeMarkStackLimit) { |
| 1586 |
marker->setMaxCapacity(maybeMarkStackLimit); |
| 1587 |
} |
| 1588 |
#endif |
| 1589 |
|
| 1590 |
if (!marker->init()) { |
| 1591 |
return false; |
| 1592 |
} |
| 1593 |
|
| 1594 |
if (!markers.emplaceBack(std::move(marker))) { |
| 1595 |
return false; |
| 1596 |
} |
| 1597 |
} |
| 1598 |
|
| 1599 |
return true; |
| 1600 |
} |
| 1601 |
|
| 1602 |
template <typename F> |
| 1603 |
static bool EraseCallback(CallbackVector<F>& vector, F callback) { |
| 1604 |
for (Callback<F>* p = vector.begin(); p != vector.end(); p++) { |
| 1605 |
if (p->op == callback) { |
| 1606 |
vector.erase(p); |
| 1607 |
return true; |
| 1608 |
} |
| 1609 |
} |
| 1610 |
|
| 1611 |
return false; |
| 1612 |
} |
| 1613 |
|
| 1614 |
template <typename F> |
| 1615 |
static bool EraseCallback(CallbackVector<F>& vector, F callback, void* data) { |
| 1616 |
for (Callback<F>* p = vector.begin(); p != vector.end(); p++) { |
| 1617 |
if (p->op == callback && p->data == data) { |
| 1618 |
vector.erase(p); |
| 1619 |
return true; |
| 1620 |
} |
| 1621 |
} |
| 1622 |
|
| 1623 |
return false; |
| 1624 |
} |
| 1625 |
|
| 1626 |
bool GCRuntime::addBlackRootsTracer(JSTraceDataOp traceOp, void* data) { |
| 1627 |
AssertHeapIsIdle(); |
| 1628 |
return blackRootTracers.ref().append(Callback<JSTraceDataOp>(traceOp, data)); |
| 1629 |
} |
| 1630 |
|
| 1631 |
void GCRuntime::removeBlackRootsTracer(JSTraceDataOp traceOp, void* data) { |
| 1632 |
// Can be called from finalizers |
| 1633 |
MOZ_ALWAYS_TRUE(EraseCallback(blackRootTracers.ref(), traceOp, data)); |
| 1634 |
} |
| 1635 |
|
| 1636 |
void GCRuntime::setGrayRootsTracer(JSGrayRootsTracer traceOp, void* data) { |
| 1637 |
AssertHeapIsIdle(); |
| 1638 |
grayRootTracer.ref() = {traceOp, data}; |
| 1639 |
} |
| 1640 |
|
| 1641 |
void GCRuntime::clearBlackAndGrayRootTracers() { |
| 1642 |
MOZ_ASSERT(rt->isBeingDestroyed()); |
| 1643 |
blackRootTracers.ref().clear(); |
| 1644 |
setGrayRootsTracer(nullptr, nullptr); |
| 1645 |
} |
| 1646 |
|
| 1647 |
void GCRuntime::setGCCallback(JSGCCallback callback, void* data) { |
| 1648 |
gcCallback.ref() = {callback, data}; |
| 1649 |
} |
| 1650 |
|
| 1651 |
void GCRuntime::callGCCallback(JSGCStatus status, JS::GCReason reason) const { |
| 1652 |
const auto& callback = gcCallback.ref(); |
| 1653 |
MOZ_ASSERT(callback.op); |
| 1654 |
callback.op(rt->mainContextFromOwnThread(), status, reason, callback.data); |
| 1655 |
} |
| 1656 |
|
| 1657 |
void GCRuntime::setObjectsTenuredCallback(JSObjectsTenuredCallback callback, |
| 1658 |
void* data) { |
| 1659 |
tenuredCallback.ref() = {callback, data}; |
| 1660 |
} |
| 1661 |
|
| 1662 |
void GCRuntime::callObjectsTenuredCallback() { |
| 1663 |
JS::AutoSuppressGCAnalysis nogc; |
| 1664 |
const auto& callback = tenuredCallback.ref(); |
| 1665 |
if (callback.op) { |
| 1666 |
callback.op(&mainThreadContext.ref(), callback.data); |
| 1667 |
} |
| 1668 |
} |
| 1669 |
|
| 1670 |
bool GCRuntime::addFinalizeCallback(JSFinalizeCallback callback, void* data) { |
| 1671 |
return finalizeCallbacks.ref().append( |
| 1672 |
Callback<JSFinalizeCallback>(callback, data)); |
| 1673 |
} |
| 1674 |
|
| 1675 |
void GCRuntime::removeFinalizeCallback(JSFinalizeCallback callback) { |
| 1676 |
MOZ_ALWAYS_TRUE(EraseCallback(finalizeCallbacks.ref(), callback)); |
| 1677 |
} |
| 1678 |
|
| 1679 |
void GCRuntime::callFinalizeCallbacks(JS::GCContext* gcx, |
| 1680 |
JSFinalizeStatus status) const { |
| 1681 |
for (const auto& p : finalizeCallbacks.ref()) { |
| 1682 |
p.op(gcx, status, p.data); |
| 1683 |
} |
| 1684 |
} |
| 1685 |
|
| 1686 |
void GCRuntime::setHostCleanupFinalizationRegistryCallback( |
| 1687 |
JSHostCleanupFinalizationRegistryCallback callback, void* data) { |
| 1688 |
hostCleanupFinalizationRegistryCallback.ref() = {callback, data}; |
| 1689 |
} |
| 1690 |
|
| 1691 |
void GCRuntime::callHostCleanupFinalizationRegistryCallback( |
| 1692 |
JSFunction* doCleanup, JSObject* hostDefinedData) { |
| 1693 |
JS::AutoSuppressGCAnalysis nogc; |
| 1694 |
const auto& callback = hostCleanupFinalizationRegistryCallback.ref(); |
| 1695 |
if (callback.op) { |
| 1696 |
callback.op(doCleanup, hostDefinedData, callback.data); |
| 1697 |
} |
| 1698 |
} |
| 1699 |
|
| 1700 |
bool GCRuntime::addWeakPointerZonesCallback(JSWeakPointerZonesCallback callback, |
| 1701 |
void* data) { |
| 1702 |
return updateWeakPointerZonesCallbacks.ref().append( |
| 1703 |
Callback<JSWeakPointerZonesCallback>(callback, data)); |
| 1704 |
} |
| 1705 |
|
| 1706 |
void GCRuntime::removeWeakPointerZonesCallback( |
| 1707 |
JSWeakPointerZonesCallback callback) { |
| 1708 |
MOZ_ALWAYS_TRUE( |
| 1709 |
EraseCallback(updateWeakPointerZonesCallbacks.ref(), callback)); |
| 1710 |
} |
| 1711 |
|
| 1712 |
void GCRuntime::callWeakPointerZonesCallbacks(JSTracer* trc) const { |
| 1713 |
for (auto const& p : updateWeakPointerZonesCallbacks.ref()) { |
| 1714 |
p.op(trc, p.data); |
| 1715 |
} |
| 1716 |
} |
| 1717 |
|
| 1718 |
bool GCRuntime::addWeakPointerCompartmentCallback( |
| 1719 |
JSWeakPointerCompartmentCallback callback, void* data) { |
| 1720 |
return updateWeakPointerCompartmentCallbacks.ref().append( |
| 1721 |
Callback<JSWeakPointerCompartmentCallback>(callback, data)); |
| 1722 |
} |
| 1723 |
|
| 1724 |
void GCRuntime::removeWeakPointerCompartmentCallback( |
| 1725 |
JSWeakPointerCompartmentCallback callback) { |
| 1726 |
MOZ_ALWAYS_TRUE( |
| 1727 |
EraseCallback(updateWeakPointerCompartmentCallbacks.ref(), callback)); |
| 1728 |
} |
| 1729 |
|
| 1730 |
void GCRuntime::callWeakPointerCompartmentCallbacks( |
| 1731 |
JSTracer* trc, JS::Compartment* comp) const { |
| 1732 |
for (auto const& p : updateWeakPointerCompartmentCallbacks.ref()) { |
| 1733 |
p.op(trc, comp, p.data); |
| 1734 |
} |
| 1735 |
} |
| 1736 |
|
| 1737 |
JS::GCSliceCallback GCRuntime::setSliceCallback(JS::GCSliceCallback callback) { |
| 1738 |
return stats().setSliceCallback(callback); |
| 1739 |
} |
| 1740 |
|
| 1741 |
bool GCRuntime::addNurseryCollectionCallback( |
| 1742 |
JS::GCNurseryCollectionCallback callback, void* data) { |
| 1743 |
return nurseryCollectionCallbacks.ref().append( |
| 1744 |
Callback<JS::GCNurseryCollectionCallback>(callback, data)); |
| 1745 |
} |
| 1746 |
|
| 1747 |
void GCRuntime::removeNurseryCollectionCallback( |
| 1748 |
JS::GCNurseryCollectionCallback callback, void* data) { |
| 1749 |
MOZ_ALWAYS_TRUE( |
| 1750 |
EraseCallback(nurseryCollectionCallbacks.ref(), callback, data)); |
| 1751 |
} |
| 1752 |
|
| 1753 |
void GCRuntime::callNurseryCollectionCallbacks(JS::GCNurseryProgress progress, |
| 1754 |
JS::GCReason reason) { |
| 1755 |
for (auto const& p : nurseryCollectionCallbacks.ref()) { |
| 1756 |
p.op(rt->mainContextFromOwnThread(), progress, reason, p.data); |
| 1757 |
} |
| 1758 |
} |
| 1759 |
|
| 1760 |
JS::DoCycleCollectionCallback GCRuntime::setDoCycleCollectionCallback( |
| 1761 |
JS::DoCycleCollectionCallback callback) { |
| 1762 |
const auto prior = gcDoCycleCollectionCallback.ref(); |
| 1763 |
gcDoCycleCollectionCallback.ref() = {callback, nullptr}; |
| 1764 |
return prior.op; |
| 1765 |
} |
| 1766 |
|
| 1767 |
void GCRuntime::callDoCycleCollectionCallback(JSContext* cx) { |
| 1768 |
const auto& callback = gcDoCycleCollectionCallback.ref(); |
| 1769 |
if (callback.op) { |
| 1770 |
callback.op(cx); |
| 1771 |
} |
| 1772 |
} |
| 1773 |
|
| 1774 |
bool GCRuntime::addRoot(Value* vp, const char* name) { |
| 1775 |
/* |
| 1776 |
* Sometimes Firefox will hold weak references to objects and then convert |
| 1777 |
* them to strong references by calling AddRoot (e.g., via PreserveWrapper, |
| 1778 |
* or ModifyBusyCount in workers). We need a read barrier to cover these |
| 1779 |
* cases. |
| 1780 |
*/ |
| 1781 |
MOZ_ASSERT(vp); |
| 1782 |
Value value = *vp; |
| 1783 |
if (value.isGCThing()) { |
| 1784 |
ValuePreWriteBarrier(value); |
| 1785 |
} |
| 1786 |
|
| 1787 |
return rootsHash.ref().put(vp, name); |
| 1788 |
} |
| 1789 |
|
| 1790 |
void GCRuntime::removeRoot(Value* vp) { |
| 1791 |
rootsHash.ref().remove(vp); |
| 1792 |
notifyRootsRemoved(); |
| 1793 |
} |
| 1794 |
|
| 1795 |
/* Compacting GC */ |
| 1796 |
|
| 1797 |
bool js::gc::IsCurrentlyAnimating(const TimeStamp& lastAnimationTime, |
| 1798 |
const TimeStamp& currentTime) { |
| 1799 |
// Assume that we're currently animating if js::NotifyAnimationActivity has |
| 1800 |
// been called in the last second. |
| 1801 |
static const auto oneSecond = TimeDuration::FromSeconds(1); |
| 1802 |
return !lastAnimationTime.IsNull() && |
| 1803 |
currentTime < (lastAnimationTime + oneSecond); |
| 1804 |
} |
| 1805 |
|
| 1806 |
static bool DiscardedCodeRecently(Zone* zone, const TimeStamp& currentTime) { |
| 1807 |
static const auto thirtySeconds = TimeDuration::FromSeconds(30); |
| 1808 |
return !zone->lastDiscardedCodeTime().IsNull() && |
| 1809 |
currentTime < (zone->lastDiscardedCodeTime() + thirtySeconds); |
| 1810 |
} |
| 1811 |
|
| 1812 |
bool GCRuntime::shouldCompact() { |
| 1813 |
// Compact on shrinking GC if enabled. Skip compacting in incremental GCs |
| 1814 |
// if we are currently animating, unless the user is inactive or we're |
| 1815 |
// responding to memory pressure. |
| 1816 |
|
| 1817 |
if (!isShrinkingGC() || !isCompactingGCEnabled()) { |
| 1818 |
return false; |
| 1819 |
} |
| 1820 |
|
| 1821 |
if (initialReason == JS::GCReason::USER_INACTIVE || |
| 1822 |
initialReason == JS::GCReason::MEM_PRESSURE) { |
| 1823 |
return true; |
| 1824 |
} |
| 1825 |
|
| 1826 |
return !isIncremental || |
| 1827 |
!IsCurrentlyAnimating(rt->lastAnimationTime, TimeStamp::Now()); |
| 1828 |
} |
| 1829 |
|
| 1830 |
bool GCRuntime::isCompactingGCEnabled() const { |
| 1831 |
return compactingEnabled && |
| 1832 |
rt->mainContextFromOwnThread()->compactingDisabledCount == 0; |
| 1833 |
} |
| 1834 |
|
| 1835 |
JS_PUBLIC_API void JS::SetCreateGCSliceBudgetCallback( |
| 1836 |
JSContext* cx, JS::CreateSliceBudgetCallback cb) { |
| 1837 |
cx->runtime()->gc.createBudgetCallback = cb; |
| 1838 |
} |
| 1839 |
|
| 1840 |
void TimeBudget::setDeadlineFromNow() { deadline = TimeStamp::Now() + budget; } |
| 1841 |
|
| 1842 |
SliceBudget::SliceBudget(TimeBudget time, InterruptRequestFlag* interrupt) |
| 1843 |
: counter(StepsPerExpensiveCheck), |
| 1844 |
interruptRequested(interrupt), |
| 1845 |
budget(TimeBudget(time)) { |
| 1846 |
budget.as<TimeBudget>().setDeadlineFromNow(); |
| 1847 |
} |
| 1848 |
|
| 1849 |
SliceBudget::SliceBudget(WorkBudget work) |
| 1850 |
: counter(work.budget), interruptRequested(nullptr), budget(work) {} |
| 1851 |
|
| 1852 |
int SliceBudget::describe(char* buffer, size_t maxlen) const { |
| 1853 |
if (isUnlimited()) { |
| 1854 |
return snprintf(buffer, maxlen, "unlimited"); |
| 1855 |
} |
| 1856 |
|
| 1857 |
if (isWorkBudget()) { |
| 1858 |
return snprintf(buffer, maxlen, "work(%" PRId64 ")", workBudget()); |
| 1859 |
} |
| 1860 |
|
| 1861 |
const char* interruptStr = ""; |
| 1862 |
if (interruptRequested) { |
| 1863 |
interruptStr = interrupted ? "INTERRUPTED " : "interruptible "; |
| 1864 |
} |
| 1865 |
const char* extra = ""; |
| 1866 |
if (idle) { |
| 1867 |
extra = extended ? " (started idle but extended)" : " (idle)"; |
| 1868 |
} |
| 1869 |
return snprintf(buffer, maxlen, "%s%" PRId64 "ms%s", interruptStr, |
| 1870 |
timeBudget(), extra); |
| 1871 |
} |
| 1872 |
|
| 1873 |
bool SliceBudget::checkOverBudget() { |
| 1874 |
MOZ_ASSERT(counter <= 0); |
| 1875 |
MOZ_ASSERT(!isUnlimited()); |
| 1876 |
|
| 1877 |
if (isWorkBudget()) { |
| 1878 |
return true; |
| 1879 |
} |
| 1880 |
|
| 1881 |
if (interruptRequested && *interruptRequested) { |
| 1882 |
interrupted = true; |
| 1883 |
} |
| 1884 |
|
| 1885 |
if (interrupted) { |
| 1886 |
return true; |
| 1887 |
} |
| 1888 |
|
| 1889 |
if (TimeStamp::Now() >= budget.as<TimeBudget>().deadline) { |
| 1890 |
return true; |
| 1891 |
} |
| 1892 |
|
| 1893 |
counter = StepsPerExpensiveCheck; |
| 1894 |
return false; |
| 1895 |
} |
| 1896 |
|
| 1897 |
void GCRuntime::requestMajorGC(JS::GCReason reason) { |
| 1898 |
MOZ_ASSERT_IF(reason != JS::GCReason::BG_TASK_FINISHED, |
| 1899 |
!CurrentThreadIsPerformingGC()); |
| 1900 |
|
| 1901 |
if (majorGCRequested()) { |
| 1902 |
return; |
| 1903 |
} |
| 1904 |
|
| 1905 |
majorGCTriggerReason = reason; |
| 1906 |
rt->mainContextFromAnyThread()->requestInterrupt(InterruptReason::MajorGC); |
| 1907 |
} |
| 1908 |
|
| 1909 |
bool GCRuntime::triggerGC(JS::GCReason reason) { |
| 1910 |
/* |
| 1911 |
* Don't trigger GCs if this is being called off the main thread from |
| 1912 |
* onTooMuchMalloc(). |
| 1913 |
*/ |
| 1914 |
if (!CurrentThreadCanAccessRuntime(rt)) { |
| 1915 |
return false; |
| 1916 |
} |
| 1917 |
|
| 1918 |
/* GC is already running. */ |
| 1919 |
if (JS::RuntimeHeapIsCollecting()) { |
| 1920 |
return false; |
| 1921 |
} |
| 1922 |
|
| 1923 |
JS::PrepareForFullGC(rt->mainContextFromOwnThread()); |
| 1924 |
requestMajorGC(reason); |
| 1925 |
return true; |
| 1926 |
} |
| 1927 |
|
| 1928 |
void GCRuntime::maybeTriggerGCAfterAlloc(Zone* zone) { |
| 1929 |
MOZ_ASSERT(CurrentThreadCanAccessRuntime(rt)); |
| 1930 |
MOZ_ASSERT(!JS::RuntimeHeapIsCollecting()); |
| 1931 |
|
| 1932 |
TriggerResult trigger = |
| 1933 |
checkHeapThreshold(zone, zone->gcHeapSize, zone->gcHeapThreshold); |
| 1934 |
|
| 1935 |
if (trigger.shouldTrigger) { |
| 1936 |
// Start or continue an in progress incremental GC. We do this to try to |
| 1937 |
// avoid performing non-incremental GCs on zones which allocate a lot of |
| 1938 |
// data, even when incremental slices can't be triggered via scheduling in |
| 1939 |
// the event loop. |
| 1940 |
triggerZoneGC(zone, JS::GCReason::ALLOC_TRIGGER, trigger.usedBytes, |
| 1941 |
trigger.thresholdBytes); |
| 1942 |
} |
| 1943 |
} |
| 1944 |
|
| 1945 |
void js::gc::MaybeMallocTriggerZoneGC(JSRuntime* rt, ZoneAllocator* zoneAlloc, |
| 1946 |
const HeapSize& heap, |
| 1947 |
const HeapThreshold& threshold, |
| 1948 |
JS::GCReason reason) { |
| 1949 |
rt->gc.maybeTriggerGCAfterMalloc(Zone::from(zoneAlloc), heap, threshold, |
| 1950 |
reason); |
| 1951 |
} |
| 1952 |
|
| 1953 |
void GCRuntime::maybeTriggerGCAfterMalloc(Zone* zone) { |
| 1954 |
if (maybeTriggerGCAfterMalloc(zone, zone->mallocHeapSize, |
| 1955 |
zone->mallocHeapThreshold, |
| 1956 |
JS::GCReason::TOO_MUCH_MALLOC)) { |
| 1957 |
return; |
| 1958 |
} |
| 1959 |
|
| 1960 |
maybeTriggerGCAfterMalloc(zone, zone->jitHeapSize, zone->jitHeapThreshold, |
| 1961 |
JS::GCReason::TOO_MUCH_JIT_CODE); |
| 1962 |
} |
| 1963 |
|
| 1964 |
bool GCRuntime::maybeTriggerGCAfterMalloc(Zone* zone, const HeapSize& heap, |
| 1965 |
const HeapThreshold& threshold, |
| 1966 |
JS::GCReason reason) { |
| 1967 |
// Ignore malloc during sweeping, for example when we resize hash tables. |
| 1968 |
if (heapState() != JS::HeapState::Idle) { |
| 1969 |
return false; |
| 1970 |
} |
| 1971 |
|
| 1972 |
MOZ_ASSERT(CurrentThreadCanAccessRuntime(rt)); |
| 1973 |
|
| 1974 |
TriggerResult trigger = checkHeapThreshold(zone, heap, threshold); |
| 1975 |
if (!trigger.shouldTrigger) { |
| 1976 |
return false; |
| 1977 |
} |
| 1978 |
|
| 1979 |
// Trigger a zone GC. budgetIncrementalGC() will work out whether to do an |
| 1980 |
// incremental or non-incremental collection. |
| 1981 |
triggerZoneGC(zone, reason, trigger.usedBytes, trigger.thresholdBytes); |
| 1982 |
return true; |
| 1983 |
} |
| 1984 |
|
| 1985 |
TriggerResult GCRuntime::checkHeapThreshold( |
| 1986 |
Zone* zone, const HeapSize& heapSize, const HeapThreshold& heapThreshold) { |
| 1987 |
MOZ_ASSERT_IF(heapThreshold.hasSliceThreshold(), zone->wasGCStarted()); |
| 1988 |
|
| 1989 |
size_t usedBytes = heapSize.bytes(); |
| 1990 |
size_t thresholdBytes = heapThreshold.hasSliceThreshold() |
| 1991 |
? heapThreshold.sliceBytes() |
| 1992 |
: heapThreshold.startBytes(); |
| 1993 |
|
| 1994 |
// The incremental limit will be checked if we trigger a GC slice. |
| 1995 |
MOZ_ASSERT(thresholdBytes <= heapThreshold.incrementalLimitBytes()); |
| 1996 |
|
| 1997 |
return TriggerResult{usedBytes >= thresholdBytes, usedBytes, thresholdBytes}; |
| 1998 |
} |
| 1999 |
|
| 2000 |
bool GCRuntime::triggerZoneGC(Zone* zone, JS::GCReason reason, size_t used, |
| 2001 |
size_t threshold) { |
| 2002 |
MOZ_ASSERT(CurrentThreadCanAccessRuntime(rt)); |
| 2003 |
|
| 2004 |
/* GC is already running. */ |
| 2005 |
if (JS::RuntimeHeapIsBusy()) { |
| 2006 |
return false; |
| 2007 |
} |
| 2008 |
|
| 2009 |
#ifdef JS_GC_ZEAL |
| 2010 |
if (hasZealMode(ZealMode::Alloc)) { |
| 2011 |
MOZ_RELEASE_ASSERT(triggerGC(reason)); |
| 2012 |
return true; |
| 2013 |
} |
| 2014 |
#endif |
| 2015 |
|
| 2016 |
if (zone->isAtomsZone()) { |
| 2017 |
stats().recordTrigger(used, threshold); |
| 2018 |
MOZ_RELEASE_ASSERT(triggerGC(reason)); |
| 2019 |
return true; |
| 2020 |
} |
| 2021 |
|
| 2022 |
stats().recordTrigger(used, threshold); |
| 2023 |
zone->scheduleGC(); |
| 2024 |
requestMajorGC(reason); |
| 2025 |
return true; |
| 2026 |
} |
| 2027 |
|
| 2028 |
void GCRuntime::maybeGC() { |
| 2029 |
MOZ_ASSERT(CurrentThreadCanAccessRuntime(rt)); |
| 2030 |
|
| 2031 |
#ifdef JS_GC_ZEAL |
| 2032 |
if (hasZealMode(ZealMode::Alloc) || hasZealMode(ZealMode::RootsChange)) { |
| 2033 |
JS::PrepareForFullGC(rt->mainContextFromOwnThread()); |
| 2034 |
gc(JS::GCOptions::Normal, JS::GCReason::DEBUG_GC); |
| 2035 |
return; |
| 2036 |
} |
| 2037 |
#endif |
| 2038 |
|
| 2039 |
(void)gcIfRequestedImpl(/* eagerOk = */ true); |
| 2040 |
} |
| 2041 |
|
| 2042 |
JS::GCReason GCRuntime::wantMajorGC(bool eagerOk) { |
| 2043 |
MOZ_ASSERT(CurrentThreadCanAccessRuntime(rt)); |
| 2044 |
|
| 2045 |
if (majorGCRequested()) { |
| 2046 |
return majorGCTriggerReason; |
| 2047 |
} |
| 2048 |
|
| 2049 |
if (isIncrementalGCInProgress() || !eagerOk) { |
| 2050 |
return JS::GCReason::NO_REASON; |
| 2051 |
} |
| 2052 |
|
| 2053 |
JS::GCReason reason = JS::GCReason::NO_REASON; |
| 2054 |
for (ZonesIter zone(this, WithAtoms); !zone.done(); zone.next()) { |
| 2055 |
if (checkEagerAllocTrigger(zone->gcHeapSize, zone->gcHeapThreshold) || |
| 2056 |
checkEagerAllocTrigger(zone->mallocHeapSize, |
| 2057 |
zone->mallocHeapThreshold)) { |
| 2058 |
zone->scheduleGC(); |
| 2059 |
reason = JS::GCReason::EAGER_ALLOC_TRIGGER; |
| 2060 |
} |
| 2061 |
} |
| 2062 |
|
| 2063 |
return reason; |
| 2064 |
} |
| 2065 |
|
| 2066 |
bool GCRuntime::checkEagerAllocTrigger(const HeapSize& size, |
| 2067 |
const HeapThreshold& threshold) { |
| 2068 |
size_t thresholdBytes = |
| 2069 |
threshold.eagerAllocTrigger(schedulingState.inHighFrequencyGCMode()); |
| 2070 |
size_t usedBytes = size.bytes(); |
| 2071 |
if (usedBytes <= 1024 * 1024 || usedBytes < thresholdBytes) { |
| 2072 |
return false; |
| 2073 |
} |
| 2074 |
|
| 2075 |
stats().recordTrigger(usedBytes, thresholdBytes); |
| 2076 |
return true; |
| 2077 |
} |
| 2078 |
|
| 2079 |
bool GCRuntime::shouldDecommit() const { |
| 2080 |
switch (gcOptions()) { |
| 2081 |
case JS::GCOptions::Normal: |
| 2082 |
// If we are allocating heavily enough to trigger "high frequency" GC then |
| 2083 |
// skip decommit so that we do not compete with the mutator. |
| 2084 |
return !schedulingState.inHighFrequencyGCMode(); |
| 2085 |
case JS::GCOptions::Shrink: |
| 2086 |
// If we're doing a shrinking GC we always decommit to release as much |
| 2087 |
// memory as possible. |
| 2088 |
return true; |
| 2089 |
case JS::GCOptions::Shutdown: |
| 2090 |
// There's no point decommitting as we are about to free everything. |
| 2091 |
return false; |
| 2092 |
} |
| 2093 |
|
| 2094 |
MOZ_CRASH("Unexpected GCOptions value"); |
| 2095 |
} |
| 2096 |
|
| 2097 |
void GCRuntime::startDecommit() { |
| 2098 |
gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::DECOMMIT); |
| 2099 |
|
| 2100 |
#ifdef DEBUG |
| 2101 |
MOZ_ASSERT(CurrentThreadCanAccessRuntime(rt)); |
| 2102 |
MOZ_ASSERT(decommitTask.isIdle()); |
| 2103 |
|
| 2104 |
{ |
| 2105 |
AutoLockGC lock(this); |
| 2106 |
MOZ_ASSERT(fullChunks(lock).verify()); |
| 2107 |
MOZ_ASSERT(availableChunks(lock).verify()); |
| 2108 |
MOZ_ASSERT(emptyChunks(lock).verify()); |
| 2109 |
|
| 2110 |
// Verify that all entries in the empty chunks pool are unused. |
| 2111 |
for (ChunkPool::Iter chunk(emptyChunks(lock)); !chunk.done(); |
| 2112 |
chunk.next()) { |
| 2113 |
MOZ_ASSERT(chunk->isEmpty()); |
| 2114 |
} |
| 2115 |
} |
| 2116 |
#endif |
| 2117 |
|
| 2118 |
if (!shouldDecommit()) { |
| 2119 |
return; |
| 2120 |
} |
| 2121 |
|
| 2122 |
{ |
| 2123 |
AutoLockGC lock(this); |
| 2124 |
if (availableChunks(lock).empty() && !tooManyEmptyChunks(lock) && |
| 2125 |
emptyChunks(lock).empty()) { |
| 2126 |
return; // Nothing to do. |
| 2127 |
} |
| 2128 |
} |
| 2129 |
|
| 2130 |
#ifdef DEBUG |
| 2131 |
{ |
| 2132 |
AutoLockHelperThreadState lock; |
| 2133 |
MOZ_ASSERT(!requestSliceAfterBackgroundTask); |
| 2134 |
} |
| 2135 |
#endif |
| 2136 |
|
| 2137 |
if (useBackgroundThreads) { |
| 2138 |
decommitTask.start(); |
| 2139 |
return; |
| 2140 |
} |
| 2141 |
|
| 2142 |
decommitTask.runFromMainThread(); |
| 2143 |
} |
| 2144 |
|
| 2145 |
BackgroundDecommitTask::BackgroundDecommitTask(GCRuntime* gc) |
| 2146 |
: GCParallelTask(gc, gcstats::PhaseKind::DECOMMIT) {} |
| 2147 |
|
| 2148 |
void js::gc::BackgroundDecommitTask::run(AutoLockHelperThreadState& lock) { |
| 2149 |
{ |
| 2150 |
AutoUnlockHelperThreadState unlock(lock); |
| 2151 |
|
| 2152 |
ChunkPool emptyChunksToFree; |
| 2153 |
{ |
| 2154 |
AutoLockGC gcLock(gc); |
| 2155 |
emptyChunksToFree = gc->expireEmptyChunkPool(gcLock); |
| 2156 |
} |
| 2157 |
|
| 2158 |
FreeChunkPool(emptyChunksToFree); |
| 2159 |
|
| 2160 |
{ |
| 2161 |
AutoLockGC gcLock(gc); |
| 2162 |
|
| 2163 |
// To help minimize the total number of chunks needed over time, sort the |
| 2164 |
// available chunks list so that we allocate into more-used chunks first. |
| 2165 |
gc->availableChunks(gcLock).sort(); |
| 2166 |
|
| 2167 |
if (DecommitEnabled()) { |
| 2168 |
gc->decommitEmptyChunks(cancel_, gcLock); |
| 2169 |
gc->decommitFreeArenas(cancel_, gcLock); |
| 2170 |
} |
| 2171 |
} |
| 2172 |
} |
| 2173 |
|
| 2174 |
gc->maybeRequestGCAfterBackgroundTask(lock); |
| 2175 |
} |
| 2176 |
|
| 2177 |
static inline bool CanDecommitWholeChunk(ArenaChunk* chunk) { |
| 2178 |
return chunk->isEmpty() && chunk->info.numArenasFreeCommitted != 0; |
| 2179 |
} |
| 2180 |
|
| 2181 |
// Called from a background thread to decommit free arenas. Releases the GC |
| 2182 |
// lock. |
| 2183 |
void GCRuntime::decommitEmptyChunks(const bool& cancel, AutoLockGC& lock) { |
| 2184 |
Vector<ArenaChunk*, 0, SystemAllocPolicy> chunksToDecommit; |
| 2185 |
for (ChunkPool::Iter chunk(emptyChunks(lock)); !chunk.done(); chunk.next()) { |
| 2186 |
if (CanDecommitWholeChunk(chunk) && !chunksToDecommit.append(chunk)) { |
| 2187 |
onOutOfMallocMemory(lock); |
| 2188 |
return; |
| 2189 |
} |
| 2190 |
} |
| 2191 |
|
| 2192 |
for (ArenaChunk* chunk : chunksToDecommit) { |
| 2193 |
if (cancel) { |
| 2194 |
break; |
| 2195 |
} |
| 2196 |
|
| 2197 |
// Check whether something used the chunk while the lock was released. The |
| 2198 |
// chunk may have been taken from the empty chunks pool (e.g. adopted as |
| 2199 |
// the current chunk, or repurposed as a nursery/buffer chunk), so we must |
| 2200 |
// verify it is still a member of the pool before removing it. |
| 2201 |
if (!emptyChunks(lock).contains(chunk) || !CanDecommitWholeChunk(chunk)) { |
| 2202 |
continue; |
| 2203 |
} |
| 2204 |
|
| 2205 |
// Temporarily remove the chunk while decommitting its memory so that the |
| 2206 |
// mutator doesn't start allocating from it when we drop the lock. |
| 2207 |
emptyChunks(lock).remove(chunk); |
| 2208 |
|
| 2209 |
{ |
| 2210 |
AutoUnlockGC unlock(lock); |
| 2211 |
chunk->decommitAllArenas(); |
| 2212 |
MOZ_ASSERT(chunk->info.numArenasFreeCommitted == 0); |
| 2213 |
} |
| 2214 |
|
| 2215 |
emptyChunks(lock).push(chunk); |
| 2216 |
} |
| 2217 |
} |
| 2218 |
|
| 2219 |
// Called from a background thread to decommit free arenas. Releases the GC |
| 2220 |
// lock. |
| 2221 |
void GCRuntime::decommitFreeArenas(const bool& cancel, AutoLockGC& lock) { |
| 2222 |
MOZ_ASSERT(DecommitEnabled()); |
| 2223 |
|
| 2224 |
// Since we release the GC lock while doing the decommit syscall below, |
| 2225 |
// it is dangerous to iterate the available list directly, as the active |
| 2226 |
// thread could modify it concurrently. Instead, we build and pass an |
| 2227 |
// explicit Vector containing the Chunks we want to visit. |
| 2228 |
Vector<ArenaChunk*, 0, SystemAllocPolicy> chunksToDecommit; |
| 2229 |
for (ChunkPool::Iter chunk(availableChunks(lock)); !chunk.done(); |
| 2230 |
chunk.next()) { |
| 2231 |
if (chunk->info.numArenasFreeCommitted != 0 && |
| 2232 |
!chunksToDecommit.append(chunk)) { |
| 2233 |
onOutOfMallocMemory(lock); |
| 2234 |
return; |
| 2235 |
} |
| 2236 |
} |
| 2237 |
|
| 2238 |
for (ArenaChunk* chunk : chunksToDecommit) { |
| 2239 |
MOZ_ASSERT(chunk->getKind() == ChunkKind::TenuredArenas); |
| 2240 |
MOZ_ASSERT(!chunk->isEmpty()); |
| 2241 |
|
| 2242 |
if (chunk->info.isCurrentChunk) { |
| 2243 |
// Chunk has become current chunk while lock was released. |
| 2244 |
continue; |
| 2245 |
} |
| 2246 |
|
| 2247 |
if (!chunk->hasAvailableArenas()) { |
| 2248 |
// Chunk has become full while lock was released. |
| 2249 |
continue; |
| 2250 |
} |
| 2251 |
|
| 2252 |
MOZ_ASSERT(availableChunks(lock).contains(chunk)); |
| 2253 |
chunk->decommitFreeArenas(this, cancel, lock); |
| 2254 |
} |
| 2255 |
} |
| 2256 |
|
| 2257 |
// Do all possible decommit immediately from the current thread without |
| 2258 |
// releasing the GC lock or allocating any memory. |
| 2259 |
void GCRuntime::decommitFreeArenasWithoutUnlocking(const AutoLockGC& lock) { |
| 2260 |
MOZ_ASSERT(DecommitEnabled()); |
| 2261 |
for (ChunkPool::Iter chunk(availableChunks(lock)); !chunk.done(); |
| 2262 |
chunk.next()) { |
| 2263 |
chunk->decommitFreeArenasWithoutUnlocking(lock); |
| 2264 |
} |
| 2265 |
MOZ_ASSERT(availableChunks(lock).verify()); |
| 2266 |
} |
| 2267 |
|
| 2268 |
void GCRuntime::maybeRequestGCAfterBackgroundTask( |
| 2269 |
const AutoLockHelperThreadState& lock) { |
| 2270 |
if (requestSliceAfterBackgroundTask) { |
| 2271 |
// Request a slice. The main thread may continue the collection immediately |
| 2272 |
// or it may yield to let the embedding schedule a slice. |
| 2273 |
requestSliceAfterBackgroundTask = false; |
| 2274 |
requestMajorGC(JS::GCReason::BG_TASK_FINISHED); |
| 2275 |
} |
| 2276 |
} |
| 2277 |
|
| 2278 |
void GCRuntime::cancelRequestedGCAfterBackgroundTask() { |
| 2279 |
MOZ_ASSERT(CurrentThreadCanAccessRuntime(rt)); |
| 2280 |
|
| 2281 |
#ifdef DEBUG |
| 2282 |
{ |
| 2283 |
AutoLockHelperThreadState lock; |
| 2284 |
MOZ_ASSERT(!requestSliceAfterBackgroundTask); |
| 2285 |
} |
| 2286 |
#endif |
| 2287 |
|
| 2288 |
majorGCTriggerReason.compareExchange(JS::GCReason::BG_TASK_FINISHED, |
| 2289 |
JS::GCReason::NO_REASON); |
| 2290 |
} |
| 2291 |
|
| 2292 |
bool GCRuntime::isWaitingOnBackgroundTask() const { |
| 2293 |
AutoLockHelperThreadState lock; |
| 2294 |
return requestSliceAfterBackgroundTask; |
| 2295 |
} |
| 2296 |
|
| 2297 |
void GCRuntime::queueUnusedLifoBlocksForFree(LifoAlloc* lifo) { |
| 2298 |
MOZ_ASSERT(JS::RuntimeHeapIsBusy()); |
| 2299 |
AutoLockHelperThreadState lock; |
| 2300 |
lifoBlocksToFree.ref().transferUnusedFrom(lifo); |
| 2301 |
} |
| 2302 |
|
| 2303 |
void GCRuntime::queueAllLifoBlocksForFreeAfterMinorGC(LifoAlloc* lifo) { |
| 2304 |
lifoBlocksToFreeAfterFullMinorGC.ref().transferFrom(lifo); |
| 2305 |
} |
| 2306 |
|
| 2307 |
void GCRuntime::queueBuffersForFreeAfterMinorGC( |
| 2308 |
Nursery::BufferSet& buffers, Nursery::StringBufferVector& stringBuffers) { |
| 2309 |
AutoLockHelperThreadState lock; |
| 2310 |
|
| 2311 |
if (!buffersToFreeAfterMinorGC.ref().empty() || |
| 2312 |
!stringBuffersToReleaseAfterMinorGC.ref().empty()) { |
| 2313 |
// In the rare case that this hasn't processed the buffers from a previous |
| 2314 |
// minor GC we have to wait here. |
| 2315 |
MOZ_ASSERT(!freeTask.isIdle(lock)); |
| 2316 |
freeTask.joinWithLockHeld(lock); |
| 2317 |
} |
| 2318 |
|
| 2319 |
MOZ_ASSERT(buffersToFreeAfterMinorGC.ref().empty()); |
| 2320 |
std::swap(buffersToFreeAfterMinorGC.ref(), buffers); |
| 2321 |
|
| 2322 |
MOZ_ASSERT(stringBuffersToReleaseAfterMinorGC.ref().empty()); |
| 2323 |
std::swap(stringBuffersToReleaseAfterMinorGC.ref(), stringBuffers); |
| 2324 |
} |
| 2325 |
|
| 2326 |
void Realm::destroy(JS::GCContext* gcx) { |
| 2327 |
JSRuntime* rt = gcx->runtime(); |
| 2328 |
if (auto callback = rt->destroyRealmCallback) { |
| 2329 |
callback(gcx, this); |
| 2330 |
} |
| 2331 |
if (principals()) { |
| 2332 |
JS_DropPrincipals(rt->mainContextFromOwnThread(), principals()); |
| 2333 |
} |
| 2334 |
// Bug 1560019: Malloc memory associated with a zone but not with a specific |
| 2335 |
// GC thing is not currently tracked. |
| 2336 |
gcx->deleteUntracked(this); |
| 2337 |
} |
| 2338 |
|
| 2339 |
void Compartment::destroy(JS::GCContext* gcx) { |
| 2340 |
JSRuntime* rt = gcx->runtime(); |
| 2341 |
if (auto callback = rt->destroyCompartmentCallback) { |
| 2342 |
callback(gcx, this); |
| 2343 |
} |
| 2344 |
// Bug 1560019: Malloc memory associated with a zone but not with a specific |
| 2345 |
// GC thing is not currently tracked. |
| 2346 |
gcx->deleteUntracked(this); |
| 2347 |
rt->gc.stats().sweptCompartment(); |
| 2348 |
} |
| 2349 |
|
| 2350 |
void Zone::destroy(JS::GCContext* gcx) { |
| 2351 |
MOZ_ASSERT(compartments().empty()); |
| 2352 |
JSRuntime* rt = gcx->runtime(); |
| 2353 |
if (auto callback = rt->destroyZoneCallback) { |
| 2354 |
callback(gcx, this); |
| 2355 |
} |
| 2356 |
// Bug 1560019: Malloc memory associated with a zone but not with a specific |
| 2357 |
// GC thing is not currently tracked. |
| 2358 |
gcx->deleteUntracked(this); |
| 2359 |
gcx->runtime()->gc.stats().sweptZone(); |
| 2360 |
} |
| 2361 |
|
| 2362 |
/* |
| 2363 |
* It's simpler if we preserve the invariant that every zone (except atoms |
| 2364 |
* zones) has at least one compartment, and every compartment has at least one |
| 2365 |
* realm. If we know we're deleting the entire zone, then sweepCompartments is |
| 2366 |
* allowed to delete all compartments. In this case, |keepAtleastOne| is false. |
| 2367 |
* If any cells remain alive in the zone, set |keepAtleastOne| true to prohibit |
| 2368 |
* sweepCompartments from deleting every compartment. Instead, it preserves an |
| 2369 |
* arbitrary compartment in the zone. |
| 2370 |
*/ |
| 2371 |
void Zone::sweepCompartments(JS::GCContext* gcx, bool keepAtleastOne, |
| 2372 |
bool destroyingRuntime) { |
| 2373 |
MOZ_ASSERT_IF(!isAtomsZone(), !compartments().empty()); |
| 2374 |
MOZ_ASSERT_IF(destroyingRuntime, !keepAtleastOne); |
| 2375 |
|
| 2376 |
Compartment** read = compartments().begin(); |
| 2377 |
Compartment** end = compartments().end(); |
| 2378 |
Compartment** write = read; |
| 2379 |
while (read < end) { |
| 2380 |
Compartment* comp = *read++; |
| 2381 |
|
| 2382 |
/* |
| 2383 |
* Don't delete the last compartment and realm if keepAtleastOne is |
| 2384 |
* still true, meaning all the other compartments were deleted. |
| 2385 |
*/ |
| 2386 |
bool keepAtleastOneRealm = read == end && keepAtleastOne; |
| 2387 |
comp->sweepRealms(gcx, keepAtleastOneRealm, destroyingRuntime); |
| 2388 |
|
| 2389 |
if (!comp->realms().empty()) { |
| 2390 |
*write++ = comp; |
| 2391 |
keepAtleastOne = false; |
| 2392 |
} else { |
| 2393 |
comp->destroy(gcx); |
| 2394 |
} |
| 2395 |
} |
| 2396 |
compartments().shrinkTo(write - compartments().begin()); |
| 2397 |
MOZ_ASSERT_IF(keepAtleastOne, !compartments().empty()); |
| 2398 |
MOZ_ASSERT_IF(destroyingRuntime, compartments().empty()); |
| 2399 |
} |
| 2400 |
|
| 2401 |
void Compartment::sweepRealms(JS::GCContext* gcx, bool keepAtleastOne, |
| 2402 |
bool destroyingRuntime) { |
| 2403 |
MOZ_ASSERT(!realms().empty()); |
| 2404 |
MOZ_ASSERT_IF(destroyingRuntime, !keepAtleastOne); |
| 2405 |
|
| 2406 |
Realm** read = realms().begin(); |
| 2407 |
Realm** end = realms().end(); |
| 2408 |
Realm** write = read; |
| 2409 |
while (read < end) { |
| 2410 |
Realm* realm = *read++; |
| 2411 |
|
| 2412 |
/* |
| 2413 |
* Don't delete the last realm if keepAtleastOne is still true, meaning |
| 2414 |
* all the other realms were deleted. |
| 2415 |
*/ |
| 2416 |
bool dontDelete = read == end && keepAtleastOne; |
| 2417 |
if ((realm->marked() || dontDelete) && !destroyingRuntime) { |
| 2418 |
*write++ = realm; |
| 2419 |
keepAtleastOne = false; |
| 2420 |
} else { |
| 2421 |
realm->destroy(gcx); |
| 2422 |
} |
| 2423 |
} |
| 2424 |
realms().shrinkTo(write - realms().begin()); |
| 2425 |
MOZ_ASSERT_IF(keepAtleastOne, !realms().empty()); |
| 2426 |
MOZ_ASSERT_IF(destroyingRuntime, realms().empty()); |
| 2427 |
} |
| 2428 |
|
| 2429 |
void GCRuntime::sweepZones(JS::GCContext* gcx, bool destroyingRuntime) { |
| 2430 |
MOZ_ASSERT_IF(destroyingRuntime, numActiveZoneIters == 0); |
| 2431 |
MOZ_ASSERT(foregroundFinalizedArenas.ref().isNothing()); |
| 2432 |
|
| 2433 |
if (numActiveZoneIters) { |
| 2434 |
return; |
| 2435 |
} |
| 2436 |
|
| 2437 |
assertBackgroundSweepingFinished(); |
| 2438 |
|
| 2439 |
// Host destroy callbacks can access the store buffer, e.g. when resizing hash |
| 2440 |
// tables containing nursery pointers. |
| 2441 |
AutoLockStoreBuffer lock(rt); |
| 2442 |
|
| 2443 |
// Sweep zones following the atoms zone. |
| 2444 |
MOZ_ASSERT(zones()[0]->isAtomsZone()); |
| 2445 |
Zone** read = zones().begin() + 1; |
| 2446 |
Zone** end = zones().end(); |
| 2447 |
Zone** write = read; |
| 2448 |
|
| 2449 |
while (read < end) { |
| 2450 |
Zone* zone = *read++; |
| 2451 |
|
| 2452 |
if (zone->wasGCStarted()) { |
| 2453 |
MOZ_ASSERT(!zone->isQueuedForBackgroundSweep()); |
| 2454 |
AutoSetThreadIsSweeping threadIsSweeping(zone); |
| 2455 |
const bool zoneIsDead = zone->arenas.arenaListsAreEmpty() && |
| 2456 |
zone->bufferAllocator.isEmpty() && |
| 2457 |
!zone->hasMarkedRealms(); |
| 2458 |
MOZ_ASSERT_IF(destroyingRuntime, zoneIsDead); |
| 2459 |
if (zoneIsDead) { |
| 2460 |
zone->arenas.checkEmptyFreeLists(); |
| 2461 |
zone->sweepCompartments(gcx, false, destroyingRuntime); |
| 2462 |
MOZ_ASSERT(zone->compartments().empty()); |
| 2463 |
zone->destroy(gcx); |
| 2464 |
continue; |
| 2465 |
} |
| 2466 |
zone->sweepCompartments(gcx, true, destroyingRuntime); |
| 2467 |
} |
| 2468 |
*write++ = zone; |
| 2469 |
} |
| 2470 |
zones().shrinkTo(write - zones().begin()); |
| 2471 |
} |
| 2472 |
|
| 2473 |
void ArenaLists::checkEmptyArenaList(AllocKind kind) { |
| 2474 |
MOZ_ASSERT(arenaList(kind).isEmpty()); |
| 2475 |
} |
| 2476 |
|
| 2477 |
void GCRuntime::purgeRuntimeForMinorGC() { |
| 2478 |
for (ZonesIter zone(this, SkipAtoms); !zone.done(); zone.next()) { |
| 2479 |
zone->externalStringCache().purge(); |
| 2480 |
zone->functionToStringCache().purge(); |
| 2481 |
} |
| 2482 |
} |
| 2483 |
|
| 2484 |
void GCRuntime::purgeRuntime() { |
| 2485 |
gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::PURGE); |
| 2486 |
|
| 2487 |
for (GCRealmsIter realm(rt); !realm.done(); realm.next()) { |
| 2488 |
realm->purge(); |
| 2489 |
} |
| 2490 |
|
| 2491 |
for (GCZonesIter zone(this); !zone.done(); zone.next()) { |
| 2492 |
zone->purgeAtomCache(); |
| 2493 |
zone->externalStringCache().purge(); |
| 2494 |
zone->functionToStringCache().purge(); |
| 2495 |
zone->boundPrefixCache().clearAndCompact(); |
| 2496 |
zone->shapeZone().purgeShapeCaches(rt->gcContext()); |
| 2497 |
} |
| 2498 |
|
| 2499 |
JSContext* cx = rt->mainContextFromOwnThread(); |
| 2500 |
queueUnusedLifoBlocksForFree(&cx->tempLifoAlloc()); |
| 2501 |
cx->interpreterStack().purge(rt); |
| 2502 |
cx->frontendCollectionPool().purge(); |
| 2503 |
|
| 2504 |
rt->caches().purge(); |
| 2505 |
|
| 2506 |
if (rt->isMainRuntime()) { |
| 2507 |
SharedImmutableStringsCache::getSingleton().purge(); |
| 2508 |
} |
| 2509 |
|
| 2510 |
MOZ_ASSERT(marker().unmarkGrayStack.empty()); |
| 2511 |
marker().unmarkGrayStack.clearAndFree(); |
| 2512 |
} |
| 2513 |
|
| 2514 |
bool GCRuntime::shouldPreserveJITCode(Realm* realm, |
| 2515 |
const TimeStamp& currentTime, |
| 2516 |
JS::GCReason reason, |
| 2517 |
bool canAllocateMoreCode, |
| 2518 |
bool isActiveCompartment) { |
| 2519 |
// During shutdown, we must clean everything up, for the sake of leak |
| 2520 |
// detection. |
| 2521 |
if (isShutdownGC()) { |
| 2522 |
return false; |
| 2523 |
} |
| 2524 |
|
| 2525 |
// A shrinking GC is trying to clear out as much as it can, and so we should |
| 2526 |
// not preserve JIT code here! |
| 2527 |
if (isShrinkingGC()) { |
| 2528 |
return false; |
| 2529 |
} |
| 2530 |
|
| 2531 |
// We are close to our allocatable code limit, so let's try to clean it out. |
| 2532 |
if (!canAllocateMoreCode) { |
| 2533 |
return false; |
| 2534 |
} |
| 2535 |
|
| 2536 |
// The topmost frame of JIT code is in this compartment, and so we should |
| 2537 |
// try to preserve this zone's code. |
| 2538 |
if (isActiveCompartment) { |
| 2539 |
return true; |
| 2540 |
} |
| 2541 |
|
| 2542 |
// The gcPreserveJitCode testing function was used. |
| 2543 |
if (alwaysPreserveCode) { |
| 2544 |
return true; |
| 2545 |
} |
| 2546 |
|
| 2547 |
// This realm explicitly requested we try to preserve its JIT code. |
| 2548 |
if (realm->preserveJitCode()) { |
| 2549 |
return true; |
| 2550 |
} |
| 2551 |
|
| 2552 |
// If we're currently animating, and we've already discarded code recently |
| 2553 |
// we can preserve jit code; however we shouldn't hold onto JIT code forever |
| 2554 |
// during animation. |
| 2555 |
if (IsCurrentlyAnimating(realm->lastAnimationTime, currentTime) && |
| 2556 |
DiscardedCodeRecently(realm->zone(), currentTime)) { |
| 2557 |
return true; |
| 2558 |
} |
| 2559 |
|
| 2560 |
// GC Invoked via a testing function. |
| 2561 |
if (reason == JS::GCReason::DEBUG_GC) { |
| 2562 |
return true; |
| 2563 |
} |
| 2564 |
|
| 2565 |
return false; |
| 2566 |
} |
| 2567 |
|
| 2568 |
#ifdef DEBUG |
| 2569 |
class CompartmentCheckTracer final : public JS::CallbackTracer { |
| 2570 |
void onChild(JS::GCCellPtr thing, const char* name) override; |
| 2571 |
bool edgeIsInCrossCompartmentMap(JS::GCCellPtr dst); |
| 2572 |
|
| 2573 |
public: |
| 2574 |
explicit CompartmentCheckTracer(JSRuntime* rt) |
| 2575 |
: JS::CallbackTracer(rt, JS::TracerKind::CompartmentCheck, |
| 2576 |
JS::WeakEdgeTraceAction::Skip) {} |
| 2577 |
|
| 2578 |
Cell* src = nullptr; |
| 2579 |
JS::TraceKind srcKind = JS::TraceKind::Null; |
| 2580 |
Zone* zone = nullptr; |
| 2581 |
Compartment* compartment = nullptr; |
| 2582 |
}; |
| 2583 |
|
| 2584 |
static bool InCrossCompartmentMap(JSRuntime* rt, JSObject* src, |
| 2585 |
JS::GCCellPtr dst) { |
| 2586 |
// Cross compartment edges are either in the cross compartment map or in a |
| 2587 |
// debugger weakmap. |
| 2588 |
|
| 2589 |
Compartment* srccomp = src->compartment(); |
| 2590 |
|
| 2591 |
if (dst.is<JSObject>()) { |
| 2592 |
if (ObjectWrapperMap::Ptr p = srccomp->lookupWrapper(&dst.as<JSObject>())) { |
| 2593 |
if (*p->value().unsafeGet() == src) { |
| 2594 |
return true; |
| 2595 |
} |
| 2596 |
} |
| 2597 |
} |
| 2598 |
|
| 2599 |
if (DebugAPI::edgeIsInDebuggerWeakmap(rt, src, dst)) { |
| 2600 |
return true; |
| 2601 |
} |
| 2602 |
|
| 2603 |
return false; |
| 2604 |
} |
| 2605 |
|
| 2606 |
void CompartmentCheckTracer::onChild(JS::GCCellPtr thing, const char* name) { |
| 2607 |
Compartment* comp = |
| 2608 |
MapGCThingTyped(thing, [](auto t) { return t->maybeCompartment(); }); |
| 2609 |
if (comp && compartment) { |
| 2610 |
MOZ_ASSERT(comp == compartment || edgeIsInCrossCompartmentMap(thing)); |
| 2611 |
} else { |
| 2612 |
TenuredCell* tenured = &thing.asCell()->asTenured(); |
| 2613 |
Zone* thingZone = tenured->zoneFromAnyThread(); |
| 2614 |
MOZ_ASSERT(thingZone == zone || thingZone->isAtomsZone()); |
| 2615 |
} |
| 2616 |
} |
| 2617 |
|
| 2618 |
bool CompartmentCheckTracer::edgeIsInCrossCompartmentMap(JS::GCCellPtr dst) { |
| 2619 |
return srcKind == JS::TraceKind::Object && |
| 2620 |
InCrossCompartmentMap(runtime(), static_cast<JSObject*>(src), dst); |
| 2621 |
} |
| 2622 |
|
| 2623 |
void GCRuntime::checkForCompartmentMismatches() { |
| 2624 |
JSContext* cx = rt->mainContextFromOwnThread(); |
| 2625 |
if (cx->disableStrictProxyCheckingCount) { |
| 2626 |
return; |
| 2627 |
} |
| 2628 |
|
| 2629 |
CompartmentCheckTracer trc(rt); |
| 2630 |
AutoAssertEmptyNursery empty(cx); |
| 2631 |
for (ZonesIter zone(this, SkipAtoms); !zone.done(); zone.next()) { |
| 2632 |
trc.zone = zone; |
| 2633 |
for (auto thingKind : AllAllocKinds()) { |
| 2634 |
for (auto i = zone->cellIterUnsafe<TenuredCell>(thingKind, empty); |
| 2635 |
!i.done(); i.next()) { |
| 2636 |
trc.src = i.getCell(); |
| 2637 |
trc.srcKind = MapAllocToTraceKind(thingKind); |
| 2638 |
trc.compartment = MapGCThingTyped( |
| 2639 |
trc.src, trc.srcKind, [](auto t) { return t->maybeCompartment(); }); |
| 2640 |
JS::TraceChildren(&trc, JS::GCCellPtr(trc.src, trc.srcKind)); |
| 2641 |
} |
| 2642 |
} |
| 2643 |
} |
| 2644 |
} |
| 2645 |
#endif |
| 2646 |
|
| 2647 |
static bool ShouldUseBackgroundThreads(bool isIncremental, |
| 2648 |
JS::GCReason reason) { |
| 2649 |
bool shouldUse = isIncremental && CanUseExtraThreads(); |
| 2650 |
MOZ_ASSERT_IF(reason == JS::GCReason::DESTROY_RUNTIME, !shouldUse); |
| 2651 |
return shouldUse; |
| 2652 |
} |
| 2653 |
|
| 2654 |
void GCRuntime::startCollection(JS::GCReason reason) { |
| 2655 |
checkGCStateNotInUse(); |
| 2656 |
MOZ_ASSERT_IF( |
| 2657 |
isShuttingDown(), |
| 2658 |
isShutdownGC() || |
| 2659 |
reason == JS::GCReason::XPCONNECT_SHUTDOWN /* Bug 1650075 */); |
| 2660 |
|
| 2661 |
initialReason = reason; |
| 2662 |
isCompacting = shouldCompact(); |
| 2663 |
rootsRemoved = false; |
| 2664 |
sweepGroupIndex = 0; |
| 2665 |
|
| 2666 |
#ifdef DEBUG |
| 2667 |
if (isShutdownGC()) { |
| 2668 |
hadShutdownGC = true; |
| 2669 |
} |
| 2670 |
|
| 2671 |
for (ZonesIter zone(this, WithAtoms); !zone.done(); zone.next()) { |
| 2672 |
zone->gcSweepGroupIndex = 0; |
| 2673 |
} |
| 2674 |
#endif |
| 2675 |
} |
| 2676 |
|
| 2677 |
static void RelazifyFunctions(Zone* zone, AllocKind kind) { |
| 2678 |
MOZ_ASSERT(kind == AllocKind::FUNCTION || |
| 2679 |
kind == AllocKind::FUNCTION_EXTENDED); |
| 2680 |
|
| 2681 |
JSRuntime* rt = zone->runtimeFromMainThread(); |
| 2682 |
AutoAssertEmptyNursery empty(rt->mainContextFromOwnThread()); |
| 2683 |
|
| 2684 |
for (auto i = zone->cellIterUnsafe<JSObject>(kind, empty); !i.done(); |
| 2685 |
i.next()) { |
| 2686 |
JSFunction* fun = &i->as<JSFunction>(); |
| 2687 |
// When iterating over the GC-heap, we may encounter function objects that |
| 2688 |
// are incomplete (missing a BaseScript when we expect one). We must check |
| 2689 |
// for this case before we can call JSFunction::hasBytecode(). |
| 2690 |
if (fun->isIncomplete()) { |
| 2691 |
continue; |
| 2692 |
} |
| 2693 |
if (fun->hasBytecode()) { |
| 2694 |
fun->maybeRelazify(rt); |
| 2695 |
} |
| 2696 |
} |
| 2697 |
} |
| 2698 |
|
| 2699 |
static bool ShouldCollectZone(Zone* zone, JS::GCReason reason) { |
| 2700 |
// If we are repeating a GC because we noticed dead compartments haven't |
| 2701 |
// been collected, then only collect zones containing those compartments. |
| 2702 |
if (reason == JS::GCReason::COMPARTMENT_REVIVED) { |
| 2703 |
for (CompartmentsInZoneIter comp(zone); !comp.done(); comp.next()) { |
| 2704 |
if (comp->gcState.scheduledForDestruction) { |
| 2705 |
return true; |
| 2706 |
} |
| 2707 |
} |
| 2708 |
|
| 2709 |
return false; |
| 2710 |
} |
| 2711 |
|
| 2712 |
// Otherwise we only collect scheduled zones. |
| 2713 |
return zone->isGCScheduled(); |
| 2714 |
} |
| 2715 |
|
| 2716 |
bool GCRuntime::prepareZonesForCollection(JS::GCReason reason, |
| 2717 |
bool* isFullOut) { |
| 2718 |
#ifdef DEBUG |
| 2719 |
/* Assert that zone state is as we expect */ |
| 2720 |
for (ZonesIter zone(this, WithAtoms); !zone.done(); zone.next()) { |
| 2721 |
MOZ_ASSERT(!zone->isCollecting()); |
| 2722 |
MOZ_ASSERT_IF(!zone->isAtomsZone(), !zone->compartments().empty()); |
| 2723 |
for (auto i : AllAllocKinds()) { |
| 2724 |
MOZ_ASSERT(zone->arenas.collectingArenaList(i).isEmpty()); |
| 2725 |
} |
| 2726 |
} |
| 2727 |
#endif |
| 2728 |
|
| 2729 |
*isFullOut = true; |
| 2730 |
bool any = false; |
| 2731 |
|
| 2732 |
for (ZonesIter zone(this, WithAtoms); !zone.done(); zone.next()) { |
| 2733 |
/* Set up which zones will be collected. */ |
| 2734 |
bool shouldCollect = ShouldCollectZone(zone, reason); |
| 2735 |
if (shouldCollect) { |
| 2736 |
any = true; |
| 2737 |
zone->changeGCState(Zone::NoGC, Zone::Prepare); |
| 2738 |
} else { |
| 2739 |
*isFullOut = false; |
| 2740 |
} |
| 2741 |
|
| 2742 |
zone->setWasCollected(shouldCollect); |
| 2743 |
} |
| 2744 |
|
| 2745 |
/* Check that at least one zone is scheduled for collection. */ |
| 2746 |
return any; |
| 2747 |
} |
| 2748 |
|
| 2749 |
// Update JIT Code state for GC: A few different actions are combined here to |
| 2750 |
// minimize the number of iterations over zones & scripts that required. |
| 2751 |
void GCRuntime::maybeDiscardJitCodeForGC() { |
| 2752 |
size_t nurserySiteResetCount = 0; |
| 2753 |
size_t pretenuredSiteResetCount = 0; |
| 2754 |
|
| 2755 |
js::CancelOffThreadCompile(rt, JS::Zone::Prepare); |
| 2756 |
for (GCZonesIter zone(this); !zone.done(); zone.next()) { |
| 2757 |
gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::MARK_DISCARD_CODE); |
| 2758 |
|
| 2759 |
// We may need to reset allocation sites and discard JIT code to recover if |
| 2760 |
// we find object lifetimes have changed. |
| 2761 |
PretenuringZone& pz = zone->pretenuring; |
| 2762 |
bool resetNurserySites = pz.shouldResetNurseryAllocSites(); |
| 2763 |
bool resetPretenuredSites = pz.shouldResetPretenuredAllocSites(); |
| 2764 |
|
| 2765 |
if (!zone->isPreservingCode()) { |
| 2766 |
Zone::JitDiscardOptions options; |
| 2767 |
options.discardJitScripts = true; |
| 2768 |
options.resetNurseryAllocSites = resetNurserySites; |
| 2769 |
options.resetPretenuredAllocSites = resetPretenuredSites; |
| 2770 |
zone->forceDiscardJitCode(rt->gcContext(), options); |
| 2771 |
} else if (resetNurserySites || resetPretenuredSites) { |
| 2772 |
zone->resetAllocSitesAndInvalidate(resetNurserySites, |
| 2773 |
resetPretenuredSites); |
| 2774 |
} |
| 2775 |
|
| 2776 |
if (resetNurserySites) { |
| 2777 |
nurserySiteResetCount++; |
| 2778 |
} |
| 2779 |
if (resetPretenuredSites) { |
| 2780 |
pretenuredSiteResetCount++; |
| 2781 |
} |
| 2782 |
} |
| 2783 |
|
| 2784 |
if (nursery().reportPretenuring()) { |
| 2785 |
if (nurserySiteResetCount) { |
| 2786 |
fprintf( |
| 2787 |
stderr, |
| 2788 |
"GC reset nursery alloc sites and invalidated code in %zu zones\n", |
| 2789 |
nurserySiteResetCount); |
| 2790 |
} |
| 2791 |
if (pretenuredSiteResetCount) { |
| 2792 |
fprintf( |
| 2793 |
stderr, |
| 2794 |
"GC reset pretenured alloc sites and invalidated code in %zu zones\n", |
| 2795 |
pretenuredSiteResetCount); |
| 2796 |
} |
| 2797 |
} |
| 2798 |
} |
| 2799 |
|
| 2800 |
void GCRuntime::relazifyFunctionsForShrinkingGC() { |
| 2801 |
gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::RELAZIFY_FUNCTIONS); |
| 2802 |
for (GCZonesIter zone(this); !zone.done(); zone.next()) { |
| 2803 |
RelazifyFunctions(zone, AllocKind::FUNCTION); |
| 2804 |
RelazifyFunctions(zone, AllocKind::FUNCTION_EXTENDED); |
| 2805 |
} |
| 2806 |
} |
| 2807 |
|
| 2808 |
void GCRuntime::purgePropMapTablesForShrinkingGC() { |
| 2809 |
gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::PURGE_PROP_MAP_TABLES); |
| 2810 |
for (GCZonesIter zone(this); !zone.done(); zone.next()) { |
| 2811 |
if (!canRelocateZone(zone) || zone->keepPropMapTables()) { |
| 2812 |
continue; |
| 2813 |
} |
| 2814 |
|
| 2815 |
// Note: CompactPropMaps never have a table. |
| 2816 |
for (auto map = zone->cellIterUnsafe<NormalPropMap>(); !map.done(); |
| 2817 |
map.next()) { |
| 2818 |
if (map->asLinked()->hasTable()) { |
| 2819 |
map->asLinked()->purgeTable(rt->gcContext()); |
| 2820 |
} |
| 2821 |
} |
| 2822 |
for (auto map = zone->cellIterUnsafe<DictionaryPropMap>(); !map.done(); |
| 2823 |
map.next()) { |
| 2824 |
if (map->asLinked()->hasTable()) { |
| 2825 |
map->asLinked()->purgeTable(rt->gcContext()); |
| 2826 |
} |
| 2827 |
} |
| 2828 |
} |
| 2829 |
} |
| 2830 |
|
| 2831 |
// The debugger keeps track of the URLs for the sources of each realm's scripts. |
| 2832 |
// These URLs are purged on shrinking GCs. |
| 2833 |
void GCRuntime::purgeSourceURLsForShrinkingGC() { |
| 2834 |
gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::PURGE_SOURCE_URLS); |
| 2835 |
for (GCZonesIter zone(this); !zone.done(); zone.next()) { |
| 2836 |
// URLs are not tracked for realms in the system zone. |
| 2837 |
if (!canRelocateZone(zone) || zone->isSystemZone()) { |
| 2838 |
continue; |
| 2839 |
} |
| 2840 |
for (CompartmentsInZoneIter comp(zone); !comp.done(); comp.next()) { |
| 2841 |
for (RealmsInCompartmentIter realm(comp); !realm.done(); realm.next()) { |
| 2842 |
GlobalObject* global = realm.get()->unsafeUnbarrieredMaybeGlobal(); |
| 2843 |
if (global) { |
| 2844 |
global->clearSourceURLSHolder(); |
| 2845 |
} |
| 2846 |
} |
| 2847 |
} |
| 2848 |
} |
| 2849 |
} |
| 2850 |
|
| 2851 |
void GCRuntime::unmarkWeakMaps() { |
| 2852 |
for (GCZonesIter zone(this); !zone.done(); zone.next()) { |
| 2853 |
/* Unmark all weak maps in the zones being collected. */ |
| 2854 |
WeakMapBase::unmarkZone(zone); |
| 2855 |
} |
| 2856 |
} |
| 2857 |
|
| 2858 |
bool GCRuntime::beginPreparePhase(JS::GCReason reason, AutoGCSession& session) { |
| 2859 |
gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::PREPARE); |
| 2860 |
|
| 2861 |
if (!prepareZonesForCollection(reason, &isFull.ref())) { |
| 2862 |
return false; |
| 2863 |
} |
| 2864 |
|
| 2865 |
/* |
| 2866 |
* Start a parallel task to clear all mark state for the zones we are |
| 2867 |
* collecting. This is linear in the size of the heap we are collecting and so |
| 2868 |
* can be slow. This usually happens concurrently with the mutator and GC |
| 2869 |
* proper does not start until this is complete. |
| 2870 |
*/ |
| 2871 |
unmarkTask.initZones(); |
| 2872 |
if (useBackgroundThreads) { |
| 2873 |
unmarkTask.start(); |
| 2874 |
} else { |
| 2875 |
unmarkTask.runFromMainThread(); |
| 2876 |
} |
| 2877 |
|
| 2878 |
/* |
| 2879 |
* Process any queued source compressions during the start of a major |
| 2880 |
* GC. |
| 2881 |
* |
| 2882 |
* Bug 1650075: When we start passing GCOptions::Shutdown for |
| 2883 |
* GCReason::XPCONNECT_SHUTDOWN GCs we can remove the extra check. |
| 2884 |
*/ |
| 2885 |
if (!isShutdownGC() && reason != JS::GCReason::XPCONNECT_SHUTDOWN) { |
| 2886 |
StartHandlingCompressionsOnGC(rt); |
| 2887 |
} |
| 2888 |
|
| 2889 |
return true; |
| 2890 |
} |
| 2891 |
|
| 2892 |
BackgroundUnmarkTask::BackgroundUnmarkTask(GCRuntime* gc) |
| 2893 |
: GCParallelTask(gc, gcstats::PhaseKind::UNMARK) {} |
| 2894 |
|
| 2895 |
void BackgroundUnmarkTask::initZones() { |
| 2896 |
MOZ_ASSERT(isIdle()); |
| 2897 |
MOZ_ASSERT(zones.empty()); |
| 2898 |
MOZ_ASSERT(!isCancelled()); |
| 2899 |
|
| 2900 |
// We can't safely iterate the zones vector from another thread so we copy the |
| 2901 |
// zones to be collected into another vector. |
| 2902 |
AutoEnterOOMUnsafeRegion oomUnsafe; |
| 2903 |
for (GCZonesIter zone(gc); !zone.done(); zone.next()) { |
| 2904 |
if (!zones.append(zone.get())) { |
| 2905 |
oomUnsafe.crash("BackgroundUnmarkTask::initZones"); |
| 2906 |
} |
| 2907 |
|
| 2908 |
zone->arenas.clearFreeLists(); |
| 2909 |
zone->arenas.moveArenasToCollectingLists(); |
| 2910 |
} |
| 2911 |
} |
| 2912 |
|
| 2913 |
void BackgroundUnmarkTask::run(AutoLockHelperThreadState& lock) { |
| 2914 |
{ |
| 2915 |
AutoUnlockHelperThreadState unlock(lock); |
| 2916 |
unmark(); |
| 2917 |
zones.clear(); |
| 2918 |
} |
| 2919 |
|
| 2920 |
gc->maybeRequestGCAfterBackgroundTask(lock); |
| 2921 |
} |
| 2922 |
|
| 2923 |
void BackgroundUnmarkTask::unmark() { |
| 2924 |
for (Zone* zone : zones) { |
| 2925 |
for (auto kind : AllAllocKinds()) { |
| 2926 |
ArenaList& arenas = zone->arenas.collectingArenaList(kind); |
| 2927 |
for (auto arena = arenas.iter(); !arena.done(); arena.next()) { |
| 2928 |
arena->unmarkAll(); |
| 2929 |
if (isCancelled()) { |
| 2930 |
return; |
| 2931 |
} |
| 2932 |
} |
| 2933 |
} |
| 2934 |
} |
| 2935 |
} |
| 2936 |
|
| 2937 |
void GCRuntime::endPreparePhase(JS::GCReason reason) { |
| 2938 |
MOZ_ASSERT(unmarkTask.isIdle()); |
| 2939 |
|
| 2940 |
for (GCZonesIter zone(this); !zone.done(); zone.next()) { |
| 2941 |
zone->setPreservingCode(false); |
| 2942 |
} |
| 2943 |
|
| 2944 |
// Discard JIT code more aggressively if the process is approaching its |
| 2945 |
// executable code limit. |
| 2946 |
bool canAllocateMoreCode = jit::CanLikelyAllocateMoreExecutableMemory(); |
| 2947 |
auto currentTime = TimeStamp::Now(); |
| 2948 |
|
| 2949 |
Compartment* activeCompartment = nullptr; |
| 2950 |
jit::JitActivationIterator activation(rt->mainContextFromOwnThread()); |
| 2951 |
if (!activation.done()) { |
| 2952 |
activeCompartment = activation->compartment(); |
| 2953 |
} |
| 2954 |
|
| 2955 |
for (CompartmentsIter c(rt); !c.done(); c.next()) { |
| 2956 |
c->gcState.scheduledForDestruction = false; |
| 2957 |
c->gcState.maybeAlive = false; |
| 2958 |
c->gcState.hasEnteredRealm = false; |
| 2959 |
if (c->invisibleToDebugger()) { |
| 2960 |
c->gcState.maybeAlive = true; // Presumed to be a system compartment. |
| 2961 |
} |
| 2962 |
bool isActiveCompartment = c == activeCompartment; |
| 2963 |
for (RealmsInCompartmentIter r(c); !r.done(); r.next()) { |
| 2964 |
if (r->shouldTraceGlobal() || !r->zone()->isGCScheduled()) { |
| 2965 |
c->gcState.maybeAlive = true; |
| 2966 |
} |
| 2967 |
if (shouldPreserveJITCode(r, currentTime, reason, canAllocateMoreCode, |
| 2968 |
isActiveCompartment)) { |
| 2969 |
r->zone()->setPreservingCode(true); |
| 2970 |
} |
| 2971 |
if (r->hasBeenEnteredIgnoringJit()) { |
| 2972 |
c->gcState.hasEnteredRealm = true; |
| 2973 |
} |
| 2974 |
} |
| 2975 |
} |
| 2976 |
|
| 2977 |
/* |
| 2978 |
* Perform remaining preparation work that must take place in the first true |
| 2979 |
* GC slice. |
| 2980 |
*/ |
| 2981 |
|
| 2982 |
{ |
| 2983 |
gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::PREPARE); |
| 2984 |
|
| 2985 |
AutoLockHelperThreadState helperLock; |
| 2986 |
|
| 2987 |
/* Clear mark state for WeakMaps in parallel with other work. */ |
| 2988 |
AutoRunParallelTask unmarkWeakMaps(this, &GCRuntime::unmarkWeakMaps, |
| 2989 |
gcstats::PhaseKind::UNMARK_WEAKMAPS, |
| 2990 |
GCUse::Unspecified, helperLock); |
| 2991 |
|
| 2992 |
AutoUnlockHelperThreadState unlock(helperLock); |
| 2993 |
|
| 2994 |
maybeDiscardJitCodeForGC(); |
| 2995 |
|
| 2996 |
/* |
| 2997 |
* We must purge the runtime at the beginning of an incremental GC. The |
| 2998 |
* danger if we purge later is that the snapshot invariant of |
| 2999 |
* incremental GC will be broken, as follows. If some object is |
| 3000 |
* reachable only through some cache (say the dtoaCache) then it will |
| 3001 |
* not be part of the snapshot. If we purge after root marking, then |
| 3002 |
* the mutator could obtain a pointer to the object and start using |
| 3003 |
* it. This object might never be marked, so a GC hazard would exist. |
| 3004 |
*/ |
| 3005 |
purgeRuntime(); |
| 3006 |
} |
| 3007 |
|
| 3008 |
// This will start background free for lifo blocks queued by purgeRuntime, |
| 3009 |
// even if there's nothing in the nursery. Record the number of the minor GC |
| 3010 |
// so we can check whether we need to wait for it to finish or whether a |
| 3011 |
// subsequent minor GC already did this. |
| 3012 |
collectNurseryFromMajorGC(reason); |
| 3013 |
initialMinorGCNumber = minorGCNumber; |
| 3014 |
|
| 3015 |
{ |
| 3016 |
gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::PREPARE); |
| 3017 |
// Relazify functions after discarding JIT code (we can't relazify functions |
| 3018 |
// with JIT code) and before the actual mark phase, so that the current GC |
| 3019 |
// can collect the JSScripts we're unlinking here. We do this only when |
| 3020 |
// we're performing a shrinking GC, as too much relazification can cause |
| 3021 |
// performance issues when we have to reparse the same functions over and |
| 3022 |
// over. |
| 3023 |
if (isShrinkingGC()) { |
| 3024 |
relazifyFunctionsForShrinkingGC(); |
| 3025 |
purgePropMapTablesForShrinkingGC(); |
| 3026 |
purgeSourceURLsForShrinkingGC(); |
| 3027 |
} |
| 3028 |
|
| 3029 |
if (isShutdownGC()) { |
| 3030 |
/* Clear any engine roots that may hold external data live. */ |
| 3031 |
for (GCZonesIter zone(this); !zone.done(); zone.next()) { |
| 3032 |
zone->clearRootsForShutdownGC(); |
| 3033 |
} |
| 3034 |
|
| 3035 |
#ifdef DEBUG |
| 3036 |
testMarkQueue.clear(); |
| 3037 |
queuePos = 0; |
| 3038 |
#endif |
| 3039 |
} |
| 3040 |
} |
| 3041 |
|
| 3042 |
#ifdef DEBUG |
| 3043 |
if (fullCompartmentChecks) { |
| 3044 |
checkForCompartmentMismatches(); |
| 3045 |
} |
| 3046 |
#endif |
| 3047 |
} |
| 3048 |
|
| 3049 |
AutoUpdateLiveCompartments::AutoUpdateLiveCompartments(GCRuntime* gc) : gc(gc) { |
| 3050 |
for (GCCompartmentsIter c(gc->rt); !c.done(); c.next()) { |
| 3051 |
c->gcState.hasMarkedCells = false; |
| 3052 |
} |
| 3053 |
} |
| 3054 |
|
| 3055 |
AutoUpdateLiveCompartments::~AutoUpdateLiveCompartments() { |
| 3056 |
for (GCCompartmentsIter c(gc->rt); !c.done(); c.next()) { |
| 3057 |
if (c->gcState.hasMarkedCells) { |
| 3058 |
c->gcState.maybeAlive = true; |
| 3059 |
} |
| 3060 |
} |
| 3061 |
} |
| 3062 |
|
| 3063 |
Zone::GCState Zone::initialMarkingState() const { |
| 3064 |
if (isAtomsZone()) { |
| 3065 |
// Don't delay gray marking in the atoms zone like we do in other zones. |
| 3066 |
return MarkBlackAndGray; |
| 3067 |
} |
| 3068 |
|
| 3069 |
return MarkBlackOnly; |
| 3070 |
} |
| 3071 |
|
| 3072 |
void GCRuntime::beginMarkPhase(AutoGCSession& session) { |
| 3073 |
/* |
| 3074 |
* Mark phase. |
| 3075 |
*/ |
| 3076 |
gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::MARK); |
| 3077 |
|
| 3078 |
// This is the slice we actually start collecting. The number can be used to |
| 3079 |
// check whether a major GC has started so we must not increment it until we |
| 3080 |
// get here. |
| 3081 |
incMajorGcNumber(); |
| 3082 |
|
| 3083 |
#ifdef DEBUG |
| 3084 |
queuePos = 0; |
| 3085 |
queueMarkColor.reset(); |
| 3086 |
#endif |
| 3087 |
|
| 3088 |
{ |
| 3089 |
BufferAllocator::MaybeLock lock; |
| 3090 |
for (GCZonesIter zone(this); !zone.done(); zone.next()) { |
| 3091 |
// In an incremental GC, clear the arena free lists to ensure that |
| 3092 |
// subsequent allocations refill them and end up marking new cells black. |
| 3093 |
// See arenaAllocatedDuringGC(). |
| 3094 |
zone->arenas.clearFreeLists(); |
| 3095 |
|
| 3096 |
#ifdef JS_GC_ZEAL |
| 3097 |
if (hasZealMode(ZealMode::YieldBeforeRootMarking)) { |
| 3098 |
for (auto kind : AllAllocKinds()) { |
| 3099 |
for (ArenaIter arena(zone, kind); !arena.done(); arena.next()) { |
| 3100 |
arena->checkNoMarkedCells(); |
| 3101 |
} |
| 3102 |
} |
| 3103 |
} |
| 3104 |
#endif |
| 3105 |
|
| 3106 |
// Incremental marking barriers are enabled at this point. |
| 3107 |
zone->changeGCState(Zone::Prepare, zone->initialMarkingState()); |
| 3108 |
|
| 3109 |
// Merge arenas allocated during the prepare phase, then move all arenas |
| 3110 |
// to the collecting arena lists. |
| 3111 |
zone->arenas.mergeArenasFromCollectingLists(); |
| 3112 |
zone->arenas.moveArenasToCollectingLists(); |
| 3113 |
|
| 3114 |
// Prepare sized allocator for major GC. |
| 3115 |
zone->bufferAllocator.startMajorCollection(lock); |
| 3116 |
|
| 3117 |
for (RealmsInZoneIter realm(zone); !realm.done(); realm.next()) { |
| 3118 |
realm->clearAllocatedDuringGC(); |
| 3119 |
} |
| 3120 |
} |
| 3121 |
} |
| 3122 |
|
| 3123 |
updateSchedulingStateOnGCStart(); |
| 3124 |
stats().measureInitialHeapSizes(); |
| 3125 |
|
| 3126 |
useParallelMarking = SingleThreadedMarking; |
| 3127 |
if (canMarkInParallel() && initParallelMarking()) { |
| 3128 |
useParallelMarking = AllowParallelMarking; |
| 3129 |
} |
| 3130 |
|
| 3131 |
MOZ_ASSERT(!hasDelayedMarking()); |
| 3132 |
haveAllImplicitEdges_ = true; |
| 3133 |
for (auto& marker : markers) { |
| 3134 |
marker->start(); |
| 3135 |
} |
| 3136 |
|
| 3137 |
if (rt->isBeingDestroyed()) { |
| 3138 |
checkNoRuntimeRoots(session); |
| 3139 |
} else { |
| 3140 |
AutoUpdateLiveCompartments updateLive(this); |
| 3141 |
#ifdef DEBUG |
| 3142 |
AutoSetThreadIsMarking threadIsMarking; |
| 3143 |
#endif // DEBUG |
| 3144 |
|
| 3145 |
marker().setRootMarkingMode(true); |
| 3146 |
traceRuntimeForMajorGC(marker().tracer(), session); |
| 3147 |
marker().setRootMarkingMode(false); |
| 3148 |
} |
| 3149 |
} |
| 3150 |
|
| 3151 |
void GCRuntime::findDeadCompartments() { |
| 3152 |
gcstats::AutoPhase ap1(stats(), gcstats::PhaseKind::FIND_DEAD_COMPARTMENTS); |
| 3153 |
|
| 3154 |
/* |
| 3155 |
* This code ensures that if a compartment is "dead", then it will be |
| 3156 |
* collected in this GC. A compartment is considered dead if its maybeAlive |
| 3157 |
* flag is false. The maybeAlive flag is set if: |
| 3158 |
* |
| 3159 |
* (1) the compartment has been entered (set in beginMarkPhase() above) |
| 3160 |
* (2) the compartment's zone is not being collected (set in |
| 3161 |
* endPreparePhase() above) |
| 3162 |
* (3) an object in the compartment was marked during root marking, either |
| 3163 |
* as a black root or a gray root. This is arranged by |
| 3164 |
* SetCompartmentHasMarkedCells and AutoUpdateLiveCompartments. |
| 3165 |
* (4) the compartment has incoming cross-compartment edges from another |
| 3166 |
* compartment that has maybeAlive set (set by this method). |
| 3167 |
* (5) the compartment has the invisibleToDebugger flag set, as it is |
| 3168 |
* presumed to be a system compartment (set in endPreparePhase() above) |
| 3169 |
* |
| 3170 |
* If the maybeAlive is false, then we set the scheduledForDestruction flag. |
| 3171 |
* At the end of the GC, we look for compartments where |
| 3172 |
* scheduledForDestruction is true. These are compartments that were somehow |
| 3173 |
* "revived" during the incremental GC. If any are found, we do a special, |
| 3174 |
* non-incremental GC of those compartments to try to collect them. |
| 3175 |
* |
| 3176 |
* Compartments can be revived for a variety of reasons, including: |
| 3177 |
* |
| 3178 |
* (1) A dead reflector can be revived by DOM code that still refers to the |
| 3179 |
* underlying DOM node (see bug 811587). |
| 3180 |
* (2) JS_TransplantObject iterates over all compartments, live or dead, and |
| 3181 |
* operates on their objects. This can trigger read barriers and mark |
| 3182 |
* unreachable objects. See bug 803376 for details on this problem. To |
| 3183 |
* avoid the problem, we try to avoid allocation and read barriers |
| 3184 |
* during JS_TransplantObject and the like. |
| 3185 |
* (3) Read barriers. A compartment may only have weak roots and reading one |
| 3186 |
* of these will cause the compartment to stay alive even though the GC |
| 3187 |
* thought it should die. An example of this is Gecko's unprivileged |
| 3188 |
* junk scope, which is handled by ignoring system compartments (see bug |
| 3189 |
* 1868437). |
| 3190 |
*/ |
| 3191 |
|
| 3192 |
// Propagate the maybeAlive flag via cross-compartment edges. |
| 3193 |
|
| 3194 |
Vector<Compartment*, 0, js::SystemAllocPolicy> workList; |
| 3195 |
|
| 3196 |
for (CompartmentsIter comp(rt); !comp.done(); comp.next()) { |
| 3197 |
if (comp->gcState.maybeAlive) { |
| 3198 |
if (!workList.append(comp)) { |
| 3199 |
return; |
| 3200 |
} |
| 3201 |
} |
| 3202 |
} |
| 3203 |
|
| 3204 |
while (!workList.empty()) { |
| 3205 |
Compartment* comp = workList.popCopy(); |
| 3206 |
for (Compartment::WrappedObjectCompartmentEnum e(comp); !e.empty(); |
| 3207 |
e.popFront()) { |
| 3208 |
Compartment* dest = e.front(); |
| 3209 |
if (!dest->gcState.maybeAlive) { |
| 3210 |
dest->gcState.maybeAlive = true; |
| 3211 |
if (!workList.append(dest)) { |
| 3212 |
return; |
| 3213 |
} |
| 3214 |
} |
| 3215 |
} |
| 3216 |
} |
| 3217 |
|
| 3218 |
// Set scheduledForDestruction based on maybeAlive. |
| 3219 |
|
| 3220 |
for (GCCompartmentsIter comp(rt); !comp.done(); comp.next()) { |
| 3221 |
MOZ_ASSERT(!comp->gcState.scheduledForDestruction); |
| 3222 |
if (!comp->gcState.maybeAlive) { |
| 3223 |
comp->gcState.scheduledForDestruction = true; |
| 3224 |
} |
| 3225 |
} |
| 3226 |
} |
| 3227 |
|
| 3228 |
void GCRuntime::updateSchedulingStateOnGCStart() { |
| 3229 |
heapSize.updateOnGCStart(); |
| 3230 |
|
| 3231 |
// Update memory counters for the zones we are collecting. |
| 3232 |
for (GCZonesIter zone(this); !zone.done(); zone.next()) { |
| 3233 |
zone->updateSchedulingStateOnGCStart(); |
| 3234 |
} |
| 3235 |
} |
| 3236 |
|
| 3237 |
inline bool GCRuntime::canMarkInParallel() const { |
| 3238 |
MOZ_ASSERT(state() >= gc::State::MarkRoots); |
| 3239 |
|
| 3240 |
#if defined(DEBUG) || defined(JS_OOM_BREAKPOINT) |
| 3241 |
// OOM testing limits the engine to using a single helper thread. |
| 3242 |
if (oom::simulator.targetThread() == THREAD_TYPE_GCPARALLEL) { |
| 3243 |
return false; |
| 3244 |
} |
| 3245 |
#endif |
| 3246 |
|
| 3247 |
return markers.length() > 1 && stats().initialCollectedBytes() >= |
| 3248 |
tunables.parallelMarkingThresholdBytes(); |
| 3249 |
} |
| 3250 |
|
| 3251 |
bool GCRuntime::initParallelMarking() { |
| 3252 |
// This is called at the start of collection. |
| 3253 |
|
| 3254 |
MOZ_ASSERT(canMarkInParallel()); |
| 3255 |
|
| 3256 |
// Reserve/release helper threads for worker runtimes. These are released at |
| 3257 |
// the end of sweeping. If there are not enough helper threads because |
| 3258 |
// other runtimes are marking in parallel then parallel marking will not be |
| 3259 |
// used. |
| 3260 |
if (!rt->isMainRuntime() && !reserveMarkingThreads(markers.length())) { |
| 3261 |
return false; |
| 3262 |
} |
| 3263 |
|
| 3264 |
// Allocate stack for parallel markers. The first marker always has stack |
| 3265 |
// allocated. Other markers have their stack freed in |
| 3266 |
// GCRuntime::finishCollection. |
| 3267 |
for (size_t i = 1; i < markers.length(); i++) { |
| 3268 |
if (!markers[i]->initStack()) { |
| 3269 |
return false; |
| 3270 |
} |
| 3271 |
} |
| 3272 |
|
| 3273 |
return true; |
| 3274 |
} |
| 3275 |
|
| 3276 |
IncrementalProgress GCRuntime::markUntilBudgetExhausted( |
| 3277 |
SliceBudget& sliceBudget, ParallelMarking allowParallelMarking, |
| 3278 |
ShouldReportMarkTime reportTime) { |
| 3279 |
// Run a marking slice and return whether the stack is now empty. |
| 3280 |
|
| 3281 |
AutoMajorGCProfilerEntry s(this); |
| 3282 |
|
| 3283 |
if (initialState != State::Mark) { |
| 3284 |
sliceBudget.forceCheck(); |
| 3285 |
if (sliceBudget.isOverBudget()) { |
| 3286 |
return NotFinished; |
| 3287 |
} |
| 3288 |
} |
| 3289 |
|
| 3290 |
#ifdef DEBUG |
| 3291 |
AutoSetThreadIsMarking threadIsMarking; |
| 3292 |
#endif // DEBUG |
| 3293 |
|
| 3294 |
if (processTestMarkQueue() == QueueYielded) { |
| 3295 |
return NotFinished; |
| 3296 |
} |
| 3297 |
|
| 3298 |
if (allowParallelMarking) { |
| 3299 |
MOZ_ASSERT(canMarkInParallel()); |
| 3300 |
MOZ_ASSERT(parallelMarkingEnabled); |
| 3301 |
MOZ_ASSERT(reportTime); |
| 3302 |
MOZ_ASSERT(!isBackgroundMarking()); |
| 3303 |
|
| 3304 |
ParallelMarker pm(this); |
| 3305 |
if (!pm.mark(sliceBudget)) { |
| 3306 |
return NotFinished; |
| 3307 |
} |
| 3308 |
|
| 3309 |
assertNoMarkingWork(); |
| 3310 |
return Finished; |
| 3311 |
} |
| 3312 |
|
| 3313 |
return marker().markUntilBudgetExhausted(sliceBudget, reportTime) |
| 3314 |
? Finished |
| 3315 |
: NotFinished; |
| 3316 |
} |
| 3317 |
|
| 3318 |
void GCRuntime::drainMarkStack() { |
| 3319 |
auto unlimited = SliceBudget::unlimited(); |
| 3320 |
MOZ_RELEASE_ASSERT(marker().markUntilBudgetExhausted(unlimited)); |
| 3321 |
} |
| 3322 |
|
| 3323 |
#ifdef DEBUG |
| 3324 |
|
| 3325 |
const GCVector<HeapPtr<JS::Value>, 0, SystemAllocPolicy>& |
| 3326 |
GCRuntime::getTestMarkQueue() const { |
| 3327 |
return testMarkQueue.get(); |
| 3328 |
} |
| 3329 |
|
| 3330 |
bool GCRuntime::appendTestMarkQueue(const JS::Value& value) { |
| 3331 |
return testMarkQueue.append(value); |
| 3332 |
} |
| 3333 |
|
| 3334 |
void GCRuntime::clearTestMarkQueue() { |
| 3335 |
testMarkQueue.clear(); |
| 3336 |
queuePos = 0; |
| 3337 |
} |
| 3338 |
|
| 3339 |
size_t GCRuntime::testMarkQueuePos() const { return queuePos; } |
| 3340 |
|
| 3341 |
size_t GCRuntime::testMarkQueueRemaining() const { |
| 3342 |
MOZ_ASSERT(queuePos <= testMarkQueue.length()); |
| 3343 |
return testMarkQueue.length() - queuePos; |
| 3344 |
} |
| 3345 |
|
| 3346 |
#endif |
| 3347 |
|
| 3348 |
GCRuntime::MarkQueueProgress GCRuntime::processTestMarkQueue() { |
| 3349 |
#ifdef DEBUG |
| 3350 |
if (testMarkQueue.empty()) { |
| 3351 |
return QueueComplete; |
| 3352 |
} |
| 3353 |
|
| 3354 |
if (queueMarkColor == mozilla::Some(MarkColor::Gray) && |
| 3355 |
state() != State::Sweep) { |
| 3356 |
return QueueSuspended; |
| 3357 |
} |
| 3358 |
|
| 3359 |
// If the queue wants to be gray marking, but we've pushed a black object |
| 3360 |
// since set-color-gray was processed, then we can't switch to gray and must |
| 3361 |
// again wait until gray marking is possible. |
| 3362 |
// |
| 3363 |
// Remove this code if the restriction against marking gray during black is |
| 3364 |
// relaxed. |
| 3365 |
if (queueMarkColor == mozilla::Some(MarkColor::Gray) && |
| 3366 |
marker().hasBlackEntries()) { |
| 3367 |
return QueueSuspended; |
| 3368 |
} |
| 3369 |
|
| 3370 |
// If the queue wants to be marking a particular color, switch to that color. |
| 3371 |
// In any case, restore the mark color to whatever it was when we entered |
| 3372 |
// this function. |
| 3373 |
bool willRevertToGray = marker().markColor() == MarkColor::Gray; |
| 3374 |
AutoSetMarkColor autoRevertColor( |
| 3375 |
marker(), queueMarkColor.valueOr(marker().markColor())); |
| 3376 |
|
| 3377 |
// Process the mark queue by taking each object in turn, pushing it onto the |
| 3378 |
// mark stack, and processing just the top element with processMarkStackTop |
| 3379 |
// without recursing into reachable objects. |
| 3380 |
while (queuePos < testMarkQueue.length()) { |
| 3381 |
Value val = testMarkQueue[queuePos++].get(); |
| 3382 |
if (val.isObject()) { |
| 3383 |
JSObject* obj = &val.toObject(); |
| 3384 |
JS::Zone* zone = obj->zone(); |
| 3385 |
if (!zone->isGCMarking() || obj->isMarkedAtLeast(marker().markColor())) { |
| 3386 |
continue; |
| 3387 |
} |
| 3388 |
|
| 3389 |
// If we have started sweeping, obey sweep group ordering. But note that |
| 3390 |
// we will first be called during the initial sweep slice, when the sweep |
| 3391 |
// group indexes have not yet been computed. In that case, we can mark |
| 3392 |
// freely. |
| 3393 |
if (state() == State::Sweep && initialState != State::Sweep) { |
| 3394 |
if (zone->gcSweepGroupIndex < getCurrentSweepGroupIndex()) { |
| 3395 |
// Too late. This must have been added after we started collecting, |
| 3396 |
// and we've already processed its sweep group. Skip it. |
| 3397 |
continue; |
| 3398 |
} |
| 3399 |
if (zone->gcSweepGroupIndex > getCurrentSweepGroupIndex()) { |
| 3400 |
// Not ready yet. Wait until we reach the object's sweep group. |
| 3401 |
queuePos--; |
| 3402 |
return QueueSuspended; |
| 3403 |
} |
| 3404 |
} |
| 3405 |
|
| 3406 |
if (marker().markColor() == MarkColor::Gray && |
| 3407 |
zone->isGCMarkingBlackOnly()) { |
| 3408 |
// Have not yet reached the point where we can mark this object, so |
| 3409 |
// continue with the GC. |
| 3410 |
queuePos--; |
| 3411 |
return QueueSuspended; |
| 3412 |
} |
| 3413 |
|
| 3414 |
if (marker().markColor() == MarkColor::Black && willRevertToGray) { |
| 3415 |
// If we put any black objects on the stack, we wouldn't be able to |
| 3416 |
// return to gray marking. So delay the marking until we're back to |
| 3417 |
// black marking. |
| 3418 |
queuePos--; |
| 3419 |
return QueueSuspended; |
| 3420 |
} |
| 3421 |
|
| 3422 |
// Mark the object. |
| 3423 |
if (!marker().markOneObjectForTest(obj)) { |
| 3424 |
// If we overflowed the stack here and delayed marking, then we won't be |
| 3425 |
// testing what we think we're testing. |
| 3426 |
MOZ_ASSERT(obj->asTenured().arena()->onDelayedMarkingList()); |
| 3427 |
printf_stderr( |
| 3428 |
"Hit mark stack limit while marking test queue; test results may " |
| 3429 |
"be invalid"); |
| 3430 |
} |
| 3431 |
} else if (val.isString()) { |
| 3432 |
JSLinearString* str = &val.toString()->asLinear(); |
| 3433 |
if (js::StringEqualsLiteral(str, "yield") && isIncrementalGc()) { |
| 3434 |
return QueueYielded; |
| 3435 |
} |
| 3436 |
|
| 3437 |
if (js::StringEqualsLiteral(str, "enter-weak-marking-mode") || |
| 3438 |
js::StringEqualsLiteral(str, "abort-weak-marking-mode")) { |
| 3439 |
if (marker().isRegularMarking()) { |
| 3440 |
// We can't enter weak marking mode at just any time, so instead |
| 3441 |
// we'll stop processing the queue and continue on with the GC. Once |
| 3442 |
// we enter weak marking mode, we can continue to the rest of the |
| 3443 |
// queue. Note that we will also suspend for aborting, and then abort |
| 3444 |
// the earliest following weak marking mode. |
| 3445 |
queuePos--; |
| 3446 |
return QueueSuspended; |
| 3447 |
} |
| 3448 |
if (js::StringEqualsLiteral(str, "abort-weak-marking-mode")) { |
| 3449 |
marker().abortLinearWeakMarking(); |
| 3450 |
} |
| 3451 |
} else if (js::StringEqualsLiteral(str, "drain")) { |
| 3452 |
auto unlimited = SliceBudget::unlimited(); |
| 3453 |
MOZ_RELEASE_ASSERT( |
| 3454 |
marker().markUntilBudgetExhausted(unlimited, DontReportMarkTime)); |
| 3455 |
} else if (js::StringEqualsLiteral(str, "set-color-gray")) { |
| 3456 |
queueMarkColor = mozilla::Some(MarkColor::Gray); |
| 3457 |
if (state() != State::Sweep || marker().hasBlackEntries()) { |
| 3458 |
// Cannot mark gray yet, so continue with the GC. |
| 3459 |
queuePos--; |
| 3460 |
return QueueSuspended; |
| 3461 |
} |
| 3462 |
marker().setMarkColor(MarkColor::Gray); |
| 3463 |
} else if (js::StringEqualsLiteral(str, "set-color-black")) { |
| 3464 |
queueMarkColor = mozilla::Some(MarkColor::Black); |
| 3465 |
marker().setMarkColor(MarkColor::Black); |
| 3466 |
} else if (js::StringEqualsLiteral(str, "unset-color")) { |
| 3467 |
queueMarkColor.reset(); |
| 3468 |
} |
| 3469 |
} |
| 3470 |
} |
| 3471 |
|
| 3472 |
// Once the queue is complete, do not force a mark color (since the next time |
| 3473 |
// the queue is processed, it should not be forcing one.) |
| 3474 |
queueMarkColor.reset(); |
| 3475 |
#endif |
| 3476 |
|
| 3477 |
return QueueComplete; |
| 3478 |
} |
| 3479 |
|
| 3480 |
static bool IsEmergencyGC(JS::GCReason reason) { |
| 3481 |
return reason == JS::GCReason::LAST_DITCH || |
| 3482 |
reason == JS::GCReason::MEM_PRESSURE; |
| 3483 |
} |
| 3484 |
|
| 3485 |
void GCRuntime::finishCollection(JS::GCReason reason) { |
| 3486 |
assertBackgroundSweepingFinished(); |
| 3487 |
|
| 3488 |
MOZ_ASSERT(!hasDelayedMarking()); |
| 3489 |
for (size_t i = 0; i < markers.length(); i++) { |
| 3490 |
const auto& marker = markers[i]; |
| 3491 |
marker->stop(); |
| 3492 |
if (i == 0) { |
| 3493 |
marker->resetStackCapacity(); |
| 3494 |
} else { |
| 3495 |
marker->freeStack(); |
| 3496 |
} |
| 3497 |
} |
| 3498 |
|
| 3499 |
maybeStopPretenuring(); |
| 3500 |
|
| 3501 |
if (IsEmergencyGC(reason)) { |
| 3502 |
waitBackgroundFreeEnd(); |
| 3503 |
} |
| 3504 |
|
| 3505 |
TimeStamp currentTime = TimeStamp::Now(); |
| 3506 |
|
| 3507 |
updateSchedulingStateOnGCEnd(currentTime); |
| 3508 |
|
| 3509 |
for (GCZonesIter zone(this); !zone.done(); zone.next()) { |
| 3510 |
zone->changeGCState(Zone::Finished, Zone::NoGC); |
| 3511 |
zone->notifyObservingDebuggers(); |
| 3512 |
zone->gcNextGraphNode = nullptr; |
| 3513 |
zone->gcNextGraphComponent = nullptr; |
| 3514 |
} |
| 3515 |
|
| 3516 |
#ifdef JS_GC_ZEAL |
| 3517 |
clearSelectedForMarking(); |
| 3518 |
#endif |
| 3519 |
|
| 3520 |
lastGCEndTime_ = currentTime; |
| 3521 |
|
| 3522 |
checkGCStateNotInUse(); |
| 3523 |
} |
| 3524 |
|
| 3525 |
void GCRuntime::checkGCStateNotInUse() { |
| 3526 |
#ifdef DEBUG |
| 3527 |
for (auto& marker : markers) { |
| 3528 |
MOZ_ASSERT(!marker->isActive()); |
| 3529 |
MOZ_ASSERT(marker->isDrained()); |
| 3530 |
} |
| 3531 |
MOZ_ASSERT(!hasDelayedMarking()); |
| 3532 |
|
| 3533 |
MOZ_ASSERT(!lastMarkSlice); |
| 3534 |
|
| 3535 |
MOZ_ASSERT(foregroundFinalizedArenas.ref().isNothing()); |
| 3536 |
|
| 3537 |
for (ZonesIter zone(this, WithAtoms); !zone.done(); zone.next()) { |
| 3538 |
if (zone->wasCollected()) { |
| 3539 |
zone->arenas.checkGCStateNotInUse(); |
| 3540 |
} |
| 3541 |
MOZ_ASSERT(!zone->wasGCStarted()); |
| 3542 |
MOZ_ASSERT(!zone->needsIncrementalBarrier()); |
| 3543 |
MOZ_ASSERT(!zone->isOnList()); |
| 3544 |
MOZ_ASSERT(!zone->gcNextGraphNode); |
| 3545 |
MOZ_ASSERT(!zone->gcNextGraphComponent); |
| 3546 |
zone->bufferAllocator.checkGCStateNotInUse(); |
| 3547 |
} |
| 3548 |
|
| 3549 |
MOZ_ASSERT(zonesToMaybeCompact.ref().isEmpty()); |
| 3550 |
MOZ_ASSERT(cellsToAssertNotGray.ref().empty()); |
| 3551 |
|
| 3552 |
AutoLockHelperThreadState lock; |
| 3553 |
MOZ_ASSERT(!requestSliceAfterBackgroundTask); |
| 3554 |
MOZ_ASSERT(unmarkTask.isIdle(lock)); |
| 3555 |
MOZ_ASSERT(markTask.isIdle(lock)); |
| 3556 |
MOZ_ASSERT(sweepTask.isIdle(lock)); |
| 3557 |
MOZ_ASSERT(decommitTask.isIdle(lock)); |
| 3558 |
#endif |
| 3559 |
} |
| 3560 |
|
| 3561 |
void GCRuntime::maybeStopPretenuring() { |
| 3562 |
nursery().maybeStopPretenuring(this); |
| 3563 |
|
| 3564 |
size_t zonesWhereStringsEnabled = 0; |
| 3565 |
size_t zonesWhereBigIntsEnabled = 0; |
| 3566 |
|
| 3567 |
for (GCZonesIter zone(this); !zone.done(); zone.next()) { |
| 3568 |
if (zone->nurseryStringsDisabled || zone->nurseryBigIntsDisabled) { |
| 3569 |
// We may need to reset allocation sites and discard JIT code to recover |
| 3570 |
// if we find object lifetimes have changed. |
| 3571 |
if (zone->pretenuring.shouldResetPretenuredAllocSites()) { |
| 3572 |
zone->unknownAllocSite(JS::TraceKind::String)->maybeResetState(); |
| 3573 |
zone->unknownAllocSite(JS::TraceKind::BigInt)->maybeResetState(); |
| 3574 |
if (zone->nurseryStringsDisabled) { |
| 3575 |
zone->nurseryStringsDisabled = false; |
| 3576 |
zonesWhereStringsEnabled++; |
| 3577 |
} |
| 3578 |
if (zone->nurseryBigIntsDisabled) { |
| 3579 |
zone->nurseryBigIntsDisabled = false; |
| 3580 |
zonesWhereBigIntsEnabled++; |
| 3581 |
} |
| 3582 |
nursery().updateAllocFlagsForZone(zone); |
| 3583 |
} |
| 3584 |
} |
| 3585 |
} |
| 3586 |
|
| 3587 |
if (nursery().reportPretenuring()) { |
| 3588 |
if (zonesWhereStringsEnabled) { |
| 3589 |
fprintf(stderr, "GC re-enabled nursery string allocation in %zu zones\n", |
| 3590 |
zonesWhereStringsEnabled); |
| 3591 |
} |
| 3592 |
if (zonesWhereBigIntsEnabled) { |
| 3593 |
fprintf(stderr, "GC re-enabled nursery big int allocation in %zu zones\n", |
| 3594 |
zonesWhereBigIntsEnabled); |
| 3595 |
} |
| 3596 |
} |
| 3597 |
} |
| 3598 |
|
| 3599 |
void GCRuntime::updateSchedulingStateOnGCEnd(TimeStamp currentTime) { |
| 3600 |
TimeDuration totalGCTime = stats().totalGCTime(); |
| 3601 |
size_t totalInitialBytes = stats().initialCollectedBytes(); |
| 3602 |
|
| 3603 |
for (GCZonesIter zone(this); !zone.done(); zone.next()) { |
| 3604 |
if (tunables.balancedHeapLimitsEnabled() && totalInitialBytes != 0) { |
| 3605 |
zone->updateCollectionRate(totalGCTime, totalInitialBytes); |
| 3606 |
} |
| 3607 |
zone->clearGCSliceThresholds(); |
| 3608 |
zone->updateGCStartThresholds(*this); |
| 3609 |
} |
| 3610 |
} |
| 3611 |
|
| 3612 |
void GCRuntime::updateAllGCStartThresholds() { |
| 3613 |
for (ZonesIter zone(this, WithAtoms); !zone.done(); zone.next()) { |
| 3614 |
zone->updateGCStartThresholds(*this); |
| 3615 |
} |
| 3616 |
} |
| 3617 |
|
| 3618 |
void GCRuntime::updateAllocationRates() { |
| 3619 |
// Calculate mutator time since the last update. This ignores the fact that |
| 3620 |
// the zone could have been created since the last update. |
| 3621 |
|
| 3622 |
TimeStamp currentTime = TimeStamp::Now(); |
| 3623 |
TimeDuration totalTime = currentTime - lastAllocRateUpdateTime; |
| 3624 |
if (collectorTimeSinceAllocRateUpdate >= totalTime) { |
| 3625 |
// It shouldn't happen but occasionally we see collector time being larger |
| 3626 |
// than total time. Skip the update in that case. |
| 3627 |
return; |
| 3628 |
} |
| 3629 |
|
| 3630 |
TimeDuration mutatorTime = totalTime - collectorTimeSinceAllocRateUpdate; |
| 3631 |
|
| 3632 |
for (AllZonesIter zone(this); !zone.done(); zone.next()) { |
| 3633 |
zone->updateAllocationRate(mutatorTime); |
| 3634 |
zone->updateGCStartThresholds(*this); |
| 3635 |
} |
| 3636 |
|
| 3637 |
lastAllocRateUpdateTime = currentTime; |
| 3638 |
collectorTimeSinceAllocRateUpdate = TimeDuration::Zero(); |
| 3639 |
} |
| 3640 |
|
| 3641 |
static const char* GCHeapStateToLabel(JS::HeapState heapState) { |
| 3642 |
switch (heapState) { |
| 3643 |
case JS::HeapState::MinorCollecting: |
| 3644 |
return "Minor GC"; |
| 3645 |
case JS::HeapState::MajorCollecting: |
| 3646 |
return "Major GC"; |
| 3647 |
default: |
| 3648 |
MOZ_CRASH("Unexpected heap state when pushing GC profiling stack frame"); |
| 3649 |
} |
| 3650 |
MOZ_ASSERT_UNREACHABLE("Should have exhausted every JS::HeapState variant!"); |
| 3651 |
return nullptr; |
| 3652 |
} |
| 3653 |
|
| 3654 |
static JS::ProfilingCategoryPair GCHeapStateToProfilingCategory( |
| 3655 |
JS::HeapState heapState) { |
| 3656 |
return heapState == JS::HeapState::MinorCollecting |
| 3657 |
? JS::ProfilingCategoryPair::GCCC_MinorGC |
| 3658 |
: JS::ProfilingCategoryPair::GCCC_MajorGC; |
| 3659 |
} |
| 3660 |
|
| 3661 |
/* Start a new heap session. */ |
| 3662 |
AutoHeapSession::AutoHeapSession(GCRuntime* gc, JS::HeapState heapState) |
| 3663 |
: gc(gc), prevState(gc->heapState_) { |
| 3664 |
MOZ_ASSERT(CurrentThreadCanAccessRuntime(gc->rt)); |
| 3665 |
MOZ_ASSERT(prevState == JS::HeapState::Idle || |
| 3666 |
(prevState == JS::HeapState::MajorCollecting && |
| 3667 |
heapState == JS::HeapState::MinorCollecting)); |
| 3668 |
MOZ_ASSERT(heapState != JS::HeapState::Idle); |
| 3669 |
|
| 3670 |
gc->heapState_ = heapState; |
| 3671 |
|
| 3672 |
if (heapState == JS::HeapState::MinorCollecting || |
| 3673 |
heapState == JS::HeapState::MajorCollecting) { |
| 3674 |
profilingStackFrame.emplace( |
| 3675 |
gc->rt->mainContextFromOwnThread(), GCHeapStateToLabel(heapState), |
| 3676 |
GCHeapStateToProfilingCategory(heapState), |
| 3677 |
uint32_t(ProfilingStackFrame::Flags::RELEVANT_FOR_JS)); |
| 3678 |
} |
| 3679 |
} |
| 3680 |
|
| 3681 |
AutoHeapSession::~AutoHeapSession() { |
| 3682 |
MOZ_ASSERT(JS::RuntimeHeapIsBusy()); |
| 3683 |
gc->heapState_ = prevState; |
| 3684 |
} |
| 3685 |
|
| 3686 |
static const char* MajorGCStateToLabel(State state) { |
| 3687 |
switch (state) { |
| 3688 |
case State::Mark: |
| 3689 |
return "js::GCRuntime::markUntilBudgetExhausted"; |
| 3690 |
case State::Sweep: |
| 3691 |
return "js::GCRuntime::performSweepActions"; |
| 3692 |
case State::Compact: |
| 3693 |
return "js::GCRuntime::compactPhase"; |
| 3694 |
default: |
| 3695 |
MOZ_CRASH("Unexpected heap state when pushing GC profiling stack frame"); |
| 3696 |
} |
| 3697 |
|
| 3698 |
MOZ_ASSERT_UNREACHABLE("Should have exhausted every State variant!"); |
| 3699 |
return nullptr; |
| 3700 |
} |
| 3701 |
|
| 3702 |
static JS::ProfilingCategoryPair MajorGCStateToProfilingCategory(State state) { |
| 3703 |
switch (state) { |
| 3704 |
case State::Mark: |
| 3705 |
return JS::ProfilingCategoryPair::GCCC_MajorGC_Mark; |
| 3706 |
case State::Sweep: |
| 3707 |
return JS::ProfilingCategoryPair::GCCC_MajorGC_Sweep; |
| 3708 |
case State::Compact: |
| 3709 |
return JS::ProfilingCategoryPair::GCCC_MajorGC_Compact; |
| 3710 |
default: |
| 3711 |
MOZ_CRASH("Unexpected heap state when pushing GC profiling stack frame"); |
| 3712 |
} |
| 3713 |
} |
| 3714 |
|
| 3715 |
AutoMajorGCProfilerEntry::AutoMajorGCProfilerEntry(GCRuntime* gc) |
| 3716 |
: AutoGeckoProfilerEntry(gc->rt->mainContextFromAnyThread(), |
| 3717 |
MajorGCStateToLabel(gc->state()), |
| 3718 |
MajorGCStateToProfilingCategory(gc->state())) { |
| 3719 |
MOZ_ASSERT(gc->heapState() == JS::HeapState::MajorCollecting); |
| 3720 |
} |
| 3721 |
|
| 3722 |
GCRuntime::IncrementalResult GCRuntime::resetIncrementalGC( |
| 3723 |
GCAbortReason reason) { |
| 3724 |
MOZ_ASSERT(reason != GCAbortReason::None); |
| 3725 |
|
| 3726 |
// Drop as much work as possible from an ongoing incremental GC so |
| 3727 |
// we can start a new GC after it has finished. |
| 3728 |
if (incrementalState == State::NotActive) { |
| 3729 |
return IncrementalResult::Ok; |
| 3730 |
} |
| 3731 |
|
| 3732 |
AutoGCSession session(this, JS::HeapState::MajorCollecting); |
| 3733 |
|
| 3734 |
switch (incrementalState) { |
| 3735 |
case State::NotActive: |
| 3736 |
case State::Finish: |
| 3737 |
MOZ_CRASH("Unexpected GC state in resetIncrementalGC"); |
| 3738 |
break; |
| 3739 |
|
| 3740 |
case State::Prepare: |
| 3741 |
unmarkTask.cancelAndWait(); |
| 3742 |
cancelRequestedGCAfterBackgroundTask(); |
| 3743 |
[[fallthrough]]; |
| 3744 |
|
| 3745 |
case State::MarkRoots: |
| 3746 |
// We haven't done any marking yet at this point. |
| 3747 |
for (GCZonesIter zone(this); !zone.done(); zone.next()) { |
| 3748 |
zone->changeGCState(zone->gcState(), Zone::NoGC); |
| 3749 |
zone->clearGCSliceThresholds(); |
| 3750 |
zone->arenas.clearFreeLists(); |
| 3751 |
zone->arenas.mergeArenasFromCollectingLists(); |
| 3752 |
} |
| 3753 |
|
| 3754 |
incrementalState = State::NotActive; |
| 3755 |
checkGCStateNotInUse(); |
| 3756 |
break; |
| 3757 |
|
| 3758 |
case State::Mark: { |
| 3759 |
// Cancel any ongoing marking. |
| 3760 |
for (auto& marker : markers) { |
| 3761 |
marker->reset(); |
| 3762 |
} |
| 3763 |
resetDelayedMarking(); |
| 3764 |
|
| 3765 |
for (GCCompartmentsIter c(rt); !c.done(); c.next()) { |
| 3766 |
resetGrayList(c); |
| 3767 |
} |
| 3768 |
|
| 3769 |
// Wait for sweeping of nursery owned sized allocations to finish. |
| 3770 |
nursery().joinSweepTask(); |
| 3771 |
|
| 3772 |
{ |
| 3773 |
BufferAllocator::AutoLock lock(this); |
| 3774 |
for (GCZonesIter zone(this); !zone.done(); zone.next()) { |
| 3775 |
zone->changeGCState(zone->initialMarkingState(), Zone::NoGC); |
| 3776 |
zone->clearGCSliceThresholds(); |
| 3777 |
zone->arenas.unmarkPreMarkedFreeCells(); |
| 3778 |
zone->arenas.mergeArenasFromCollectingLists(); |
| 3779 |
|
| 3780 |
// Merge sized alloc data structures back without sweeping them. |
| 3781 |
zone->bufferAllocator.finishMajorCollection(lock); |
| 3782 |
} |
| 3783 |
} |
| 3784 |
|
| 3785 |
{ |
| 3786 |
AutoLockHelperThreadState lock; |
| 3787 |
lifoBlocksToFree.ref().freeAll(); |
| 3788 |
} |
| 3789 |
|
| 3790 |
lastMarkSlice = false; |
| 3791 |
incrementalState = State::Finish; |
| 3792 |
|
| 3793 |
#ifdef DEBUG |
| 3794 |
for (auto& marker : markers) { |
| 3795 |
MOZ_ASSERT(!marker->shouldCheckCompartments()); |
| 3796 |
} |
| 3797 |
#endif |
| 3798 |
|
| 3799 |
break; |
| 3800 |
} |
| 3801 |
|
| 3802 |
case State::Sweep: { |
| 3803 |
// Finish sweeping the current sweep group, then abort. |
| 3804 |
for (CompartmentsIter c(rt); !c.done(); c.next()) { |
| 3805 |
c->gcState.scheduledForDestruction = false; |
| 3806 |
} |
| 3807 |
|
| 3808 |
abortSweepAfterCurrentGroup = true; |
| 3809 |
isCompacting = false; |
| 3810 |
|
| 3811 |
break; |
| 3812 |
} |
| 3813 |
|
| 3814 |
case State::Finalize: { |
| 3815 |
isCompacting = false; |
| 3816 |
break; |
| 3817 |
} |
| 3818 |
|
| 3819 |
case State::Compact: { |
| 3820 |
// Skip any remaining zones that would have been compacted. |
| 3821 |
MOZ_ASSERT(isCompacting); |
| 3822 |
startedCompacting = true; |
| 3823 |
zonesToMaybeCompact.ref().clear(); |
| 3824 |
break; |
| 3825 |
} |
| 3826 |
|
| 3827 |
case State::Decommit: { |
| 3828 |
break; |
| 3829 |
} |
| 3830 |
} |
| 3831 |
|
| 3832 |
stats().reset(reason); |
| 3833 |
|
| 3834 |
if (reason == GCAbortReason::AbortRequested) { |
| 3835 |
return IncrementalResult::Abort; |
| 3836 |
} |
| 3837 |
|
| 3838 |
return IncrementalResult::Reset; |
| 3839 |
} |
| 3840 |
|
| 3841 |
AutoDisableBarriers::AutoDisableBarriers(GCRuntime* gc) : gc(gc) { |
| 3842 |
/* |
| 3843 |
* Clear needsIncrementalBarrier early so we don't do any write barriers |
| 3844 |
* during sweeping. |
| 3845 |
*/ |
| 3846 |
for (GCZonesIter zone(gc); !zone.done(); zone.next()) { |
| 3847 |
if (zone->isGCMarking()) { |
| 3848 |
MOZ_ASSERT(zone->needsIncrementalBarrier()); |
| 3849 |
zone->setNeedsIncrementalBarrier(false); |
| 3850 |
} |
| 3851 |
MOZ_ASSERT(!zone->needsIncrementalBarrier()); |
| 3852 |
} |
| 3853 |
} |
| 3854 |
|
| 3855 |
AutoDisableBarriers::~AutoDisableBarriers() { |
| 3856 |
for (GCZonesIter zone(gc); !zone.done(); zone.next()) { |
| 3857 |
MOZ_ASSERT(!zone->needsIncrementalBarrier()); |
| 3858 |
if (zone->isGCMarking()) { |
| 3859 |
zone->setNeedsIncrementalBarrier(true); |
| 3860 |
} |
| 3861 |
} |
| 3862 |
} |
| 3863 |
|
| 3864 |
static bool NeedToCollectNursery(GCRuntime* gc) { |
| 3865 |
return !gc->nursery().isEmpty() || !gc->storeBuffer().isEmpty(); |
| 3866 |
} |
| 3867 |
|
| 3868 |
#ifdef DEBUG |
| 3869 |
static const char* DescribeBudget(const SliceBudget& budget) { |
| 3870 |
constexpr size_t length = 32; |
| 3871 |
static char buffer[length]; |
| 3872 |
budget.describe(buffer, length); |
| 3873 |
return buffer; |
| 3874 |
} |
| 3875 |
#endif |
| 3876 |
|
| 3877 |
static bool ShouldPauseMutatorWhileWaiting(const SliceBudget& budget, |
| 3878 |
JS::GCReason reason, |
| 3879 |
bool budgetWasIncreased) { |
| 3880 |
// When we're nearing the incremental limit at which we will finish the |
| 3881 |
// collection synchronously, pause the main thread if there is only background |
| 3882 |
// GC work happening. This allows the GC to catch up and avoid hitting the |
| 3883 |
// limit. |
| 3884 |
return budget.isTimeBudget() && |
| 3885 |
(reason == JS::GCReason::ALLOC_TRIGGER || |
| 3886 |
reason == JS::GCReason::TOO_MUCH_MALLOC) && |
| 3887 |
budgetWasIncreased; |
| 3888 |
} |
| 3889 |
|
| 3890 |
void GCRuntime::incrementalSlice(SliceBudget& budget, JS::GCReason reason, |
| 3891 |
bool budgetWasIncreased) { |
| 3892 |
MOZ_ASSERT_IF(isIncrementalGCInProgress(), isIncremental); |
| 3893 |
|
| 3894 |
AutoSetThreadIsPerformingGC performingGC(rt->gcContext()); |
| 3895 |
|
| 3896 |
AutoGCSession session(this, JS::HeapState::MajorCollecting); |
| 3897 |
|
| 3898 |
bool destroyingRuntime = (reason == JS::GCReason::DESTROY_RUNTIME); |
| 3899 |
|
| 3900 |
initialState = incrementalState; |
| 3901 |
isIncremental = !budget.isUnlimited(); |
| 3902 |
useBackgroundThreads = ShouldUseBackgroundThreads(isIncremental, reason); |
| 3903 |
|
| 3904 |
#ifdef JS_GC_ZEAL |
| 3905 |
// Do the incremental collection type specified by zeal mode if the collection |
| 3906 |
// was triggered by runDebugGC() and incremental GC has not been cancelled by |
| 3907 |
// resetIncrementalGC(). |
| 3908 |
useZeal = isIncremental && reason == JS::GCReason::DEBUG_GC; |
| 3909 |
#endif |
| 3910 |
|
| 3911 |
#ifdef DEBUG |
| 3912 |
stats().log( |
| 3913 |
"Incremental: %d, lastMarkSlice: %d, useZeal: %d, budget: %s, " |
| 3914 |
"budgetWasIncreased: %d", |
| 3915 |
bool(isIncremental), bool(lastMarkSlice), bool(useZeal), |
| 3916 |
DescribeBudget(budget), budgetWasIncreased); |
| 3917 |
#endif |
| 3918 |
|
| 3919 |
if (useZeal && zealModeControlsYieldPoint()) { |
| 3920 |
// Yields between slices occurs at predetermined points in these modes; the |
| 3921 |
// budget is not used. |isIncremental| is still true. |
| 3922 |
stats().log("Using unlimited budget for two-slice zeal mode"); |
| 3923 |
budget = SliceBudget::unlimited(); |
| 3924 |
} |
| 3925 |
|
| 3926 |
bool shouldPauseMutator = |
| 3927 |
ShouldPauseMutatorWhileWaiting(budget, reason, budgetWasIncreased); |
| 3928 |
|
| 3929 |
switch (incrementalState) { |
| 3930 |
case State::NotActive: |
| 3931 |
startCollection(reason); |
| 3932 |
|
| 3933 |
incrementalState = State::Prepare; |
| 3934 |
if (!beginPreparePhase(reason, session)) { |
| 3935 |
incrementalState = State::NotActive; |
| 3936 |
break; |
| 3937 |
} |
| 3938 |
|
| 3939 |
if (useZeal && hasZealMode(ZealMode::YieldBeforeRootMarking)) { |
| 3940 |
break; |
| 3941 |
} |
| 3942 |
|
| 3943 |
[[fallthrough]]; |
| 3944 |
|
| 3945 |
case State::Prepare: |
| 3946 |
if (waitForBackgroundTask(unmarkTask, budget, shouldPauseMutator) == |
| 3947 |
NotFinished) { |
| 3948 |
break; |
| 3949 |
} |
| 3950 |
|
| 3951 |
incrementalState = State::MarkRoots; |
| 3952 |
|
| 3953 |
if (isIncremental && initialState == State::Prepare && |
| 3954 |
reason == JS::GCReason::BG_TASK_FINISHED) { |
| 3955 |
// The next slice may be long so wait for the embedding to schedule it |
| 3956 |
// rather than doing it as soon as unmarking finishes. This can happen |
| 3957 |
// when the embedding's GC callback sees this slice end with work |
| 3958 |
// available. |
| 3959 |
MOZ_ASSERT(hasForegroundWork()); |
| 3960 |
break; |
| 3961 |
} |
| 3962 |
|
| 3963 |
[[fallthrough]]; |
| 3964 |
|
| 3965 |
case State::MarkRoots: |
| 3966 |
endPreparePhase(reason); |
| 3967 |
|
| 3968 |
beginMarkPhase(session); |
| 3969 |
incrementalState = State::Mark; |
| 3970 |
|
| 3971 |
if (useZeal && hasZealMode(ZealMode::YieldBeforeMarking) && |
| 3972 |
isIncremental) { |
| 3973 |
break; |
| 3974 |
} |
| 3975 |
|
| 3976 |
[[fallthrough]]; |
| 3977 |
|
| 3978 |
case State::Mark: |
| 3979 |
if (mightSweepInThisSlice(budget.isUnlimited())) { |
| 3980 |
prepareForSweepSlice(reason); |
| 3981 |
|
| 3982 |
// Incremental marking validation re-runs all marking non-incrementally, |
| 3983 |
// which requires collecting the nursery. If that might happen in this |
| 3984 |
// slice, do it now while it's safe to do so. |
| 3985 |
if (isIncremental && |
| 3986 |
hasZealMode(ZealMode::IncrementalMarkingValidator)) { |
| 3987 |
collectNurseryFromMajorGC(JS::GCReason::EVICT_NURSERY); |
| 3988 |
} |
| 3989 |
} |
| 3990 |
|
| 3991 |
{ |
| 3992 |
gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::MARK); |
| 3993 |
if (markUntilBudgetExhausted(budget, useParallelMarking) == |
| 3994 |
NotFinished) { |
| 3995 |
break; |
| 3996 |
} |
| 3997 |
} |
| 3998 |
|
| 3999 |
assertNoMarkingWork(); |
| 4000 |
|
| 4001 |
/* |
| 4002 |
* There are a number of reasons why we break out of collection here, |
| 4003 |
* either ending the slice or to run a new interation of the loop in |
| 4004 |
* GCRuntime::collect() |
| 4005 |
*/ |
| 4006 |
|
| 4007 |
/* |
| 4008 |
* In incremental GCs where we have already performed more than one |
| 4009 |
* slice we yield after marking with the aim of starting the sweep in |
| 4010 |
* the next slice, since the first slice of sweeping can be expensive. |
| 4011 |
* |
| 4012 |
* This is modified by the various zeal modes. We don't yield in |
| 4013 |
* YieldBeforeMarking mode and we always yield in YieldBeforeSweeping |
| 4014 |
* mode. |
| 4015 |
* |
| 4016 |
* We will need to mark anything new on the stack when we resume, so |
| 4017 |
* we stay in Mark state. |
| 4018 |
*/ |
| 4019 |
if (isIncremental && !lastMarkSlice) { |
| 4020 |
if ((initialState == State::Mark && |
| 4021 |
!(useZeal && hasZealMode(ZealMode::YieldBeforeMarking))) || |
| 4022 |
(useZeal && hasZealMode(ZealMode::YieldBeforeSweeping))) { |
| 4023 |
lastMarkSlice = true; |
| 4024 |
stats().log("Yielding before starting sweeping"); |
| 4025 |
break; |
| 4026 |
} |
| 4027 |
} |
| 4028 |
|
| 4029 |
incrementalState = State::Sweep; |
| 4030 |
lastMarkSlice = false; |
| 4031 |
|
| 4032 |
beginSweepPhase(reason, session); |
| 4033 |
|
| 4034 |
[[fallthrough]]; |
| 4035 |
|
| 4036 |
case State::Sweep: |
| 4037 |
if (initialState == State::Sweep) { |
| 4038 |
prepareForSweepSlice(reason); |
| 4039 |
} |
| 4040 |
|
| 4041 |
if (performSweepActions(budget) == NotFinished) { |
| 4042 |
break; |
| 4043 |
} |
| 4044 |
|
| 4045 |
endSweepPhase(destroyingRuntime); |
| 4046 |
|
| 4047 |
incrementalState = State::Finalize; |
| 4048 |
|
| 4049 |
[[fallthrough]]; |
| 4050 |
|
| 4051 |
case State::Finalize: |
| 4052 |
if (waitForBackgroundTask(sweepTask, budget, shouldPauseMutator) == |
| 4053 |
NotFinished) { |
| 4054 |
break; |
| 4055 |
} |
| 4056 |
|
| 4057 |
for (GCZonesIter zone(this); !zone.done(); zone.next()) { |
| 4058 |
zone->arenas.mergeBackgroundSweptArenas(); |
| 4059 |
} |
| 4060 |
|
| 4061 |
{ |
| 4062 |
BufferAllocator::AutoLock lock(this); |
| 4063 |
for (GCZonesIter zone(this); !zone.done(); zone.next()) { |
| 4064 |
zone->bufferAllocator.finishMajorCollection(lock); |
| 4065 |
} |
| 4066 |
} |
| 4067 |
|
| 4068 |
atomMarking.mergePendingFreeArenaIndexes(this); |
| 4069 |
|
| 4070 |
{ |
| 4071 |
AutoLockGC lock(this); |
| 4072 |
clearCurrentChunk(lock); |
| 4073 |
} |
| 4074 |
|
| 4075 |
assertBackgroundSweepingFinished(); |
| 4076 |
|
| 4077 |
// Ensure freeing of nursery owned sized allocations from the initial |
| 4078 |
// minor GC has finished. |
| 4079 |
MOZ_ASSERT(minorGCNumber >= initialMinorGCNumber); |
| 4080 |
if (minorGCNumber == initialMinorGCNumber) { |
| 4081 |
MOZ_ASSERT(nursery().sweepTaskIsIdle()); |
| 4082 |
} |
| 4083 |
|
| 4084 |
{ |
| 4085 |
// Sweep the zones list now that background finalization is finished to |
| 4086 |
// remove and free dead zones, compartments and realms. |
| 4087 |
gcstats::AutoPhase ap1(stats(), gcstats::PhaseKind::SWEEP); |
| 4088 |
gcstats::AutoPhase ap2(stats(), gcstats::PhaseKind::DESTROY); |
| 4089 |
sweepZones(rt->gcContext(), destroyingRuntime); |
| 4090 |
} |
| 4091 |
|
| 4092 |
MOZ_ASSERT(!startedCompacting); |
| 4093 |
incrementalState = State::Compact; |
| 4094 |
|
| 4095 |
// Always yield before compacting since it is not incremental. |
| 4096 |
if (isCompacting && !budget.isUnlimited()) { |
| 4097 |
break; |
| 4098 |
} |
| 4099 |
|
| 4100 |
[[fallthrough]]; |
| 4101 |
|
| 4102 |
case State::Compact: |
| 4103 |
if (isCompacting) { |
| 4104 |
if (NeedToCollectNursery(this)) { |
| 4105 |
collectNurseryFromMajorGC(reason); |
| 4106 |
} |
| 4107 |
|
| 4108 |
storeBuffer().checkEmpty(); |
| 4109 |
if (!startedCompacting) { |
| 4110 |
beginCompactPhase(); |
| 4111 |
} |
| 4112 |
|
| 4113 |
nursery().joinSweepTask(); |
| 4114 |
if (compactPhase(reason, budget, session) == NotFinished) { |
| 4115 |
break; |
| 4116 |
} |
| 4117 |
|
| 4118 |
endCompactPhase(); |
| 4119 |
} |
| 4120 |
|
| 4121 |
startDecommit(); |
| 4122 |
incrementalState = State::Decommit; |
| 4123 |
|
| 4124 |
[[fallthrough]]; |
| 4125 |
|
| 4126 |
case State::Decommit: |
| 4127 |
if (waitForBackgroundTask(decommitTask, budget, shouldPauseMutator) == |
| 4128 |
NotFinished) { |
| 4129 |
break; |
| 4130 |
} |
| 4131 |
|
| 4132 |
incrementalState = State::Finish; |
| 4133 |
|
| 4134 |
[[fallthrough]]; |
| 4135 |
|
| 4136 |
case State::Finish: |
| 4137 |
finishCollection(reason); |
| 4138 |
incrementalState = State::NotActive; |
| 4139 |
break; |
| 4140 |
} |
| 4141 |
|
| 4142 |
#ifdef DEBUG |
| 4143 |
MOZ_ASSERT(safeToYield); |
| 4144 |
for (auto& marker : markers) { |
| 4145 |
MOZ_ASSERT(marker->markColor() == MarkColor::Black); |
| 4146 |
} |
| 4147 |
MOZ_ASSERT(!rt->gcContext()->hasJitCodeToPoison()); |
| 4148 |
#endif |
| 4149 |
} |
| 4150 |
|
| 4151 |
void GCRuntime::collectNurseryFromMajorGC(JS::GCReason reason) { |
| 4152 |
collectNursery(gcOptions(), JS::GCReason::EVICT_NURSERY, |
| 4153 |
gcstats::PhaseKind::EVICT_NURSERY_FOR_MAJOR_GC); |
| 4154 |
|
| 4155 |
MOZ_ASSERT(nursery().isEmpty()); |
| 4156 |
MOZ_ASSERT(storeBuffer().isEmpty()); |
| 4157 |
} |
| 4158 |
|
| 4159 |
bool GCRuntime::hasForegroundWork() const { |
| 4160 |
switch (incrementalState) { |
| 4161 |
case State::NotActive: |
| 4162 |
// Incremental GC is not running and no work is pending. |
| 4163 |
return false; |
| 4164 |
case State::Prepare: |
| 4165 |
// We yield in the Prepare state after starting unmarking. |
| 4166 |
return !unmarkTask.wasStarted(); |
| 4167 |
case State::Finalize: |
| 4168 |
// We yield in the Finalize state to wait for background sweeping. |
| 4169 |
return !isBackgroundSweeping(); |
| 4170 |
case State::Decommit: |
| 4171 |
// We yield in the Decommit state to wait for background decommit. |
| 4172 |
return !decommitTask.wasStarted(); |
| 4173 |
default: |
| 4174 |
// In all other states there is still work to do. |
| 4175 |
return true; |
| 4176 |
} |
| 4177 |
} |
| 4178 |
|
| 4179 |
IncrementalProgress GCRuntime::waitForBackgroundTask(GCParallelTask& task, |
| 4180 |
const SliceBudget& budget, |
| 4181 |
bool shouldPauseMutator) { |
| 4182 |
// Wait here in non-incremental collections, or if we want to pause the |
| 4183 |
// mutator to let the GC catch up. |
| 4184 |
if (budget.isUnlimited() || shouldPauseMutator) { |
| 4185 |
gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::WAIT_BACKGROUND_THREAD); |
| 4186 |
Maybe<TimeStamp> deadline; |
| 4187 |
if (budget.isTimeBudget()) { |
| 4188 |
deadline.emplace(budget.deadline()); |
| 4189 |
} |
| 4190 |
task.join(deadline); |
| 4191 |
} |
| 4192 |
|
| 4193 |
// In incremental collections, yield if the task has not finished and request |
| 4194 |
// a slice to notify us when this happens. |
| 4195 |
if (!budget.isUnlimited()) { |
| 4196 |
AutoLockHelperThreadState lock; |
| 4197 |
if (task.wasStarted(lock)) { |
| 4198 |
requestSliceAfterBackgroundTask = true; |
| 4199 |
return NotFinished; |
| 4200 |
} |
| 4201 |
|
| 4202 |
task.joinWithLockHeld(lock); |
| 4203 |
} |
| 4204 |
|
| 4205 |
MOZ_ASSERT(task.isIdle()); |
| 4206 |
|
| 4207 |
cancelRequestedGCAfterBackgroundTask(); |
| 4208 |
|
| 4209 |
return Finished; |
| 4210 |
} |
| 4211 |
|
| 4212 |
inline void GCRuntime::checkZoneIsScheduled(Zone* zone, JS::GCReason reason, |
| 4213 |
const char* trigger) { |
| 4214 |
#ifdef DEBUG |
| 4215 |
if (zone->isGCScheduled()) { |
| 4216 |
return; |
| 4217 |
} |
| 4218 |
|
| 4219 |
fprintf(stderr, |
| 4220 |
"checkZoneIsScheduled: Zone %p not scheduled as expected in %s GC " |
| 4221 |
"for %s trigger\n", |
| 4222 |
zone, JS::ExplainGCReason(reason), trigger); |
| 4223 |
for (ZonesIter zone(this, WithAtoms); !zone.done(); zone.next()) { |
| 4224 |
fprintf(stderr, " Zone %p:%s%s\n", zone.get(), |
| 4225 |
zone->isAtomsZone() ? " atoms" : "", |
| 4226 |
zone->isGCScheduled() ? " scheduled" : ""); |
| 4227 |
} |
| 4228 |
fflush(stderr); |
| 4229 |
MOZ_CRASH("Zone not scheduled"); |
| 4230 |
#endif |
| 4231 |
} |
| 4232 |
|
| 4233 |
GCRuntime::IncrementalResult GCRuntime::budgetIncrementalGC( |
| 4234 |
bool nonincrementalByAPI, JS::GCReason reason, SliceBudget& budget) { |
| 4235 |
if (nonincrementalByAPI) { |
| 4236 |
stats().nonincremental(GCAbortReason::NonIncrementalRequested); |
| 4237 |
budget = SliceBudget::unlimited(); |
| 4238 |
|
| 4239 |
// Reset any in progress incremental GC if this was triggered via the |
| 4240 |
// API. This isn't required for correctness, but sometimes during tests |
| 4241 |
// the caller expects this GC to collect certain objects, and we need |
| 4242 |
// to make sure to collect everything possible. |
| 4243 |
if (reason != JS::GCReason::ALLOC_TRIGGER) { |
| 4244 |
return resetIncrementalGC(GCAbortReason::NonIncrementalRequested); |
| 4245 |
} |
| 4246 |
|
| 4247 |
return IncrementalResult::Ok; |
| 4248 |
} |
| 4249 |
|
| 4250 |
if (reason == JS::GCReason::ABORT_GC) { |
| 4251 |
budget = SliceBudget::unlimited(); |
| 4252 |
stats().nonincremental(GCAbortReason::AbortRequested); |
| 4253 |
return resetIncrementalGC(GCAbortReason::AbortRequested); |
| 4254 |
} |
| 4255 |
|
| 4256 |
if (!budget.isUnlimited()) { |
| 4257 |
GCAbortReason unsafeReason = GCAbortReason::None; |
| 4258 |
if (reason == JS::GCReason::COMPARTMENT_REVIVED) { |
| 4259 |
unsafeReason = GCAbortReason::CompartmentRevived; |
| 4260 |
} else if (!incrementalGCEnabled) { |
| 4261 |
unsafeReason = GCAbortReason::ModeChange; |
| 4262 |
} |
| 4263 |
|
| 4264 |
if (unsafeReason != GCAbortReason::None) { |
| 4265 |
budget = SliceBudget::unlimited(); |
| 4266 |
stats().nonincremental(unsafeReason); |
| 4267 |
return resetIncrementalGC(unsafeReason); |
| 4268 |
} |
| 4269 |
} |
| 4270 |
|
| 4271 |
GCAbortReason resetReason = GCAbortReason::None; |
| 4272 |
for (ZonesIter zone(this, WithAtoms); !zone.done(); zone.next()) { |
| 4273 |
if (zone->gcHeapSize.bytes() >= |
| 4274 |
zone->gcHeapThreshold.incrementalLimitBytes()) { |
| 4275 |
checkZoneIsScheduled(zone, reason, "GC bytes"); |
| 4276 |
budget = SliceBudget::unlimited(); |
| 4277 |
stats().nonincremental(GCAbortReason::GCBytesTrigger); |
| 4278 |
if (zone->wasGCStarted() && zone->gcState() > Zone::Sweep) { |
| 4279 |
resetReason = GCAbortReason::GCBytesTrigger; |
| 4280 |
} |
| 4281 |
} |
| 4282 |
|
| 4283 |
if (zone->mallocHeapSize.bytes() >= |
| 4284 |
zone->mallocHeapThreshold.incrementalLimitBytes()) { |
| 4285 |
checkZoneIsScheduled(zone, reason, "malloc bytes"); |
| 4286 |
budget = SliceBudget::unlimited(); |
| 4287 |
stats().nonincremental(GCAbortReason::MallocBytesTrigger); |
| 4288 |
if (zone->wasGCStarted() && zone->gcState() > Zone::Sweep) { |
| 4289 |
resetReason = GCAbortReason::MallocBytesTrigger; |
| 4290 |
} |
| 4291 |
} |
| 4292 |
|
| 4293 |
if (zone->jitHeapSize.bytes() >= |
| 4294 |
zone->jitHeapThreshold.incrementalLimitBytes()) { |
| 4295 |
checkZoneIsScheduled(zone, reason, "JIT code bytes"); |
| 4296 |
budget = SliceBudget::unlimited(); |
| 4297 |
stats().nonincremental(GCAbortReason::JitCodeBytesTrigger); |
| 4298 |
if (zone->wasGCStarted() && zone->gcState() > Zone::Sweep) { |
| 4299 |
resetReason = GCAbortReason::JitCodeBytesTrigger; |
| 4300 |
} |
| 4301 |
} |
| 4302 |
|
| 4303 |
if (isIncrementalGCInProgress() && |
| 4304 |
zone->isGCScheduled() != zone->wasGCStarted()) { |
| 4305 |
budget = SliceBudget::unlimited(); |
| 4306 |
resetReason = GCAbortReason::ZoneChange; |
| 4307 |
} |
| 4308 |
} |
| 4309 |
|
| 4310 |
if (resetReason != GCAbortReason::None) { |
| 4311 |
return resetIncrementalGC(resetReason); |
| 4312 |
} |
| 4313 |
|
| 4314 |
return IncrementalResult::Ok; |
| 4315 |
} |
| 4316 |
|
| 4317 |
bool GCRuntime::maybeIncreaseSliceBudget(SliceBudget& budget, |
| 4318 |
TimeStamp sliceStartTime, |
| 4319 |
TimeStamp gcStartTime) { |
| 4320 |
if (js::SupportDifferentialTesting()) { |
| 4321 |
return false; |
| 4322 |
} |
| 4323 |
|
| 4324 |
if (!budget.isTimeBudget() || !isIncrementalGCInProgress()) { |
| 4325 |
return false; |
| 4326 |
} |
| 4327 |
|
| 4328 |
bool wasIncreasedForLongCollections = |
| 4329 |
maybeIncreaseSliceBudgetForLongCollections(budget, sliceStartTime, |
| 4330 |
gcStartTime); |
| 4331 |
bool wasIncreasedForUgentCollections = |
| 4332 |
maybeIncreaseSliceBudgetForUrgentCollections(budget); |
| 4333 |
|
| 4334 |
return wasIncreasedForLongCollections || wasIncreasedForUgentCollections; |
| 4335 |
} |
| 4336 |
|
| 4337 |
// Return true if the budget is actually extended after rounding. |
| 4338 |
static bool ExtendBudget(SliceBudget& budget, double newDuration) { |
| 4339 |
long millis = lround(newDuration); |
| 4340 |
if (millis <= budget.timeBudget()) { |
| 4341 |
return false; |
| 4342 |
} |
| 4343 |
|
| 4344 |
bool idleTriggered = budget.idle; |
| 4345 |
budget = SliceBudget(TimeBudget(millis), nullptr); // Uninterruptible. |
| 4346 |
budget.idle = idleTriggered; |
| 4347 |
budget.extended = true; |
| 4348 |
return true; |
| 4349 |
} |
| 4350 |
|
| 4351 |
bool GCRuntime::maybeIncreaseSliceBudgetForLongCollections( |
| 4352 |
SliceBudget& budget, TimeStamp sliceStartTime, TimeStamp gcStartTime) { |
| 4353 |
// For long-running collections, enforce a minimum time budget that increases |
| 4354 |
// linearly with time up to a maximum. |
| 4355 |
|
| 4356 |
// All times are in milliseconds. |
| 4357 |
struct BudgetAtTime { |
| 4358 |
double time; |
| 4359 |
double budget; |
| 4360 |
}; |
| 4361 |
const BudgetAtTime MinBudgetStart{1500, 0.0}; |
| 4362 |
const BudgetAtTime MinBudgetEnd{2500, 100.0}; |
| 4363 |
|
| 4364 |
double totalTime = (sliceStartTime - gcStartTime).ToMilliseconds(); |
| 4365 |
|
| 4366 |
double minBudget = |
| 4367 |
LinearInterpolate(totalTime, MinBudgetStart.time, MinBudgetStart.budget, |
| 4368 |
MinBudgetEnd.time, MinBudgetEnd.budget); |
| 4369 |
|
| 4370 |
return ExtendBudget(budget, minBudget); |
| 4371 |
} |
| 4372 |
|
| 4373 |
bool GCRuntime::maybeIncreaseSliceBudgetForUrgentCollections( |
| 4374 |
SliceBudget& budget) { |
| 4375 |
// Enforce a minimum time budget based on how close we are to the incremental |
| 4376 |
// limit. |
| 4377 |
|
| 4378 |
size_t minBytesRemaining = SIZE_MAX; |
| 4379 |
for (AllZonesIter zone(this); !zone.done(); zone.next()) { |
| 4380 |
if (!zone->wasGCStarted()) { |
| 4381 |
continue; |
| 4382 |
} |
| 4383 |
size_t gcBytesRemaining = |
| 4384 |
zone->gcHeapThreshold.incrementalBytesRemaining(zone->gcHeapSize); |
| 4385 |
minBytesRemaining = std::min(minBytesRemaining, gcBytesRemaining); |
| 4386 |
size_t mallocBytesRemaining = |
| 4387 |
zone->mallocHeapThreshold.incrementalBytesRemaining( |
| 4388 |
zone->mallocHeapSize); |
| 4389 |
minBytesRemaining = std::min(minBytesRemaining, mallocBytesRemaining); |
| 4390 |
} |
| 4391 |
|
| 4392 |
if (minBytesRemaining < tunables.urgentThresholdBytes() && |
| 4393 |
minBytesRemaining != 0) { |
| 4394 |
// Increase budget based on the reciprocal of the fraction remaining. |
| 4395 |
double fractionRemaining = |
| 4396 |
double(minBytesRemaining) / double(tunables.urgentThresholdBytes()); |
| 4397 |
double minBudget = double(defaultSliceBudgetMS()) / fractionRemaining; |
| 4398 |
return ExtendBudget(budget, minBudget); |
| 4399 |
} |
| 4400 |
|
| 4401 |
return false; |
| 4402 |
} |
| 4403 |
|
| 4404 |
static void ScheduleZones(GCRuntime* gc, JS::GCReason reason) { |
| 4405 |
for (ZonesIter zone(gc, WithAtoms); !zone.done(); zone.next()) { |
| 4406 |
// Re-check heap threshold for alloc-triggered zones that were not |
| 4407 |
// previously collected. Now we have allocation rate data, the heap limit |
| 4408 |
// may have been increased beyond the current size. |
| 4409 |
if (gc->tunables.balancedHeapLimitsEnabled() && zone->isGCScheduled() && |
| 4410 |
zone->smoothedCollectionRate.ref().isNothing() && |
| 4411 |
reason == JS::GCReason::ALLOC_TRIGGER && |
| 4412 |
zone->gcHeapSize.bytes() < zone->gcHeapThreshold.startBytes()) { |
| 4413 |
zone->unscheduleGC(); // May still be re-scheduled below. |
| 4414 |
} |
| 4415 |
|
| 4416 |
if (gc->isShutdownGC()) { |
| 4417 |
zone->scheduleGC(); |
| 4418 |
} |
| 4419 |
|
| 4420 |
if (!gc->isPerZoneGCEnabled()) { |
| 4421 |
zone->scheduleGC(); |
| 4422 |
} |
| 4423 |
|
| 4424 |
// To avoid resets, continue to collect any zones that were being |
| 4425 |
// collected in a previous slice. |
| 4426 |
if (gc->isIncrementalGCInProgress() && zone->wasGCStarted()) { |
| 4427 |
zone->scheduleGC(); |
| 4428 |
} |
| 4429 |
|
| 4430 |
// This is a heuristic to reduce the total number of collections. |
| 4431 |
bool inHighFrequencyMode = gc->schedulingState.inHighFrequencyGCMode(); |
| 4432 |
if (zone->gcHeapSize.bytes() >= |
| 4433 |
zone->gcHeapThreshold.eagerAllocTrigger(inHighFrequencyMode) || |
| 4434 |
zone->mallocHeapSize.bytes() >= |
| 4435 |
zone->mallocHeapThreshold.eagerAllocTrigger(inHighFrequencyMode) || |
| 4436 |
zone->jitHeapSize.bytes() >= zone->jitHeapThreshold.startBytes()) { |
| 4437 |
zone->scheduleGC(); |
| 4438 |
} |
| 4439 |
} |
| 4440 |
} |
| 4441 |
|
| 4442 |
static void UnscheduleZones(GCRuntime* gc) { |
| 4443 |
for (ZonesIter zone(gc->rt, WithAtoms); !zone.done(); zone.next()) { |
| 4444 |
zone->unscheduleGC(); |
| 4445 |
} |
| 4446 |
} |
| 4447 |
|
| 4448 |
class js::gc::AutoCallGCCallbacks { |
| 4449 |
GCRuntime& gc_; |
| 4450 |
JS::GCReason reason_; |
| 4451 |
|
| 4452 |
public: |
| 4453 |
explicit AutoCallGCCallbacks(GCRuntime& gc, JS::GCReason reason) |
| 4454 |
: gc_(gc), reason_(reason) { |
| 4455 |
gc_.maybeCallGCCallback(JSGC_BEGIN, reason); |
| 4456 |
} |
| 4457 |
~AutoCallGCCallbacks() { gc_.maybeCallGCCallback(JSGC_END, reason_); } |
| 4458 |
}; |
| 4459 |
|
| 4460 |
void GCRuntime::maybeCallGCCallback(JSGCStatus status, JS::GCReason reason) { |
| 4461 |
if (!gcCallback.ref().op) { |
| 4462 |
return; |
| 4463 |
} |
| 4464 |
|
| 4465 |
if (isIncrementalGCInProgress()) { |
| 4466 |
return; |
| 4467 |
} |
| 4468 |
|
| 4469 |
if (gcCallbackDepth == 0) { |
| 4470 |
// Save scheduled zone information in case the callback clears it. |
| 4471 |
for (ZonesIter zone(this, WithAtoms); !zone.done(); zone.next()) { |
| 4472 |
zone->gcScheduledSaved_ = zone->gcScheduled_; |
| 4473 |
} |
| 4474 |
} |
| 4475 |
|
| 4476 |
// Save and clear GC options and state in case the callback reenters GC. |
| 4477 |
JS::GCOptions options = gcOptions(); |
| 4478 |
maybeGcOptions = Nothing(); |
| 4479 |
bool savedFullGCRequested = fullGCRequested; |
| 4480 |
fullGCRequested = false; |
| 4481 |
|
| 4482 |
gcCallbackDepth++; |
| 4483 |
|
| 4484 |
callGCCallback(status, reason); |
| 4485 |
|
| 4486 |
MOZ_ASSERT(gcCallbackDepth != 0); |
| 4487 |
gcCallbackDepth--; |
| 4488 |
|
| 4489 |
// Restore the original GC options. |
| 4490 |
maybeGcOptions = Some(options); |
| 4491 |
|
| 4492 |
// At the end of a GC, clear out the fullGCRequested state. At the start, |
| 4493 |
// restore the previous setting. |
| 4494 |
fullGCRequested = savedFullGCRequested; |
| 4495 |
|
| 4496 |
if (gcCallbackDepth == 0) { |
| 4497 |
// Ensure any zone that was originally scheduled stays scheduled. |
| 4498 |
for (ZonesIter zone(this, WithAtoms); !zone.done(); zone.next()) { |
| 4499 |
zone->gcScheduled_ = zone->gcScheduled_ || zone->gcScheduledSaved_; |
| 4500 |
} |
| 4501 |
} |
| 4502 |
} |
| 4503 |
|
| 4504 |
/* |
| 4505 |
* We disable inlining to ensure that the bottom of the stack with possible GC |
| 4506 |
* roots recorded in MarkRuntime excludes any pointers we use during the marking |
| 4507 |
* implementation. |
| 4508 |
*/ |
| 4509 |
MOZ_NEVER_INLINE GCRuntime::IncrementalResult GCRuntime::gcCycle( |
| 4510 |
bool nonincrementalByAPI, const SliceBudget& budgetArg, |
| 4511 |
JS::GCReason reason) { |
| 4512 |
// Assert if this is a GC unsafe region. |
| 4513 |
rt->mainContextFromOwnThread()->verifyIsSafeToGC(); |
| 4514 |
|
| 4515 |
// It's ok if threads other than the main thread have suppressGC set, as |
| 4516 |
// they are operating on zones which will not be collected from here. |
| 4517 |
MOZ_ASSERT(!rt->mainContextFromOwnThread()->suppressGC); |
| 4518 |
|
| 4519 |
// This reason is used internally. See below. |
| 4520 |
MOZ_ASSERT(reason != JS::GCReason::RESET); |
| 4521 |
|
| 4522 |
// Background finalization and decommit are finished by definition before we |
| 4523 |
// can start a new major GC. Background allocation may still be running, but |
| 4524 |
// that's OK because chunk pools are protected by the GC lock. |
| 4525 |
bool firstSlice = !isIncrementalGCInProgress(); |
| 4526 |
if (firstSlice) { |
| 4527 |
assertBackgroundSweepingFinished(); |
| 4528 |
MOZ_ASSERT(decommitTask.isIdle()); |
| 4529 |
} |
| 4530 |
|
| 4531 |
// Note that GC callbacks are allowed to re-enter GC. |
| 4532 |
AutoCallGCCallbacks callCallbacks(*this, reason); |
| 4533 |
|
| 4534 |
// Reset the fullGCRequested flag at the end of GC. |
| 4535 |
auto resetFullFlag = MakeScopeExit([&] { |
| 4536 |
if (!isIncrementalGCInProgress()) { |
| 4537 |
fullGCRequested = false; |
| 4538 |
} |
| 4539 |
}); |
| 4540 |
|
| 4541 |
// Record GC start time and update global scheduling state. |
| 4542 |
TimeStamp now = TimeStamp::Now(); |
| 4543 |
if (firstSlice) { |
| 4544 |
schedulingState.updateHighFrequencyModeOnGCStart( |
| 4545 |
gcOptions(), lastGCStartTime_, now, tunables); |
| 4546 |
lastGCStartTime_ = now; |
| 4547 |
} |
| 4548 |
schedulingState.updateHighFrequencyModeOnSliceStart(gcOptions(), reason); |
| 4549 |
|
| 4550 |
// Increase slice budget for long running collections before it is recorded by |
| 4551 |
// AutoGCSlice. |
| 4552 |
SliceBudget budget(budgetArg); |
| 4553 |
bool budgetWasIncreased = |
| 4554 |
maybeIncreaseSliceBudget(budget, now, lastGCStartTime_); |
| 4555 |
|
| 4556 |
ScheduleZones(this, reason); |
| 4557 |
|
| 4558 |
auto updateCollectorTime = MakeScopeExit([&] { |
| 4559 |
if (const gcstats::Statistics::SliceData* slice = stats().lastSlice()) { |
| 4560 |
collectorTimeSinceAllocRateUpdate += slice->duration(); |
| 4561 |
} |
| 4562 |
}); |
| 4563 |
|
| 4564 |
gcstats::AutoGCSlice agc(stats(), scanZonesBeforeGC(), gcOptions(), budget, |
| 4565 |
reason, budgetWasIncreased); |
| 4566 |
|
| 4567 |
IncrementalResult result = |
| 4568 |
budgetIncrementalGC(nonincrementalByAPI, reason, budget); |
| 4569 |
if (result != IncrementalResult::Ok && incrementalState == State::NotActive) { |
| 4570 |
// The collection was reset or aborted and has finished. |
| 4571 |
return result; |
| 4572 |
} |
| 4573 |
|
| 4574 |
if (result == IncrementalResult::Reset) { |
| 4575 |
// The collection was reset but we must finish up some remaining work. This |
| 4576 |
// happens with the reset reason, after which a new collection will be |
| 4577 |
// started. |
| 4578 |
reason = JS::GCReason::RESET; |
| 4579 |
} |
| 4580 |
|
| 4581 |
majorGCTriggerReason = JS::GCReason::NO_REASON; |
| 4582 |
MOZ_ASSERT(!stats().hasTrigger()); |
| 4583 |
|
| 4584 |
incGcNumber(); |
| 4585 |
incGcSliceNumber(); |
| 4586 |
|
| 4587 |
gcprobes::MajorGCStart(); |
| 4588 |
incrementalSlice(budget, reason, budgetWasIncreased); |
| 4589 |
gcprobes::MajorGCEnd(); |
| 4590 |
|
| 4591 |
MOZ_ASSERT_IF(result == IncrementalResult::Reset, |
| 4592 |
!isIncrementalGCInProgress()); |
| 4593 |
return result; |
| 4594 |
} |
| 4595 |
|
| 4596 |
inline bool GCRuntime::mightSweepInThisSlice(bool nonIncremental) { |
| 4597 |
MOZ_ASSERT(incrementalState < State::Sweep); |
| 4598 |
return nonIncremental || lastMarkSlice || zealModeControlsYieldPoint(); |
| 4599 |
} |
| 4600 |
|
| 4601 |
#ifdef JS_GC_ZEAL |
| 4602 |
static bool IsDeterministicGCReason(JS::GCReason reason) { |
| 4603 |
switch (reason) { |
| 4604 |
case JS::GCReason::API: |
| 4605 |
case JS::GCReason::DESTROY_RUNTIME: |
| 4606 |
case JS::GCReason::LAST_DITCH: |
| 4607 |
case JS::GCReason::TOO_MUCH_MALLOC: |
| 4608 |
case JS::GCReason::TOO_MUCH_WASM_MEMORY: |
| 4609 |
case JS::GCReason::TOO_MUCH_JIT_CODE: |
| 4610 |
case JS::GCReason::ALLOC_TRIGGER: |
| 4611 |
case JS::GCReason::DEBUG_GC: |
| 4612 |
case JS::GCReason::CC_FORCED: |
| 4613 |
case JS::GCReason::SHUTDOWN_CC: |
| 4614 |
case JS::GCReason::ABORT_GC: |
| 4615 |
case JS::GCReason::DISABLE_GENERATIONAL_GC: |
| 4616 |
case JS::GCReason::FINISH_GC: |
| 4617 |
case JS::GCReason::PREPARE_FOR_TRACING: |
| 4618 |
return true; |
| 4619 |
|
| 4620 |
default: |
| 4621 |
return false; |
| 4622 |
} |
| 4623 |
} |
| 4624 |
#endif |
| 4625 |
|
| 4626 |
gcstats::ZoneGCStats GCRuntime::scanZonesBeforeGC() { |
| 4627 |
gcstats::ZoneGCStats zoneStats; |
| 4628 |
for (ZonesIter zone(this, WithAtoms); !zone.done(); zone.next()) { |
| 4629 |
zoneStats.zoneCount++; |
| 4630 |
zoneStats.compartmentCount += zone->compartments().length(); |
| 4631 |
for (CompartmentsInZoneIter comp(zone); !comp.done(); comp.next()) { |
| 4632 |
zoneStats.realmCount += comp->realms().length(); |
| 4633 |
} |
| 4634 |
if (zone->isGCScheduled()) { |
| 4635 |
zoneStats.collectedZoneCount++; |
| 4636 |
zoneStats.collectedCompartmentCount += zone->compartments().length(); |
| 4637 |
} |
| 4638 |
} |
| 4639 |
|
| 4640 |
return zoneStats; |
| 4641 |
} |
| 4642 |
|
| 4643 |
// The GC can only clean up scheduledForDestruction realms that were marked live |
| 4644 |
// by a barrier (e.g. by RemapWrappers from a navigation event). It is also |
| 4645 |
// common to have realms held live because they are part of a cycle in gecko, |
| 4646 |
// e.g. involving the HTMLDocument wrapper. In this case, we need to run the |
| 4647 |
// CycleCollector in order to remove these edges before the realm can be freed. |
| 4648 |
void GCRuntime::maybeDoCycleCollection() { |
| 4649 |
const static float ExcessiveGrayRealms = 0.8f; |
| 4650 |
const static size_t LimitGrayRealms = 200; |
| 4651 |
|
| 4652 |
size_t realmsTotal = 0; |
| 4653 |
size_t realmsGray = 0; |
| 4654 |
for (RealmsIter realm(rt); !realm.done(); realm.next()) { |
| 4655 |
++realmsTotal; |
| 4656 |
GlobalObject* global = realm->unsafeUnbarrieredMaybeGlobal(); |
| 4657 |
if (global && global->isMarkedGray()) { |
| 4658 |
++realmsGray; |
| 4659 |
} |
| 4660 |
} |
| 4661 |
float grayFraction = float(realmsGray) / float(realmsTotal); |
| 4662 |
if (grayFraction > ExcessiveGrayRealms || realmsGray > LimitGrayRealms) { |
| 4663 |
callDoCycleCollectionCallback(rt->mainContextFromOwnThread()); |
| 4664 |
} |
| 4665 |
} |
| 4666 |
|
| 4667 |
void GCRuntime::checkCanCallAPI() { |
| 4668 |
MOZ_RELEASE_ASSERT(CurrentThreadCanAccessRuntime(rt)); |
| 4669 |
|
| 4670 |
/* If we attempt to invoke the GC while we are running in the GC, assert. */ |
| 4671 |
MOZ_RELEASE_ASSERT(!JS::RuntimeHeapIsBusy()); |
| 4672 |
} |
| 4673 |
|
| 4674 |
bool GCRuntime::checkIfGCAllowedInCurrentState(JS::GCReason reason) { |
| 4675 |
if (rt->mainContextFromOwnThread()->suppressGC) { |
| 4676 |
return false; |
| 4677 |
} |
| 4678 |
|
| 4679 |
// Only allow shutdown GCs when we're destroying the runtime. This keeps |
| 4680 |
// the GC callback from triggering a nested GC and resetting global state. |
| 4681 |
if (rt->isBeingDestroyed() && !isShutdownGC()) { |
| 4682 |
return false; |
| 4683 |
} |
| 4684 |
|
| 4685 |
#ifdef JS_GC_ZEAL |
| 4686 |
if (deterministicOnly && !IsDeterministicGCReason(reason)) { |
| 4687 |
return false; |
| 4688 |
} |
| 4689 |
#endif |
| 4690 |
|
| 4691 |
return true; |
| 4692 |
} |
| 4693 |
|
| 4694 |
bool GCRuntime::shouldRepeatForDeadZone(JS::GCReason reason) { |
| 4695 |
MOZ_ASSERT_IF(reason == JS::GCReason::COMPARTMENT_REVIVED, !isIncremental); |
| 4696 |
MOZ_ASSERT(!isIncrementalGCInProgress()); |
| 4697 |
|
| 4698 |
if (!isIncremental) { |
| 4699 |
return false; |
| 4700 |
} |
| 4701 |
|
| 4702 |
for (CompartmentsIter c(rt); !c.done(); c.next()) { |
| 4703 |
if (c->gcState.scheduledForDestruction) { |
| 4704 |
return true; |
| 4705 |
} |
| 4706 |
} |
| 4707 |
|
| 4708 |
return false; |
| 4709 |
} |
| 4710 |
|
| 4711 |
struct MOZ_RAII AutoSetZoneSliceThresholds { |
| 4712 |
explicit AutoSetZoneSliceThresholds(GCRuntime* gc) : gc(gc) { |
| 4713 |
// On entry, zones that are already collecting should have a slice threshold |
| 4714 |
// set. |
| 4715 |
for (ZonesIter zone(gc, WithAtoms); !zone.done(); zone.next()) { |
| 4716 |
MOZ_ASSERT(zone->wasGCStarted() == |
| 4717 |
zone->gcHeapThreshold.hasSliceThreshold()); |
| 4718 |
MOZ_ASSERT(zone->wasGCStarted() == |
| 4719 |
zone->mallocHeapThreshold.hasSliceThreshold()); |
| 4720 |
} |
| 4721 |
} |
| 4722 |
|
| 4723 |
~AutoSetZoneSliceThresholds() { |
| 4724 |
// On exit, update the thresholds for all collecting zones. |
| 4725 |
bool waitingOnBGTask = gc->isWaitingOnBackgroundTask(); |
| 4726 |
for (ZonesIter zone(gc, WithAtoms); !zone.done(); zone.next()) { |
| 4727 |
if (zone->wasGCStarted()) { |
| 4728 |
zone->setGCSliceThresholds(*gc, waitingOnBGTask); |
| 4729 |
} else { |
| 4730 |
MOZ_ASSERT(!zone->gcHeapThreshold.hasSliceThreshold()); |
| 4731 |
MOZ_ASSERT(!zone->mallocHeapThreshold.hasSliceThreshold()); |
| 4732 |
} |
| 4733 |
} |
| 4734 |
} |
| 4735 |
|
| 4736 |
GCRuntime* gc; |
| 4737 |
}; |
| 4738 |
|
| 4739 |
void GCRuntime::collect(bool nonincrementalByAPI, const SliceBudget& budget, |
| 4740 |
JS::GCReason reason) { |
| 4741 |
TimeStamp startTime = TimeStamp::Now(); |
| 4742 |
auto timer = MakeScopeExit([&] { |
| 4743 |
if (Realm* realm = rt->mainContextFromOwnThread()->realm()) { |
| 4744 |
realm->timers.gcTime += TimeStamp::Now() - startTime; |
| 4745 |
} |
| 4746 |
}); |
| 4747 |
|
| 4748 |
auto clearGCOptions = MakeScopeExit([&] { |
| 4749 |
if (!isIncrementalGCInProgress()) { |
| 4750 |
maybeGcOptions = Nothing(); |
| 4751 |
} |
| 4752 |
}); |
| 4753 |
|
| 4754 |
MOZ_ASSERT(reason != JS::GCReason::NO_REASON); |
| 4755 |
|
| 4756 |
// Checks run for each request, even if we do not actually GC. |
| 4757 |
checkCanCallAPI(); |
| 4758 |
|
| 4759 |
// Check if we are allowed to GC at this time before proceeding. |
| 4760 |
if (!checkIfGCAllowedInCurrentState(reason)) { |
| 4761 |
return; |
| 4762 |
} |
| 4763 |
|
| 4764 |
stats().log("GC slice starting in state %s", StateName(incrementalState)); |
| 4765 |
|
| 4766 |
AutoStopVerifyingBarriers av(rt, isShutdownGC()); |
| 4767 |
AutoMaybeLeaveAtomsZone leaveAtomsZone(rt->mainContextFromOwnThread()); |
| 4768 |
AutoSetZoneSliceThresholds sliceThresholds(this); |
| 4769 |
|
| 4770 |
if (!isIncrementalGCInProgress() && tunables.balancedHeapLimitsEnabled()) { |
| 4771 |
updateAllocationRates(); |
| 4772 |
} |
| 4773 |
|
| 4774 |
bool repeat; |
| 4775 |
do { |
| 4776 |
IncrementalResult cycleResult = |
| 4777 |
gcCycle(nonincrementalByAPI, budget, reason); |
| 4778 |
|
| 4779 |
if (cycleResult == IncrementalResult::Abort) { |
| 4780 |
MOZ_ASSERT(reason == JS::GCReason::ABORT_GC); |
| 4781 |
MOZ_ASSERT(!isIncrementalGCInProgress()); |
| 4782 |
stats().log("GC aborted by request"); |
| 4783 |
break; |
| 4784 |
} |
| 4785 |
|
| 4786 |
/* |
| 4787 |
* Sometimes when we finish a GC we need to immediately start a new one. |
| 4788 |
* This happens in the following cases: |
| 4789 |
* - when we reset the current GC |
| 4790 |
* - when finalizers drop roots during shutdown |
| 4791 |
* - when zones that we thought were dead at the start of GC are |
| 4792 |
* not collected (see the large comment in beginMarkPhase) |
| 4793 |
*/ |
| 4794 |
repeat = false; |
| 4795 |
if (!isIncrementalGCInProgress()) { |
| 4796 |
if (cycleResult == IncrementalResult::Reset) { |
| 4797 |
repeat = true; |
| 4798 |
} else if (rootsRemoved && isShutdownGC()) { |
| 4799 |
/* Need to re-schedule all zones for GC. */ |
| 4800 |
JS::PrepareForFullGC(rt->mainContextFromOwnThread()); |
| 4801 |
repeat = true; |
| 4802 |
reason = JS::GCReason::ROOTS_REMOVED; |
| 4803 |
} else if (shouldRepeatForDeadZone(reason)) { |
| 4804 |
repeat = true; |
| 4805 |
reason = JS::GCReason::COMPARTMENT_REVIVED; |
| 4806 |
} |
| 4807 |
} |
| 4808 |
} while (repeat); |
| 4809 |
|
| 4810 |
if (reason == JS::GCReason::COMPARTMENT_REVIVED) { |
| 4811 |
maybeDoCycleCollection(); |
| 4812 |
} |
| 4813 |
|
| 4814 |
#ifdef JS_GC_ZEAL |
| 4815 |
if (!isIncrementalGCInProgress()) { |
| 4816 |
if (hasZealMode(ZealMode::CheckHeapAfterGC)) { |
| 4817 |
gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::TRACE_HEAP); |
| 4818 |
CheckHeapAfterGC(rt); |
| 4819 |
} |
| 4820 |
if (hasZealMode(ZealMode::CheckGrayMarking)) { |
| 4821 |
MOZ_RELEASE_ASSERT(CheckGrayMarkingState(rt)); |
| 4822 |
} |
| 4823 |
} |
| 4824 |
#endif |
| 4825 |
stats().log("GC slice ending in state %s", StateName(incrementalState)); |
| 4826 |
|
| 4827 |
UnscheduleZones(this); |
| 4828 |
} |
| 4829 |
|
| 4830 |
SliceBudget GCRuntime::defaultBudget(JS::GCReason reason, int64_t millis) { |
| 4831 |
// millis == 0 means use internal GC scheduling logic to come up with |
| 4832 |
// a duration for the slice budget. This may end up still being zero |
| 4833 |
// based on preferences. |
| 4834 |
if (millis == 0) { |
| 4835 |
millis = defaultSliceBudgetMS(); |
| 4836 |
} |
| 4837 |
|
| 4838 |
// If the embedding has registered a callback for creating SliceBudgets, |
| 4839 |
// then use it. |
| 4840 |
if (createBudgetCallback) { |
| 4841 |
return createBudgetCallback(reason, millis); |
| 4842 |
} |
| 4843 |
|
| 4844 |
// Otherwise, the preference can request an unlimited duration slice. |
| 4845 |
if (millis == 0) { |
| 4846 |
return SliceBudget::unlimited(); |
| 4847 |
} |
| 4848 |
|
| 4849 |
return SliceBudget(TimeBudget(millis)); |
| 4850 |
} |
| 4851 |
|
| 4852 |
void GCRuntime::gc(JS::GCOptions options, JS::GCReason reason) { |
| 4853 |
if (!isIncrementalGCInProgress()) { |
| 4854 |
setGCOptions(options); |
| 4855 |
} |
| 4856 |
|
| 4857 |
collect(true, SliceBudget::unlimited(), reason); |
| 4858 |
} |
| 4859 |
|
| 4860 |
void GCRuntime::startGC(JS::GCOptions options, JS::GCReason reason, |
| 4861 |
const SliceBudget& budget) { |
| 4862 |
MOZ_ASSERT(!isIncrementalGCInProgress()); |
| 4863 |
setGCOptions(options); |
| 4864 |
|
| 4865 |
if (!JS::IsIncrementalGCEnabled(rt->mainContextFromOwnThread())) { |
| 4866 |
collect(true, SliceBudget::unlimited(), reason); |
| 4867 |
return; |
| 4868 |
} |
| 4869 |
|
| 4870 |
collect(false, budget, reason); |
| 4871 |
} |
| 4872 |
|
| 4873 |
void GCRuntime::setGCOptions(JS::GCOptions options) { |
| 4874 |
MOZ_ASSERT(maybeGcOptions == Nothing()); |
| 4875 |
maybeGcOptions = Some(options); |
| 4876 |
} |
| 4877 |
|
| 4878 |
void GCRuntime::gcSlice(JS::GCReason reason, const SliceBudget& budget) { |
| 4879 |
MOZ_ASSERT(isIncrementalGCInProgress()); |
| 4880 |
collect(false, budget, reason); |
| 4881 |
} |
| 4882 |
|
| 4883 |
void GCRuntime::finishGC(JS::GCReason reason) { |
| 4884 |
MOZ_ASSERT(isIncrementalGCInProgress()); |
| 4885 |
|
| 4886 |
// If we're not collecting because we're out of memory then skip the |
| 4887 |
// compacting phase if we need to finish an ongoing incremental GC |
| 4888 |
// non-incrementally to avoid janking the browser. |
| 4889 |
if (!IsOOMReason(initialReason)) { |
| 4890 |
if (incrementalState == State::Compact) { |
| 4891 |
abortGC(); |
| 4892 |
return; |
| 4893 |
} |
| 4894 |
|
| 4895 |
isCompacting = false; |
| 4896 |
} |
| 4897 |
|
| 4898 |
collect(false, SliceBudget::unlimited(), reason); |
| 4899 |
} |
| 4900 |
|
| 4901 |
void GCRuntime::abortGC() { |
| 4902 |
MOZ_ASSERT(isIncrementalGCInProgress()); |
| 4903 |
checkCanCallAPI(); |
| 4904 |
MOZ_ASSERT(!rt->mainContextFromOwnThread()->suppressGC); |
| 4905 |
|
| 4906 |
collect(false, SliceBudget::unlimited(), JS::GCReason::ABORT_GC); |
| 4907 |
} |
| 4908 |
|
| 4909 |
static bool ZonesSelected(GCRuntime* gc) { |
| 4910 |
for (ZonesIter zone(gc, WithAtoms); !zone.done(); zone.next()) { |
| 4911 |
if (zone->isGCScheduled()) { |
| 4912 |
return true; |
| 4913 |
} |
| 4914 |
} |
| 4915 |
return false; |
| 4916 |
} |
| 4917 |
|
| 4918 |
void GCRuntime::startDebugGC(JS::GCOptions options, const SliceBudget& budget) { |
| 4919 |
MOZ_ASSERT(!isIncrementalGCInProgress()); |
| 4920 |
setGCOptions(options); |
| 4921 |
|
| 4922 |
if (!ZonesSelected(this)) { |
| 4923 |
JS::PrepareForFullGC(rt->mainContextFromOwnThread()); |
| 4924 |
} |
| 4925 |
|
| 4926 |
collect(false, budget, JS::GCReason::DEBUG_GC); |
| 4927 |
} |
| 4928 |
|
| 4929 |
void GCRuntime::debugGCSlice(const SliceBudget& budget) { |
| 4930 |
MOZ_ASSERT(isIncrementalGCInProgress()); |
| 4931 |
|
| 4932 |
if (!ZonesSelected(this)) { |
| 4933 |
JS::PrepareForIncrementalGC(rt->mainContextFromOwnThread()); |
| 4934 |
} |
| 4935 |
|
| 4936 |
collect(false, budget, JS::GCReason::DEBUG_GC); |
| 4937 |
} |
| 4938 |
|
| 4939 |
void js::PrepareForDebugGC(JSRuntime* rt) { |
| 4940 |
// If zones have already been scheduled then use them. |
| 4941 |
if (ZonesSelected(&rt->gc)) { |
| 4942 |
return; |
| 4943 |
} |
| 4944 |
|
| 4945 |
// If we already started a GC then continue with the same set of zones. This |
| 4946 |
// prevents resetting an ongoing GC when new zones are added. |
| 4947 |
JSContext* cx = rt->mainContextFromOwnThread(); |
| 4948 |
if (JS::IsIncrementalGCInProgress(cx)) { |
| 4949 |
JS::PrepareForIncrementalGC(cx); |
| 4950 |
return; |
| 4951 |
} |
| 4952 |
|
| 4953 |
// Otherwise schedule all zones. |
| 4954 |
JS::PrepareForFullGC(rt->mainContextFromOwnThread()); |
| 4955 |
} |
| 4956 |
|
| 4957 |
void GCRuntime::onOutOfMallocMemory() { |
| 4958 |
// Stop allocating new chunks. |
| 4959 |
allocTask.cancelAndWait(); |
| 4960 |
|
| 4961 |
// Make sure we release anything queued for release. |
| 4962 |
decommitTask.join(); |
| 4963 |
nursery().joinDecommitTask(); |
| 4964 |
|
| 4965 |
// Wait for background free of nursery huge slots to finish. |
| 4966 |
sweepTask.join(); |
| 4967 |
|
| 4968 |
AutoLockGC lock(this); |
| 4969 |
onOutOfMallocMemory(lock); |
| 4970 |
} |
| 4971 |
|
| 4972 |
void GCRuntime::onOutOfMallocMemory(const AutoLockGC& lock) { |
| 4973 |
#ifdef DEBUG |
| 4974 |
// Release any relocated arenas we may be holding on to, without releasing |
| 4975 |
// the GC lock. |
| 4976 |
releaseHeldRelocatedArenasWithoutUnlocking(lock); |
| 4977 |
#endif |
| 4978 |
|
| 4979 |
// Throw away any excess chunks we have lying around. |
| 4980 |
freeEmptyChunks(lock); |
| 4981 |
|
| 4982 |
// Immediately decommit as many arenas as possible in the hopes that this |
| 4983 |
// might let the OS scrape together enough pages to satisfy the failing |
| 4984 |
// malloc request. |
| 4985 |
if (DecommitEnabled()) { |
| 4986 |
decommitFreeArenasWithoutUnlocking(lock); |
| 4987 |
} |
| 4988 |
} |
| 4989 |
|
| 4990 |
void GCRuntime::minorGC(JS::GCReason reason, gcstats::PhaseKind phase) { |
| 4991 |
MOZ_ASSERT(!JS::RuntimeHeapIsBusy()); |
| 4992 |
|
| 4993 |
MOZ_ASSERT_IF(reason == JS::GCReason::EVICT_NURSERY, |
| 4994 |
!rt->mainContextFromOwnThread()->suppressGC); |
| 4995 |
if (rt->mainContextFromOwnThread()->suppressGC) { |
| 4996 |
return; |
| 4997 |
} |
| 4998 |
|
| 4999 |
incGcNumber(); |
| 5000 |
|
| 5001 |
collectNursery(JS::GCOptions::Normal, reason, phase); |
| 5002 |
|
| 5003 |
#ifdef JS_GC_ZEAL |
| 5004 |
if (hasZealMode(ZealMode::CheckHeapAfterGC)) { |
| 5005 |
gcstats::AutoPhase ap(stats(), phase); |
| 5006 |
waitBackgroundSweepEnd(); |
| 5007 |
waitBackgroundDecommitEnd(); |
| 5008 |
CheckHeapAfterGC(rt); |
| 5009 |
} |
| 5010 |
#endif |
| 5011 |
|
| 5012 |
for (ZonesIter zone(this, WithAtoms); !zone.done(); zone.next()) { |
| 5013 |
maybeTriggerGCAfterAlloc(zone); |
| 5014 |
maybeTriggerGCAfterMalloc(zone); |
| 5015 |
} |
| 5016 |
} |
| 5017 |
|
| 5018 |
void GCRuntime::collectNursery(JS::GCOptions options, JS::GCReason reason, |
| 5019 |
gcstats::PhaseKind phase) { |
| 5020 |
AutoMaybeLeaveAtomsZone leaveAtomsZone(rt->mainContextFromOwnThread()); |
| 5021 |
|
| 5022 |
uint32_t numAllocs = 0; |
| 5023 |
for (ZonesIter zone(this, WithAtoms); !zone.done(); zone.next()) { |
| 5024 |
numAllocs += zone->getAndResetTenuredAllocsSinceMinorGC(); |
| 5025 |
} |
| 5026 |
stats().setAllocsSinceMinorGCTenured(numAllocs); |
| 5027 |
|
| 5028 |
gcstats::AutoPhase ap(stats(), phase); |
| 5029 |
|
| 5030 |
nursery().collect(options, reason); |
| 5031 |
|
| 5032 |
startBackgroundFreeAfterMinorGC(); |
| 5033 |
|
| 5034 |
// We ignore gcMaxBytes when allocating for minor collection. However, if we |
| 5035 |
// overflowed, we disable the nursery. The next time we allocate, we'll fail |
| 5036 |
// because bytes >= gcMaxBytes. |
| 5037 |
if (heapSize.bytes() >= tunables.gcMaxBytes()) { |
| 5038 |
if (!nursery().isEmpty()) { |
| 5039 |
nursery().collect(options, JS::GCReason::DISABLE_GENERATIONAL_GC); |
| 5040 |
MOZ_ASSERT(nursery().isEmpty()); |
| 5041 |
startBackgroundFreeAfterMinorGC(); |
| 5042 |
} |
| 5043 |
|
| 5044 |
// Disabling the nursery triggers pre-barriers when we discard JIT |
| 5045 |
// code. Normally we don't allow any barriers in a major GC and there is an |
| 5046 |
// assertion to check this in PreWriteBarrier. For the case where we disable |
| 5047 |
// the nursery during a major GC, set up a minor GC session to silence the |
| 5048 |
// assertion. |
| 5049 |
AutoGCSession session(this, JS::HeapState::MinorCollecting); |
| 5050 |
|
| 5051 |
nursery().disable(); |
| 5052 |
} |
| 5053 |
} |
| 5054 |
|
| 5055 |
void GCRuntime::startBackgroundFreeAfterMinorGC() { |
| 5056 |
// Called after nursery collection. Free whatever blocks are safe to free now. |
| 5057 |
|
| 5058 |
AutoLockHelperThreadState lock; |
| 5059 |
|
| 5060 |
lifoBlocksToFree.ref().transferFrom(&lifoBlocksToFreeAfterNextMinorGC.ref()); |
| 5061 |
|
| 5062 |
if (nursery().tenuredEverything) { |
| 5063 |
lifoBlocksToFree.ref().transferFrom( |
| 5064 |
&lifoBlocksToFreeAfterFullMinorGC.ref()); |
| 5065 |
} else { |
| 5066 |
lifoBlocksToFreeAfterNextMinorGC.ref().transferFrom( |
| 5067 |
&lifoBlocksToFreeAfterFullMinorGC.ref()); |
| 5068 |
} |
| 5069 |
|
| 5070 |
if (!hasBuffersForBackgroundFree()) { |
| 5071 |
return; |
| 5072 |
} |
| 5073 |
|
| 5074 |
freeTask.startOrRunIfIdle(lock); |
| 5075 |
} |
| 5076 |
|
| 5077 |
bool GCRuntime::gcIfRequestedImpl(bool eagerOk) { |
| 5078 |
// This method returns whether a major GC was performed. |
| 5079 |
|
| 5080 |
if (nursery().minorGCRequested()) { |
| 5081 |
minorGC(nursery().minorGCTriggerReason()); |
| 5082 |
} |
| 5083 |
|
| 5084 |
JS::GCReason reason = wantMajorGC(eagerOk); |
| 5085 |
if (reason == JS::GCReason::NO_REASON) { |
| 5086 |
return false; |
| 5087 |
} |
| 5088 |
|
| 5089 |
SliceBudget budget = defaultBudget(reason, 0); |
| 5090 |
if (!isIncrementalGCInProgress()) { |
| 5091 |
startGC(JS::GCOptions::Normal, reason, budget); |
| 5092 |
} else { |
| 5093 |
gcSlice(reason, budget); |
| 5094 |
} |
| 5095 |
return true; |
| 5096 |
} |
| 5097 |
|
| 5098 |
void js::gc::FinishGC(JSContext* cx, JS::GCReason reason) { |
| 5099 |
// Calling this when GC is suppressed won't have any effect. |
| 5100 |
MOZ_ASSERT(!cx->suppressGC); |
| 5101 |
|
| 5102 |
// GC callbacks may run arbitrary code, including JS. Check this regardless of |
| 5103 |
// whether we GC for this invocation. |
| 5104 |
MOZ_ASSERT(cx->isNurseryAllocAllowed()); |
| 5105 |
|
| 5106 |
if (JS::IsIncrementalGCInProgress(cx)) { |
| 5107 |
JS::PrepareForIncrementalGC(cx); |
| 5108 |
JS::FinishIncrementalGC(cx, reason); |
| 5109 |
} |
| 5110 |
} |
| 5111 |
|
| 5112 |
void js::gc::WaitForBackgroundTasks(JSContext* cx) { |
| 5113 |
cx->runtime()->gc.waitForBackgroundTasks(); |
| 5114 |
} |
| 5115 |
|
| 5116 |
void GCRuntime::waitForBackgroundTasks() { |
| 5117 |
MOZ_ASSERT(!isIncrementalGCInProgress()); |
| 5118 |
MOZ_ASSERT(sweepTask.isIdle()); |
| 5119 |
MOZ_ASSERT(decommitTask.isIdle()); |
| 5120 |
MOZ_ASSERT(markTask.isIdle()); |
| 5121 |
|
| 5122 |
allocTask.join(); |
| 5123 |
freeTask.join(); |
| 5124 |
nursery().joinDecommitTask(); |
| 5125 |
} |
| 5126 |
|
| 5127 |
Realm* js::NewRealm(JSContext* cx, JSPrincipals* principals, |
| 5128 |
const JS::RealmOptions& options) { |
| 5129 |
JSRuntime* rt = cx->runtime(); |
| 5130 |
JS_AbortIfWrongThread(cx); |
| 5131 |
|
| 5132 |
UniquePtr<Zone> zoneHolder; |
| 5133 |
UniquePtr<Compartment> compHolder; |
| 5134 |
|
| 5135 |
Compartment* comp = nullptr; |
| 5136 |
Zone* zone = nullptr; |
| 5137 |
JS::CompartmentSpecifier compSpec = |
| 5138 |
options.creationOptions().compartmentSpecifier(); |
| 5139 |
switch (compSpec) { |
| 5140 |
case JS::CompartmentSpecifier::NewCompartmentInSystemZone: |
| 5141 |
// systemZone might be null here, in which case we'll make a zone and |
| 5142 |
// set this field below. |
| 5143 |
zone = rt->gc.systemZone; |
| 5144 |
break; |
| 5145 |
case JS::CompartmentSpecifier::NewCompartmentInExistingZone: |
| 5146 |
zone = options.creationOptions().zone(); |
| 5147 |
MOZ_ASSERT(zone); |
| 5148 |
break; |
| 5149 |
case JS::CompartmentSpecifier::ExistingCompartment: |
| 5150 |
comp = options.creationOptions().compartment(); |
| 5151 |
zone = comp->zone(); |
| 5152 |
break; |
| 5153 |
case JS::CompartmentSpecifier::NewCompartmentAndZone: |
| 5154 |
break; |
| 5155 |
} |
| 5156 |
|
| 5157 |
if (!zone) { |
| 5158 |
Zone::Kind kind = Zone::NormalZone; |
| 5159 |
const JSPrincipals* trusted = rt->trustedPrincipals(); |
| 5160 |
if (compSpec == JS::CompartmentSpecifier::NewCompartmentInSystemZone || |
| 5161 |
(principals && principals == trusted)) { |
| 5162 |
kind = Zone::SystemZone; |
| 5163 |
} |
| 5164 |
|
| 5165 |
zoneHolder = MakeUnique<Zone>(cx->runtime(), kind); |
| 5166 |
if (!zoneHolder || !zoneHolder->init()) { |
| 5167 |
ReportOutOfMemory(cx); |
| 5168 |
return nullptr; |
| 5169 |
} |
| 5170 |
|
| 5171 |
zone = zoneHolder.get(); |
| 5172 |
} |
| 5173 |
|
| 5174 |
bool invisibleToDebugger = options.creationOptions().invisibleToDebugger(); |
| 5175 |
if (comp) { |
| 5176 |
// Debugger visibility is per-compartment, not per-realm, so make sure the |
| 5177 |
// new realm's visibility matches its compartment's. |
| 5178 |
MOZ_ASSERT(comp->invisibleToDebugger() == invisibleToDebugger); |
| 5179 |
} else { |
| 5180 |
compHolder = cx->make_unique<JS::Compartment>(zone, invisibleToDebugger); |
| 5181 |
if (!compHolder) { |
| 5182 |
return nullptr; |
| 5183 |
} |
| 5184 |
|
| 5185 |
comp = compHolder.get(); |
| 5186 |
} |
| 5187 |
|
| 5188 |
UniquePtr<Realm> realm(cx->new_<Realm>(comp, options)); |
| 5189 |
if (!realm) { |
| 5190 |
return nullptr; |
| 5191 |
} |
| 5192 |
realm->init(cx, principals); |
| 5193 |
|
| 5194 |
// Make sure we don't put system and non-system realms in the same |
| 5195 |
// compartment. |
| 5196 |
if (!compHolder) { |
| 5197 |
MOZ_RELEASE_ASSERT(realm->isSystem() == IsSystemCompartment(comp)); |
| 5198 |
} |
| 5199 |
|
| 5200 |
AutoLockGC lock(rt); |
| 5201 |
|
| 5202 |
// Reserve space in the Vectors before we start mutating them. |
| 5203 |
if (!comp->realms().reserve(comp->realms().length() + 1) || |
| 5204 |
(compHolder && |
| 5205 |
!zone->compartments().reserve(zone->compartments().length() + 1)) || |
| 5206 |
(zoneHolder && !rt->gc.zones().reserve(rt->gc.zones().length() + 1))) { |
| 5207 |
ReportOutOfMemory(cx); |
| 5208 |
return nullptr; |
| 5209 |
} |
| 5210 |
|
| 5211 |
// After this everything must be infallible. |
| 5212 |
|
| 5213 |
comp->realms().infallibleAppend(realm.get()); |
| 5214 |
|
| 5215 |
if (compHolder) { |
| 5216 |
zone->compartments().infallibleAppend(compHolder.release()); |
| 5217 |
} |
| 5218 |
|
| 5219 |
if (zoneHolder) { |
| 5220 |
rt->gc.zones().infallibleAppend(zoneHolder.release()); |
| 5221 |
|
| 5222 |
// Lazily set the runtime's system zone. |
| 5223 |
if (compSpec == JS::CompartmentSpecifier::NewCompartmentInSystemZone) { |
| 5224 |
MOZ_RELEASE_ASSERT(!rt->gc.systemZone); |
| 5225 |
MOZ_ASSERT(zone->isSystemZone()); |
| 5226 |
rt->gc.systemZone = zone; |
| 5227 |
} |
| 5228 |
} |
| 5229 |
|
| 5230 |
return realm.release(); |
| 5231 |
} |
| 5232 |
|
| 5233 |
void GCRuntime::runDebugGC() { |
| 5234 |
#ifdef JS_GC_ZEAL |
| 5235 |
if (rt->mainContextFromOwnThread()->suppressGC) { |
| 5236 |
return; |
| 5237 |
} |
| 5238 |
|
| 5239 |
if (hasZealMode(ZealMode::VerifierPost) || |
| 5240 |
hasZealMode(ZealMode::GenerationalGC)) { |
| 5241 |
return minorGC(JS::GCReason::DEBUG_GC); |
| 5242 |
} |
| 5243 |
|
| 5244 |
PrepareForDebugGC(rt); |
| 5245 |
|
| 5246 |
auto budget = SliceBudget::unlimited(); |
| 5247 |
if (hasZealMode(ZealMode::IncrementalMultipleSlices)) { |
| 5248 |
/* |
| 5249 |
* Start with a small slice limit and double it every slice. This |
| 5250 |
* ensure that we get multiple slices, and collection runs to |
| 5251 |
* completion. |
| 5252 |
*/ |
| 5253 |
if (!isIncrementalGCInProgress()) { |
| 5254 |
zealSliceBudget = zealFrequency / 2; |
| 5255 |
} else { |
| 5256 |
zealSliceBudget *= 2; |
| 5257 |
} |
| 5258 |
budget = SliceBudget(WorkBudget(zealSliceBudget)); |
| 5259 |
|
| 5260 |
js::gc::State initialState = incrementalState; |
| 5261 |
if (!isIncrementalGCInProgress()) { |
| 5262 |
setGCOptions(JS::GCOptions::Shrink); |
| 5263 |
} |
| 5264 |
collect(false, budget, JS::GCReason::DEBUG_GC); |
| 5265 |
|
| 5266 |
/* Reset the slice size when we get to the sweep or compact phases. */ |
| 5267 |
if ((initialState == State::Mark && incrementalState == State::Sweep) || |
| 5268 |
(initialState == State::Sweep && incrementalState == State::Compact)) { |
| 5269 |
zealSliceBudget = zealFrequency / 2; |
| 5270 |
} |
| 5271 |
} else if (zealModeControlsYieldPoint()) { |
| 5272 |
// These modes trigger incremental GC that happens in two slices and the |
| 5273 |
// supplied budget is ignored by incrementalSlice. |
| 5274 |
budget = SliceBudget(WorkBudget(1)); |
| 5275 |
|
| 5276 |
if (!isIncrementalGCInProgress()) { |
| 5277 |
setGCOptions(JS::GCOptions::Normal); |
| 5278 |
} |
| 5279 |
collect(false, budget, JS::GCReason::DEBUG_GC); |
| 5280 |
} else if (hasZealMode(ZealMode::Compact)) { |
| 5281 |
gc(JS::GCOptions::Shrink, JS::GCReason::DEBUG_GC); |
| 5282 |
} else { |
| 5283 |
gc(JS::GCOptions::Normal, JS::GCReason::DEBUG_GC); |
| 5284 |
} |
| 5285 |
|
| 5286 |
#endif |
| 5287 |
} |
| 5288 |
|
| 5289 |
void GCRuntime::setFullCompartmentChecks(bool enabled) { |
| 5290 |
MOZ_ASSERT(!JS::RuntimeHeapIsMajorCollecting()); |
| 5291 |
fullCompartmentChecks = enabled; |
| 5292 |
} |
| 5293 |
|
| 5294 |
void GCRuntime::notifyRootsRemoved() { |
| 5295 |
rootsRemoved = true; |
| 5296 |
|
| 5297 |
#ifdef JS_GC_ZEAL |
| 5298 |
/* Schedule a GC to happen "soon". */ |
| 5299 |
if (hasZealMode(ZealMode::RootsChange)) { |
| 5300 |
nextScheduled = 1; |
| 5301 |
} |
| 5302 |
#endif |
| 5303 |
} |
| 5304 |
|
| 5305 |
#ifdef JS_GC_ZEAL |
| 5306 |
bool GCRuntime::selectForMarking(JSObject* object) { |
| 5307 |
MOZ_ASSERT(!JS::RuntimeHeapIsMajorCollecting()); |
| 5308 |
return selectedForMarking.ref().get().append(object); |
| 5309 |
} |
| 5310 |
|
| 5311 |
void GCRuntime::clearSelectedForMarking() { |
| 5312 |
selectedForMarking.ref().get().clearAndFree(); |
| 5313 |
} |
| 5314 |
|
| 5315 |
void GCRuntime::setDeterministic(bool enabled) { |
| 5316 |
MOZ_ASSERT(!JS::RuntimeHeapIsMajorCollecting()); |
| 5317 |
deterministicOnly = enabled; |
| 5318 |
} |
| 5319 |
#endif |
| 5320 |
|
| 5321 |
#ifdef DEBUG |
| 5322 |
|
| 5323 |
AutoAssertNoNurseryAlloc::AutoAssertNoNurseryAlloc() { |
| 5324 |
TlsContext.get()->disallowNurseryAlloc(); |
| 5325 |
} |
| 5326 |
|
| 5327 |
AutoAssertNoNurseryAlloc::~AutoAssertNoNurseryAlloc() { |
| 5328 |
TlsContext.get()->allowNurseryAlloc(); |
| 5329 |
} |
| 5330 |
|
| 5331 |
#endif // DEBUG |
| 5332 |
|
| 5333 |
#ifdef JSGC_HASH_TABLE_CHECKS |
| 5334 |
void GCRuntime::checkHashTablesAfterMovingGC() { |
| 5335 |
waitBackgroundSweepEnd(); |
| 5336 |
waitBackgroundDecommitEnd(); |
| 5337 |
|
| 5338 |
/* |
| 5339 |
* Check that internal hash tables no longer have any pointers to things |
| 5340 |
* that have been moved. |
| 5341 |
*/ |
| 5342 |
rt->geckoProfiler().checkStringsMapAfterMovingGC(); |
| 5343 |
if (rt->hasJitRuntime() && rt->jitRuntime()->hasInterpreterEntryMap()) { |
| 5344 |
rt->jitRuntime()->getInterpreterEntryMap()->checkScriptsAfterMovingGC(); |
| 5345 |
} |
| 5346 |
for (ZonesIter zone(this, SkipAtoms); !zone.done(); zone.next()) { |
| 5347 |
zone->checkUniqueIdTableAfterMovingGC(); |
| 5348 |
zone->shapeZone().checkTablesAfterMovingGC(zone); |
| 5349 |
zone->checkAllCrossCompartmentWrappersAfterMovingGC(); |
| 5350 |
zone->checkScriptMapsAfterMovingGC(); |
| 5351 |
|
| 5352 |
// Note: CompactPropMaps never have a table. |
| 5353 |
JS::AutoCheckCannotGC nogc; |
| 5354 |
for (auto map = zone->cellIterUnsafe<NormalPropMap>(); !map.done(); |
| 5355 |
map.next()) { |
| 5356 |
if (PropMapTable* table = map->asLinked()->maybeTable(nogc)) { |
| 5357 |
table->checkAfterMovingGC(zone); |
| 5358 |
} |
| 5359 |
} |
| 5360 |
for (auto map = zone->cellIterUnsafe<DictionaryPropMap>(); !map.done(); |
| 5361 |
map.next()) { |
| 5362 |
if (PropMapTable* table = map->asLinked()->maybeTable(nogc)) { |
| 5363 |
table->checkAfterMovingGC(zone); |
| 5364 |
} |
| 5365 |
} |
| 5366 |
|
| 5367 |
WeakMapBase::checkWeakMapsAfterMovingGC(zone); |
| 5368 |
} |
| 5369 |
|
| 5370 |
for (CompartmentsIter c(this); !c.done(); c.next()) { |
| 5371 |
for (RealmsInCompartmentIter r(c); !r.done(); r.next()) { |
| 5372 |
r->dtoaCache.checkCacheAfterMovingGC(); |
| 5373 |
if (r->debugEnvs()) { |
| 5374 |
r->debugEnvs()->checkHashTablesAfterMovingGC(); |
| 5375 |
} |
| 5376 |
} |
| 5377 |
} |
| 5378 |
} |
| 5379 |
#endif |
| 5380 |
|
| 5381 |
#ifdef DEBUG |
| 5382 |
bool GCRuntime::hasZone(Zone* target) { |
| 5383 |
for (AllZonesIter zone(this); !zone.done(); zone.next()) { |
| 5384 |
if (zone == target) { |
| 5385 |
return true; |
| 5386 |
} |
| 5387 |
} |
| 5388 |
return false; |
| 5389 |
} |
| 5390 |
#endif |
| 5391 |
|
| 5392 |
void AutoAssertEmptyNursery::checkCondition(JSContext* cx) { |
| 5393 |
if (!noAlloc) { |
| 5394 |
noAlloc.emplace(); |
| 5395 |
} |
| 5396 |
this->cx = cx; |
| 5397 |
MOZ_ASSERT(cx->nursery().isEmpty()); |
| 5398 |
} |
| 5399 |
|
| 5400 |
AutoEmptyNursery::AutoEmptyNursery(JSContext* cx) { |
| 5401 |
MOZ_ASSERT(!cx->suppressGC); |
| 5402 |
cx->runtime()->gc.stats().suspendPhases(); |
| 5403 |
cx->runtime()->gc.evictNursery(JS::GCReason::EVICT_NURSERY); |
| 5404 |
cx->runtime()->gc.stats().resumePhases(); |
| 5405 |
checkCondition(cx); |
| 5406 |
} |
| 5407 |
|
| 5408 |
#ifdef DEBUG |
| 5409 |
|
| 5410 |
namespace js { |
| 5411 |
|
| 5412 |
// We don't want jsfriendapi.h to depend on GenericPrinter, |
| 5413 |
// so these functions are declared directly in the cpp. |
| 5414 |
|
| 5415 |
extern JS_PUBLIC_API void DumpString(JSString* str, js::GenericPrinter& out); |
| 5416 |
|
| 5417 |
} // namespace js |
| 5418 |
|
| 5419 |
void js::gc::Cell::dump(js::GenericPrinter& out) const { |
| 5420 |
switch (getTraceKind()) { |
| 5421 |
case JS::TraceKind::Object: |
| 5422 |
reinterpret_cast<const JSObject*>(this)->dump(out); |
| 5423 |
break; |
| 5424 |
|
| 5425 |
case JS::TraceKind::String: |
| 5426 |
js::DumpString(reinterpret_cast<JSString*>(const_cast<Cell*>(this)), out); |
| 5427 |
break; |
| 5428 |
|
| 5429 |
case JS::TraceKind::Shape: |
| 5430 |
reinterpret_cast<const Shape*>(this)->dump(out); |
| 5431 |
break; |
| 5432 |
|
| 5433 |
default: |
| 5434 |
out.printf("%s(%p)\n", JS::GCTraceKindToAscii(getTraceKind()), |
| 5435 |
(void*)this); |
| 5436 |
} |
| 5437 |
} |
| 5438 |
|
| 5439 |
// For use in a debugger. |
| 5440 |
void js::gc::Cell::dump() const { |
| 5441 |
js::Fprinter out(stderr); |
| 5442 |
dump(out); |
| 5443 |
} |
| 5444 |
#endif |
| 5445 |
|
| 5446 |
JS_PUBLIC_API bool js::gc::detail::CanCheckGrayBits(const TenuredCell* cell) { |
| 5447 |
// We do not check the gray marking state of cells in the following cases: |
| 5448 |
// |
| 5449 |
// 1) When OOM has caused us to clear the gcGrayBitsValid_ flag. |
| 5450 |
// |
| 5451 |
// 2) When we are in an incremental GC and examine a cell that is in a zone |
| 5452 |
// that is not being collected. Gray targets of CCWs that are marked black |
| 5453 |
// by a barrier will eventually be marked black in a later GC slice. |
| 5454 |
// |
| 5455 |
// 3) When mark bits are being cleared concurrently by a helper thread. |
| 5456 |
|
| 5457 |
MOZ_ASSERT(cell); |
| 5458 |
|
| 5459 |
auto* runtime = cell->runtimeFromAnyThread(); |
| 5460 |
MOZ_ASSERT(CurrentThreadCanAccessRuntime(runtime)); |
| 5461 |
|
| 5462 |
if (!runtime->gc.areGrayBitsValid()) { |
| 5463 |
return false; |
| 5464 |
} |
| 5465 |
|
| 5466 |
JS::Zone* zone = cell->zone(); |
| 5467 |
|
| 5468 |
if (runtime->gc.isIncrementalGCInProgress() && !zone->wasGCStarted()) { |
| 5469 |
return false; |
| 5470 |
} |
| 5471 |
|
| 5472 |
return !zone->isGCPreparing(); |
| 5473 |
} |
| 5474 |
|
| 5475 |
JS_PUBLIC_API bool js::gc::detail::CellIsMarkedGrayIfKnown( |
| 5476 |
const TenuredCell* cell) { |
| 5477 |
MOZ_ASSERT_IF(cell->isPermanentAndMayBeShared(), cell->isMarkedBlack()); |
| 5478 |
if (!cell->isMarkedGray()) { |
| 5479 |
return false; |
| 5480 |
} |
| 5481 |
|
| 5482 |
return CanCheckGrayBits(cell); |
| 5483 |
} |
| 5484 |
|
| 5485 |
#ifdef DEBUG |
| 5486 |
|
| 5487 |
JS_PUBLIC_API void js::gc::detail::AssertCellIsNotGray(const Cell* cell) { |
| 5488 |
if (!cell->isTenured()) { |
| 5489 |
return; |
| 5490 |
} |
| 5491 |
|
| 5492 |
// Check that a cell is not marked gray. |
| 5493 |
// |
| 5494 |
// Since this is a debug-only check, take account of the eventual mark state |
| 5495 |
// of cells that will be marked black by the next GC slice in an incremental |
| 5496 |
// GC. For performance reasons we don't do this in CellIsMarkedGrayIfKnown. |
| 5497 |
|
| 5498 |
const auto* tc = &cell->asTenured(); |
| 5499 |
if (!tc->isMarkedGray() || !CanCheckGrayBits(tc)) { |
| 5500 |
return; |
| 5501 |
} |
| 5502 |
|
| 5503 |
// TODO: I'd like to AssertHeapIsIdle() here, but this ends up getting |
| 5504 |
// called during GC and while iterating the heap for memory reporting. |
| 5505 |
MOZ_ASSERT(!JS::RuntimeHeapIsCycleCollecting()); |
| 5506 |
|
| 5507 |
if (tc->zone()->isGCMarkingBlackAndGray()) { |
| 5508 |
// We are doing gray marking in the cell's zone. Even if the cell is |
| 5509 |
// currently marked gray it may eventually be marked black. Delay checking |
| 5510 |
// non-black cells until we finish gray marking. |
| 5511 |
|
| 5512 |
if (!tc->isMarkedBlack()) { |
| 5513 |
JSRuntime* rt = tc->zone()->runtimeFromMainThread(); |
| 5514 |
AutoEnterOOMUnsafeRegion oomUnsafe; |
| 5515 |
if (!rt->gc.cellsToAssertNotGray.ref().append(cell)) { |
| 5516 |
oomUnsafe.crash("Can't append to delayed gray checks list"); |
| 5517 |
} |
| 5518 |
} |
| 5519 |
return; |
| 5520 |
} |
| 5521 |
|
| 5522 |
MOZ_ASSERT(!tc->isMarkedGray()); |
| 5523 |
} |
| 5524 |
|
| 5525 |
extern JS_PUBLIC_API bool js::gc::detail::ObjectIsMarkedBlack( |
| 5526 |
const JSObject* obj) { |
| 5527 |
return obj->isMarkedBlack(); |
| 5528 |
} |
| 5529 |
|
| 5530 |
#endif |
| 5531 |
|
| 5532 |
js::gc::ClearEdgesTracer::ClearEdgesTracer(JSRuntime* rt) |
| 5533 |
: GenericTracerImpl(rt, JS::TracerKind::ClearEdges, |
| 5534 |
JS::WeakMapTraceAction::TraceKeysAndValues) {} |
| 5535 |
|
| 5536 |
template <typename T> |
| 5537 |
void js::gc::ClearEdgesTracer::onEdge(T** thingp, const char* name) { |
| 5538 |
// We don't handle removing pointers to nursery edges from the store buffer |
| 5539 |
// with this tracer. Check that this doesn't happen. |
| 5540 |
T* thing = *thingp; |
| 5541 |
MOZ_ASSERT(!IsInsideNursery(thing)); |
| 5542 |
|
| 5543 |
// Fire the pre-barrier since we're removing an edge from the graph. |
| 5544 |
InternalBarrierMethods<T*>::preBarrier(thing); |
| 5545 |
|
| 5546 |
*thingp = nullptr; |
| 5547 |
} |
| 5548 |
|
| 5549 |
void GCRuntime::setPerformanceHint(PerformanceHint hint) { |
| 5550 |
if (hint == PerformanceHint::InPageLoad) { |
| 5551 |
inPageLoadCount++; |
| 5552 |
} else { |
| 5553 |
MOZ_ASSERT(inPageLoadCount); |
| 5554 |
inPageLoadCount--; |
| 5555 |
} |
| 5556 |
} |