Debian Codegraph @

js/public/HeapAPI.h

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #ifndef js_HeapAPI_h
8 #define js_HeapAPI_h
9
10 #include "mozilla/Atomics.h"
11 #include "mozilla/BitSet.h"
12
13 #include <limits.h>
14 #include <type_traits>
15
16 #include "js/AllocPolicy.h"
17 #include "js/GCAnnotations.h"
18 #include "js/HashTable.h"
19 #include "js/shadow/String.h" // JS::shadow::String
20 #include "js/shadow/Symbol.h" // JS::shadow::Symbol
21 #include "js/shadow/Zone.h" // JS::shadow::Zone
22 #include "js/TraceKind.h"
23 #include "js/TypeDecls.h"
24
25 /* These values are private to the JS engine. */
26 namespace js {
27
28 JS_PUBLIC_API bool CurrentThreadCanAccessZone(JS::Zone* zone);
29
30 // To prevent false sharing, some data structures are aligned to a typical cache
31 // line size.
32 static constexpr size_t TypicalCacheLineSize = 64;
33
34 namespace gc {
35
36 class Arena;
37 struct Cell;
38 class ArenaChunk;
39 class StoreBuffer;
40 class TenuredCell;
41
42 const size_t ArenaShift = 12;
43 const size_t ArenaSize = size_t(1) << ArenaShift;
44 const size_t ArenaMask = ArenaSize - 1;
45
46 #if defined(XP_DARWIN) && defined(__aarch64__)
47 const size_t PageShift = 14;
48 #else
49 const size_t PageShift = 12;
50 #endif
51 // Expected page size, so we could initialze ArenasPerPage at compile-time.
52 // The actual system page size should be queried by SystemPageSize().
53 const size_t PageSize = size_t(1) << PageShift;
54 const size_t PageMask = PageSize - 1;
55 constexpr size_t ArenasPerPage = PageSize / ArenaSize;
56
57 const size_t ChunkShift = 20;
58 const size_t ChunkSize = size_t(1) << ChunkShift;
59 const size_t ChunkMask = ChunkSize - 1;
60
61 const size_t CellAlignShift = 3;
62 const size_t CellAlignBytes = size_t(1) << CellAlignShift;
63 const size_t CellAlignMask = CellAlignBytes - 1;
64
65 const size_t CellBytesPerMarkBit = CellAlignBytes;
66 const size_t MarkBitsPerCell = 2;
67
68 /*
69 * The minimum cell size ends up as twice the cell alignment because the mark
70 * bitmap contains one bit per CellBytesPerMarkBit bytes (which is equal to
71 * CellAlignBytes) and we need two mark bits per cell.
72 */
73 const size_t MinCellSize = CellBytesPerMarkBit * MarkBitsPerCell;
74
75 /*
76 * The mark bitmap has one bit per each possible cell start position. This
77 * wastes some space for larger GC things but allows us to avoid division by the
78 * cell's size when accessing the bitmap.
79 */
80 const size_t ArenaBitmapBits = ArenaSize / CellBytesPerMarkBit;
81 const size_t ArenaBitmapBytes = HowMany(ArenaBitmapBits, 8);
82 const size_t ArenaBitmapWords = HowMany(ArenaBitmapBits, JS_BITS_PER_WORD);
83
84 enum class ChunkKind : uint8_t {
85 Invalid = 0,
86 TenuredArenas,
87 MediumBuffers,
88 NurseryToSpace,
89 NurseryFromSpace
90 };
91
92 // The base class for all GC chunks, either in the nursery or in the tenured
93 // heap memory. This structure is locatable from any GC pointer by aligning to
94 // the chunk size.
95 class ChunkBase {
96 protected:
97 // Initialize a tenured heap chunk.
98 explicit ChunkBase(JSRuntime* rt) {
99 MOZ_ASSERT((uintptr_t(this) & ChunkMask) == 0);
100 initBaseForArenaChunk(rt);
101 }
102
103 void initBaseForArenaChunk(JSRuntime* rt) {
104 runtime = rt;
105 storeBuffer = nullptr;
106 kind = ChunkKind::TenuredArenas;
107 nurseryChunkIndex = UINT8_MAX;
108 }
109
110 // Initialize a nursery chunk.
111 ChunkBase(JSRuntime* rt, StoreBuffer* sb, ChunkKind kind, uint8_t chunkIndex)
112 : storeBuffer(sb),
113 runtime(rt),
114 kind(kind),
115 nurseryChunkIndex(chunkIndex) {
116 MOZ_ASSERT(isNurseryChunk());
117 MOZ_ASSERT((uintptr_t(this) & ChunkMask) == 0);
118 MOZ_ASSERT(storeBuffer);
119 }
120
121 ChunkBase(JSRuntime* rt, ChunkKind kind)
122 : storeBuffer(nullptr),
123 runtime(rt),
124 kind(kind),
125 nurseryChunkIndex(UINT8_MAX) {}
126
127 public:
128 ChunkKind getKind() const {
129 MOZ_ASSERT_IF(storeBuffer, isNurseryChunk());
130 MOZ_ASSERT_IF(!storeBuffer, isTenuredChunk());
131 return kind;
132 }
133
134 bool isNurseryChunk() const {
135 return kind == ChunkKind::NurseryToSpace ||
136 kind == ChunkKind::NurseryFromSpace;
137 }
138
139 bool isTenuredChunk() const {
140 return kind == ChunkKind::TenuredArenas || kind == ChunkKind::MediumBuffers;
141 }
142
143 // The store buffer for pointers from tenured things to things in this
144 // chunk. Will be non-null if and only if this is a nursery chunk.
145 StoreBuffer* storeBuffer;
146
147 // Provide quick access to the runtime from absolutely anywhere.
148 JSRuntime* runtime;
149
150 ChunkKind kind;
151
152 uint8_t nurseryChunkIndex;
153 };
154
155 // Information about tenured heap chunks containing arenas.
156 struct ArenaChunkInfo {
157 private:
158 friend class ChunkPool;
159 ArenaChunk* next = nullptr;
160 ArenaChunk* prev = nullptr;
161
162 public:
163 /* Number of free arenas, either committed or decommitted. */
164 uint32_t numArenasFree;
165
166 /* Number of free, committed arenas. */
167 uint32_t numArenasFreeCommitted;
168
169 /* Whether this chunk is the chunk currently being allocated from. */
170 bool isCurrentChunk = false;
171 };
172
173 /*
174 * Calculating ArenasPerChunk:
175 *
176 * To figure out how many Arenas will fit in a chunk we need to know how much
177 * extra space is available after we allocate the header data. This is a problem
178 * because the header size depends on the number of arenas in the chunk.
179 *
180 * The dependent fields are markBits, decommittedPages and
181 * freeCommittedArenas. markBits needs ArenaBitmapBytes bytes per arena,
182 * decommittedPages needs one bit per page and freeCommittedArenas needs one
183 * bit per arena.
184 *
185 * We can calculate an approximate value by dividing the number of bits of free
186 * space in the chunk by the number of bits needed per arena. This is an
187 * approximation because it doesn't take account of the fact that the variable
188 * sized fields must be rounded up to a whole number of words, or any padding
189 * the compiler adds between fields.
190 *
191 * Fortunately, for the chunk and arena size parameters we use this
192 * approximation turns out to be correct. If it were not we might need to adjust
193 * the arena count down by one to allow more space for the padding.
194 */
195 const size_t BitsPerPageWithHeaders =
196 (ArenaSize + ArenaBitmapBytes) * ArenasPerPage * CHAR_BIT + ArenasPerPage +
197 1;
198 const size_t ChunkBitsAvailable =
199 (ChunkSize - sizeof(ChunkBase) - sizeof(ArenaChunkInfo)) * CHAR_BIT;
200 const size_t PagesPerChunk = ChunkBitsAvailable / BitsPerPageWithHeaders;
201 const size_t ArenasPerChunk = PagesPerChunk * ArenasPerPage;
202 const size_t FreeCommittedBits = ArenasPerChunk;
203 const size_t DecommitBits = PagesPerChunk;
204 const size_t BitsPerArenaWithHeaders =
205 (ArenaSize + ArenaBitmapBytes) * CHAR_BIT +
206 (DecommitBits / ArenasPerChunk) + 1;
207
208 const size_t CalculatedChunkSizeRequired =
209 sizeof(ChunkBase) + sizeof(ArenaChunkInfo) +
210 RoundUp(ArenasPerChunk * ArenaBitmapBytes, sizeof(uintptr_t)) +
211 RoundUp(FreeCommittedBits, sizeof(uint32_t) * CHAR_BIT) / CHAR_BIT +
212 RoundUp(DecommitBits, sizeof(uint32_t) * CHAR_BIT) / CHAR_BIT +
213 ArenasPerChunk * ArenaSize;
214 static_assert(CalculatedChunkSizeRequired <= ChunkSize,
215 "Calculated ArenasPerChunk is too large");
216
217 const size_t CalculatedChunkPadSize = ChunkSize - CalculatedChunkSizeRequired;
218 static_assert(CalculatedChunkPadSize * CHAR_BIT < BitsPerArenaWithHeaders,
219 "Calculated ArenasPerChunk is too small");
220
221 static_assert(ArenasPerChunk == 252,
222 "Do not accidentally change our heap's density.");
223
224 const size_t FirstArenaOffset = ChunkSize - ArenasPerChunk * ArenaSize;
225
226 // Mark bitmaps are atomic because they can be written by gray unmarking on the
227 // main thread while read by sweeping on a background thread. The former does
228 // not affect the result of the latter.
229 using MarkBitmapWord = mozilla::Atomic<uintptr_t, mozilla::Relaxed>;
230 static constexpr size_t MarkBitmapWordBits = sizeof(MarkBitmapWord) * CHAR_BIT;
231
232 /*
233 * Live objects are marked black or gray. Everything reachable from a JS root is
234 * marked black. Objects marked gray are eligible for cycle collection.
235 *
236 * BlackBit: GrayOrBlackBit: Color:
237 * 0 0 white
238 * 0 1 gray
239 * 1 0 black
240 * 1 1 black
241 */
242 enum class ColorBit : uint32_t { BlackBit = 0, GrayOrBlackBit = 1 };
243
244 // Mark colors. Order is important here: the greater value the 'more marked' a
245 // cell is.
246 enum class MarkColor : uint8_t { Gray = 1, Black = 2 };
247
248 // Mark bitmap for a tenured heap chunk.
249 template <size_t BytesPerMarkBit, size_t FirstThingOffset>
250 class alignas(TypicalCacheLineSize) MarkBitmap {
251 static constexpr size_t ByteCount =
252 (ChunkSize - FirstThingOffset) / BytesPerMarkBit;
253 static constexpr size_t WordCount = HowMany(ByteCount, MarkBitmapWordBits);
254 MarkBitmapWord bitmap[WordCount];
255
256 public:
257 static constexpr size_t FirstThingAdjustmentBits =
258 FirstThingOffset / BytesPerMarkBit;
259
260 static constexpr size_t FirstThingAdjustmentWords =
261 FirstThingAdjustmentBits / MarkBitmapWordBits;
262
263 MOZ_ALWAYS_INLINE void getMarkWordAndMask(const void* cell, ColorBit colorBit,
264 MarkBitmapWord** wordp,
265 uintptr_t* maskp) {
266 // Note: the JIT pre-barrier trampolines inline this code. Update
267 // MacroAssembler::emitPreBarrierFastPath code too when making changes here!
268
269 MOZ_ASSERT(size_t(colorBit) < MarkBitsPerCell);
270
271 size_t offset = uintptr_t(cell) & ChunkMask;
272 MOZ_ASSERT(offset >= FirstThingOffset);
273
274 const size_t bit = offset / BytesPerMarkBit + size_t(colorBit);
275 size_t word = bit / MarkBitmapWordBits - FirstThingAdjustmentWords;
276 MOZ_ASSERT(word < WordCount);
277 *wordp = &bitmap[word];
278 *maskp = uintptr_t(1) << (bit % MarkBitmapWordBits);
279 }
280
281 // The following are not exported and are defined in gc/Heap.h:
282 MOZ_ALWAYS_INLINE bool markBit(const void* cell, ColorBit colorBit) {
283 MarkBitmapWord* word;
284 uintptr_t mask;
285 getMarkWordAndMask(cell, colorBit, &word, &mask);
286 return *word & mask;
287 }
288
289 MOZ_ALWAYS_INLINE bool isMarkedAny(const void* cell) {
290 return markBit(cell, ColorBit::BlackBit) ||
291 markBit(cell, ColorBit::GrayOrBlackBit);
292 }
293
294 MOZ_ALWAYS_INLINE bool isMarkedBlack(const void* cell) {
295 // Return true if BlackBit is set.
296 return markBit(cell, ColorBit::BlackBit);
297 }
298
299 MOZ_ALWAYS_INLINE bool isMarkedGray(const void* cell) {
300 // Return true if GrayOrBlackBit is set and BlackBit is not set.
301 return !markBit(cell, ColorBit::BlackBit) &&
302 markBit(cell, ColorBit::GrayOrBlackBit);
303 }
304
305 inline bool markIfUnmarked(const void* cell, MarkColor color);
306 inline bool markIfUnmarkedThreadSafe(const void* cell, MarkColor color);
307 inline void markBlack(const void* cell);
308 inline void markBlackAtomic(const void* cell);
309 inline void copyMarkBit(TenuredCell* dst, const TenuredCell* src,
310 ColorBit colorBit);
311 inline void unmark(const void* cell);
312 inline void unmarkOneBit(const void* cell, ColorBit colorBit);
313 inline MarkBitmapWord* arenaBits(Arena* arena);
314
315 inline void copyFrom(const MarkBitmap& other);
316 inline void clear();
317 };
318
319 using ChunkMarkBitmap = MarkBitmap<CellBytesPerMarkBit, FirstArenaOffset>;
320
321 // Bitmap with one bit per page used for decommitted page set.
322 using ChunkPageBitmap = mozilla::BitSet<PagesPerChunk, uint32_t>;
323
324 // Bitmap with one bit per arena used for free committed arena set.
325 using ChunkArenaBitmap = mozilla::BitSet<ArenasPerChunk, uint32_t>;
326
327 // Base class for a tenured heap chunk containing fixed size arenas.
328 class ArenaChunkBase : public ChunkBase {
329 public:
330 ArenaChunkInfo info;
331 ChunkMarkBitmap markBits;
332 ChunkArenaBitmap freeCommittedArenas;
333 ChunkPageBitmap decommittedPages;
334
335 protected:
336 explicit ArenaChunkBase(JSRuntime* runtime) : ChunkBase(runtime) {
337 static_assert(sizeof(markBits) == ArenaBitmapBytes * ArenasPerChunk,
338 "Ensure our MarkBitmap actually covers all arenas.");
339 info.numArenasFree = ArenasPerChunk;
340 }
341
342 void initAsCommitted();
343 void initAsDecommitted();
344 };
345 static_assert(FirstArenaOffset ==
346 RoundUp(sizeof(gc::ArenaChunkBase), ArenaSize));
347
348 /*
349 * We sometimes use an index to refer to a cell in an arena. The index for a
350 * cell is found by dividing by the cell alignment so not all indices refer to
351 * valid cells.
352 */
353 const size_t ArenaCellIndexBytes = CellAlignBytes;
354 const size_t MaxArenaCellIndex = ArenaSize / CellAlignBytes;
355
356 const size_t ChunkStoreBufferOffset = offsetof(ChunkBase, storeBuffer);
357 const size_t ChunkMarkBitmapOffset = offsetof(ArenaChunkBase, markBits);
358
359 // Hardcoded offsets into Arena class.
360 const size_t ArenaZoneOffset = 2 * sizeof(uint32_t);
361 const size_t ArenaHeaderSize = ArenaZoneOffset + 2 * sizeof(uintptr_t) +
362 sizeof(size_t) + sizeof(uintptr_t);
363
364 // The first word of a GC thing has certain requirements from the GC and is used
365 // to store flags in the low bits.
366 const size_t CellFlagBitsReservedForGC = 3;
367
368 // The first word can be used to store JSClass pointers for some thing kinds, so
369 // these must be suitably aligned.
370 const size_t JSClassAlignBytes = size_t(1) << CellFlagBitsReservedForGC;
371
372 #ifdef JS_DEBUG
373 /* When downcasting, ensure we are actually the right type. */
374 extern JS_PUBLIC_API void AssertGCThingHasType(js::gc::Cell* cell,
375 JS::TraceKind kind);
376 #else
377 inline void AssertGCThingHasType(js::gc::Cell* cell, JS::TraceKind kind) {}
378 #endif
379
380 MOZ_ALWAYS_INLINE bool IsInsideNursery(const js::gc::Cell* cell);
381 MOZ_ALWAYS_INLINE bool IsInsideNursery(const js::gc::TenuredCell* cell);
382
383 } /* namespace gc */
384 } /* namespace js */
385
386 namespace JS {
387
388 enum class HeapState {
389 Idle, // doing nothing with the GC heap
390 Tracing, // tracing the GC heap without collecting, e.g.
391 // IterateCompartments()
392 MajorCollecting, // doing a GC of the major heap
393 MinorCollecting, // doing a GC of the minor heap (nursery)
394 CycleCollecting // in the "Unlink" phase of cycle collection
395 };
396
397 JS_PUBLIC_API HeapState RuntimeHeapState();
398
399 static inline bool RuntimeHeapIsBusy() {
400 return RuntimeHeapState() != HeapState::Idle;
401 }
402
403 static inline bool RuntimeHeapIsTracing() {
404 return RuntimeHeapState() == HeapState::Tracing;
405 }
406
407 static inline bool RuntimeHeapIsMajorCollecting() {
408 return RuntimeHeapState() == HeapState::MajorCollecting;
409 }
410
411 static inline bool RuntimeHeapIsMinorCollecting() {
412 return RuntimeHeapState() == HeapState::MinorCollecting;
413 }
414
415 static inline bool RuntimeHeapIsCollecting(HeapState state) {
416 return state == HeapState::MajorCollecting ||
417 state == HeapState::MinorCollecting;
418 }
419
420 static inline bool RuntimeHeapIsCollecting() {
421 return RuntimeHeapIsCollecting(RuntimeHeapState());
422 }
423
424 static inline bool RuntimeHeapIsCycleCollecting() {
425 return RuntimeHeapState() == HeapState::CycleCollecting;
426 }
427
428 /*
429 * This list enumerates the different types of conceptual stacks we have in
430 * SpiderMonkey. In reality, they all share the C stack, but we allow different
431 * stack limits depending on the type of code running.
432 */
433 enum StackKind {
434 StackForSystemCode, // C++, such as the GC, running on behalf of the VM.
435 StackForTrustedScript, // Script running with trusted principals.
436 StackForUntrustedScript, // Script running with untrusted principals.
437 StackKindCount
438 };
439
440 /*
441 * Default maximum size for the generational nursery in bytes. This is the
442 * initial value. In the browser this configured by the
443 * javascript.options.mem.nursery.max_kb pref.
444 */
445 const uint32_t DefaultNurseryMaxBytes = 64 * js::gc::ChunkSize;
446
447 /* Default maximum heap size in bytes to pass to JS_NewContext(). */
448 const uint32_t DefaultHeapMaxBytes = 32 * 1024 * 1024;
449
450 /**
451 * A GC pointer, tagged with the trace kind.
452 *
453 * In general, a GC pointer should be stored with an exact type. This class
454 * is for use when that is not possible because a single pointer must point
455 * to several kinds of GC thing.
456 */
457 class JS_PUBLIC_API GCCellPtr {
458 public:
459 GCCellPtr() : GCCellPtr(nullptr) {}
460
461 // Construction from a void* and trace kind.
462 GCCellPtr(void* gcthing, JS::TraceKind traceKind)
463 : ptr(checkedCast(gcthing, traceKind)) {}
464
465 // Automatically construct a null GCCellPtr from nullptr.
466 MOZ_IMPLICIT GCCellPtr(decltype(nullptr))
467 : ptr(checkedCast(nullptr, JS::TraceKind::Null)) {}
468
469 // Construction from an explicit type.
470 template <typename T>
471 explicit GCCellPtr(T* p)
472 : ptr(checkedCast(p, JS::MapTypeToTraceKind<T>::kind)) {}
473 explicit GCCellPtr(JSFunction* p)
474 : ptr(checkedCast(p, JS::TraceKind::Object)) {}
475 explicit GCCellPtr(JSScript* p)
476 : ptr(checkedCast(p, JS::TraceKind::Script)) {}
477 explicit GCCellPtr(const Value& v);
478
479 JS::TraceKind kind() const {
480 uintptr_t kindBits = ptr & OutOfLineTraceKindMask;
481 if (kindBits != OutOfLineTraceKindMask) {
482 return JS::TraceKind(kindBits);
483 }
484 return outOfLineKind();
485 }
486
487 // Allow GCCellPtr to be used in a boolean context.
488 explicit operator bool() const {
489 MOZ_ASSERT(bool(asCell()) == (kind() != JS::TraceKind::Null));
490 return asCell();
491 }
492
493 bool operator==(const GCCellPtr other) const { return ptr == other.ptr; }
494 bool operator!=(const GCCellPtr other) const { return ptr != other.ptr; }
495
496 // Simplify checks to the kind.
497 template <typename T, typename = std::enable_if_t<JS::IsBaseTraceType_v<T>>>
498 bool is() const {
499 return kind() == JS::MapTypeToTraceKind<T>::kind;
500 }
501
502 // Conversions to more specific types must match the kind. Access to
503 // further refined types is not allowed directly from a GCCellPtr.
504 template <typename T, typename = std::enable_if_t<JS::IsBaseTraceType_v<T>>>
505 T& as() const {
506 MOZ_ASSERT(kind() == JS::MapTypeToTraceKind<T>::kind);
507 // We can't use static_cast here, because the fact that JSObject
508 // inherits from js::gc::Cell is not part of the public API.
509 return *reinterpret_cast<T*>(asCell());
510 }
511
512 // Return a pointer to the cell this |GCCellPtr| refers to, or |nullptr|.
513 // (It would be more symmetrical with |to| for this to return a |Cell&|, but
514 // the result can be |nullptr|, and null references are undefined behavior.)
515 js::gc::Cell* asCell() const {
516 return reinterpret_cast<js::gc::Cell*>(ptr & ~OutOfLineTraceKindMask);
517 }
518
519 // The CC's trace logger needs an identity that is XPIDL serializable.
520 uint64_t unsafeAsInteger() const {
521 return static_cast<uint64_t>(unsafeAsUIntPtr());
522 }
523 // Inline mark bitmap access requires direct pointer arithmetic.
524 uintptr_t unsafeAsUIntPtr() const {
525 MOZ_ASSERT(asCell());
526 MOZ_ASSERT(!js::gc::IsInsideNursery(asCell()));
527 return reinterpret_cast<uintptr_t>(asCell());
528 }
529
530 MOZ_ALWAYS_INLINE bool mayBeOwnedByOtherRuntime() const {
531 if (!is<JSString>() && !is<JS::Symbol>()) {
532 return false;
533 }
534 if (is<JSString>()) {
535 return JS::shadow::String::isPermanentAtom(asCell());
536 }
537 MOZ_ASSERT(is<JS::Symbol>());
538 return JS::shadow::Symbol::isWellKnownSymbol(asCell());
539 }
540
541 private:
542 static uintptr_t checkedCast(void* p, JS::TraceKind traceKind) {
543 auto* cell = static_cast<js::gc::Cell*>(p);
544 MOZ_ASSERT((uintptr_t(p) & OutOfLineTraceKindMask) == 0);
545 AssertGCThingHasType(cell, traceKind);
546 // Store trace in the bottom bits of pointer for common kinds.
547 uintptr_t kindBits = uintptr_t(traceKind);
548 if (kindBits >= OutOfLineTraceKindMask) {
549 kindBits = OutOfLineTraceKindMask;
550 }
551 return uintptr_t(p) | kindBits;
552 }
553
554 JS::TraceKind outOfLineKind() const;
555
556 uintptr_t ptr;
557 } JS_HAZ_GC_POINTER;
558
559 // Unwraps the given GCCellPtr, calls the functor |f| with a template argument
560 // of the actual type of the pointer, and returns the result.
561 template <typename F>
562 auto MapGCThingTyped(GCCellPtr thing, F&& f) {
563 switch (thing.kind()) {
564 #define JS_EXPAND_DEF(name, type, _, _1) \
565 case JS::TraceKind::name: \
566 return f(&thing.as<type>());
567 JS_FOR_EACH_TRACEKIND(JS_EXPAND_DEF);
568 #undef JS_EXPAND_DEF
569 default:
570 MOZ_CRASH("Invalid trace kind in MapGCThingTyped for GCCellPtr.");
571 }
572 }
573
574 // Unwraps the given GCCellPtr and calls the functor |f| with a template
575 // argument of the actual type of the pointer. Doesn't return anything.
576 template <typename F>
577 void ApplyGCThingTyped(GCCellPtr thing, F&& f) {
578 // This function doesn't do anything but is supplied for symmetry with other
579 // MapGCThingTyped/ApplyGCThingTyped implementations that have to wrap the
580 // functor to return a dummy value that is ignored.
581 MapGCThingTyped(thing, f);
582 }
583
584 } /* namespace JS */
585
586 namespace js {
587 namespace gc {
588
589 namespace detail {
590
591 // `addr` must be an address within GC-controlled memory. Note that it cannot
592 // point just past GC-controlled memory.
593 static MOZ_ALWAYS_INLINE ChunkBase* GetGCAddressChunkBase(const void* addr) {
594 MOZ_ASSERT(addr);
595 auto* chunk = reinterpret_cast<ChunkBase*>(uintptr_t(addr) & ~ChunkMask);
596 MOZ_ASSERT(chunk->runtime);
597 MOZ_ASSERT(chunk->kind != ChunkKind::Invalid);
598 return chunk;
599 }
600
601 static MOZ_ALWAYS_INLINE ChunkBase* GetCellChunkBase(const Cell* cell) {
602 return GetGCAddressChunkBase(cell);
603 }
604
605 static MOZ_ALWAYS_INLINE ArenaChunkBase* GetCellChunkBase(
606 const TenuredCell* cell) {
607 MOZ_ASSERT(cell);
608 auto* chunk = reinterpret_cast<ArenaChunkBase*>(uintptr_t(cell) & ~ChunkMask);
609 MOZ_ASSERT(chunk->runtime);
610 MOZ_ASSERT(chunk->kind == ChunkKind::TenuredArenas);
611 return chunk;
612 }
613
614 static MOZ_ALWAYS_INLINE JS::Zone* GetTenuredGCThingZone(const void* ptr) {
615 // This takes a void* because the compiler can't see type relationships in
616 // this header. |ptr| must be a pointer to a tenured GC thing.
617 MOZ_ASSERT(ptr);
618 const uintptr_t zone_addr = (uintptr_t(ptr) & ~ArenaMask) | ArenaZoneOffset;
619 return *reinterpret_cast<JS::Zone**>(zone_addr);
620 }
621
622 static MOZ_ALWAYS_INLINE bool TenuredCellIsMarkedBlack(
623 const TenuredCell* cell) {
624 MOZ_ASSERT(cell);
625 MOZ_ASSERT(!js::gc::IsInsideNursery(cell));
626
627 ArenaChunkBase* chunk = GetCellChunkBase(cell);
628 return chunk->markBits.isMarkedBlack(cell);
629 }
630
631 static MOZ_ALWAYS_INLINE bool NonBlackCellIsMarkedGray(
632 const TenuredCell* cell) {
633 // Return true if GrayOrBlackBit is set. Callers should check BlackBit first.
634
635 MOZ_ASSERT(cell);
636 MOZ_ASSERT(!js::gc::IsInsideNursery(cell));
637 MOZ_ASSERT(!TenuredCellIsMarkedBlack(cell));
638
639 ArenaChunkBase* chunk = GetCellChunkBase(cell);
640 return chunk->markBits.markBit(cell, ColorBit::GrayOrBlackBit);
641 }
642
643 static MOZ_ALWAYS_INLINE bool TenuredCellIsMarkedGray(const TenuredCell* cell) {
644 MOZ_ASSERT(cell);
645 MOZ_ASSERT(!js::gc::IsInsideNursery(cell));
646 ArenaChunkBase* chunk = GetCellChunkBase(cell);
647 return chunk->markBits.isMarkedGray(cell);
648 }
649
650 static MOZ_ALWAYS_INLINE bool CellIsMarkedGray(const Cell* cell) {
651 MOZ_ASSERT(cell);
652 if (js::gc::IsInsideNursery(cell)) {
653 return false;
654 }
655 return TenuredCellIsMarkedGray(reinterpret_cast<const TenuredCell*>(cell));
656 }
657
658 extern JS_PUBLIC_API bool CanCheckGrayBits(const TenuredCell* cell);
659
660 extern JS_PUBLIC_API bool CellIsMarkedGrayIfKnown(const TenuredCell* cell);
661
662 #ifdef DEBUG
663 extern JS_PUBLIC_API void AssertCellIsNotGray(const Cell* cell);
664
665 extern JS_PUBLIC_API bool ObjectIsMarkedBlack(const JSObject* obj);
666 #endif
667
668 MOZ_ALWAYS_INLINE bool ChunkPtrHasStoreBuffer(const void* ptr) {
669 return GetGCAddressChunkBase(ptr)->storeBuffer;
670 }
671
672 } /* namespace detail */
673
674 MOZ_ALWAYS_INLINE bool IsInsideNursery(const Cell* cell) {
675 MOZ_ASSERT(cell);
676 return detail::ChunkPtrHasStoreBuffer(cell);
677 }
678
679 MOZ_ALWAYS_INLINE bool IsInsideNursery(const TenuredCell* cell) {
680 MOZ_ASSERT(cell);
681 MOZ_ASSERT(!IsInsideNursery(reinterpret_cast<const Cell*>(cell)));
682 return false;
683 }
684
685 // Return whether |cell| is in the region of the nursery currently being
686 // collected.
687 MOZ_ALWAYS_INLINE bool InCollectedNurseryRegion(const Cell* cell) {
688 MOZ_ASSERT(cell);
689 return detail::GetCellChunkBase(cell)->getKind() ==
690 ChunkKind::NurseryFromSpace;
691 }
692
693 // Allow use before the compiler knows the derivation of JSObject, JSString, and
694 // JS::BigInt.
695 MOZ_ALWAYS_INLINE bool IsInsideNursery(const JSObject* obj) {
696 return IsInsideNursery(reinterpret_cast<const Cell*>(obj));
697 }
698 MOZ_ALWAYS_INLINE bool IsInsideNursery(const JSString* str) {
699 return IsInsideNursery(reinterpret_cast<const Cell*>(str));
700 }
701 MOZ_ALWAYS_INLINE bool IsInsideNursery(const JS::BigInt* bi) {
702 return IsInsideNursery(reinterpret_cast<const Cell*>(bi));
703 }
704 MOZ_ALWAYS_INLINE bool InCollectedNurseryRegion(const JSObject* obj) {
705 return InCollectedNurseryRegion(reinterpret_cast<const Cell*>(obj));
706 }
707
708 MOZ_ALWAYS_INLINE bool IsCellPointerValid(const void* ptr) {
709 auto addr = uintptr_t(ptr);
710 if (addr < ChunkSize || addr % CellAlignBytes != 0) {
711 return false;
712 }
713
714 auto* cell = reinterpret_cast<const Cell*>(ptr);
715 if (!IsInsideNursery(cell)) {
716 return detail::GetTenuredGCThingZone(cell) != nullptr;
717 }
718
719 return true;
720 }
721
722 MOZ_ALWAYS_INLINE bool IsCellPointerValidOrNull(const void* cell) {
723 if (!cell) {
724 return true;
725 }
726 return IsCellPointerValid(cell);
727 }
728
729 } /* namespace gc */
730 } /* namespace js */
731
732 namespace JS {
733
734 extern JS_PUBLIC_API Zone* GetTenuredGCThingZone(GCCellPtr thing);
735
736 extern JS_PUBLIC_API Zone* GetNurseryCellZone(js::gc::Cell* cell);
737
738 static MOZ_ALWAYS_INLINE Zone* GetGCThingZone(GCCellPtr thing) {
739 if (!js::gc::IsInsideNursery(thing.asCell())) {
740 return js::gc::detail::GetTenuredGCThingZone(thing.asCell());
741 }
742
743 return GetNurseryCellZone(thing.asCell());
744 }
745
746 static MOZ_ALWAYS_INLINE Zone* GetStringZone(JSString* str) {
747 if (!js::gc::IsInsideNursery(str)) {
748 return js::gc::detail::GetTenuredGCThingZone(str);
749 }
750
751 return GetNurseryCellZone(reinterpret_cast<js::gc::Cell*>(str));
752 }
753
754 extern JS_PUBLIC_API Zone* GetObjectZone(JSObject* obj);
755
756 static MOZ_ALWAYS_INLINE bool GCThingIsMarkedGray(GCCellPtr thing) {
757 js::gc::Cell* cell = thing.asCell();
758 if (IsInsideNursery(cell)) {
759 return false;
760 }
761
762 auto* tenuredCell = reinterpret_cast<js::gc::TenuredCell*>(cell);
763 return js::gc::detail::CellIsMarkedGrayIfKnown(tenuredCell);
764 }
765
766 // Specialised gray marking check for use by the cycle collector. This is not
767 // called during incremental GC or when the gray bits are invalid.
768 static MOZ_ALWAYS_INLINE bool GCThingIsMarkedGrayInCC(GCCellPtr thing) {
769 js::gc::Cell* cell = thing.asCell();
770 if (IsInsideNursery(cell)) {
771 return false;
772 }
773
774 auto* tenuredCell = reinterpret_cast<js::gc::TenuredCell*>(cell);
775 if (!js::gc::detail::TenuredCellIsMarkedGray(tenuredCell)) {
776 return false;
777 }
778
779 MOZ_ASSERT(js::gc::detail::CanCheckGrayBits(tenuredCell));
780
781 return true;
782 }
783
784 extern JS_PUBLIC_API JS::TraceKind GCThingTraceKind(void* thing);
785
786 /*
787 * Returns true when writes to GC thing pointers (and reads from weak pointers)
788 * must call an incremental barrier. This is generally only true when running
789 * mutator code in-between GC slices. At other times, the barrier may be elided
790 * for performance.
791 */
792 extern JS_PUBLIC_API bool IsIncrementalBarrierNeeded(JSContext* cx);
793
794 /*
795 * Notify the GC that a reference to a JSObject is about to be overwritten.
796 * This method must be called if IsIncrementalBarrierNeeded.
797 */
798 extern JS_PUBLIC_API void IncrementalPreWriteBarrier(JSObject* obj);
799
800 /*
801 * Notify the GC that a reference to a tenured GC cell is about to be
802 * overwritten. This method must be called if IsIncrementalBarrierNeeded.
803 */
804 extern JS_PUBLIC_API void IncrementalPreWriteBarrier(GCCellPtr thing);
805
806 /**
807 * Unsets the gray bit for anything reachable from |thing|. |kind| should not be
808 * JS::TraceKind::Shape. |thing| should be non-null. The return value indicates
809 * if anything was unmarked.
810 */
811 extern JS_PUBLIC_API bool UnmarkGrayGCThingRecursively(GCCellPtr thing);
812
813 } // namespace JS
814
815 namespace js {
816 namespace gc {
817
818 extern JS_PUBLIC_API void PerformIncrementalReadBarrier(JS::GCCellPtr thing);
819
820 static MOZ_ALWAYS_INLINE void ExposeGCThingToActiveJS(JS::GCCellPtr thing) {
821 // TODO: I'd like to assert !RuntimeHeapIsBusy() here but this gets
822 // called while we are tracing the heap, e.g. during memory reporting
823 // (see bug 1313318).
824 MOZ_ASSERT(!JS::RuntimeHeapIsCollecting());
825
826 // GC things residing in the nursery cannot be gray: they have no mark bits.
827 // All live objects in the nursery are moved to tenured at the beginning of
828 // each GC slice, so the gray marker never sees nursery things.
829 if (IsInsideNursery(thing.asCell())) {
830 return;
831 }
832
833 auto* cell = reinterpret_cast<TenuredCell*>(thing.asCell());
834 if (detail::TenuredCellIsMarkedBlack(cell)) {
835 return;
836 }
837
838 // GC things owned by other runtimes are always black.
839 MOZ_ASSERT(!thing.mayBeOwnedByOtherRuntime());
840
841 auto* zone = JS::shadow::Zone::from(detail::GetTenuredGCThingZone(cell));
842 if (zone->needsIncrementalBarrier()) {
843 PerformIncrementalReadBarrier(thing);
844 } else if (!zone->isGCPreparing() && detail::NonBlackCellIsMarkedGray(cell)) {
845 MOZ_ALWAYS_TRUE(JS::UnmarkGrayGCThingRecursively(thing));
846 }
847
848 MOZ_ASSERT_IF(!zone->isGCPreparing(), !detail::TenuredCellIsMarkedGray(cell));
849 }
850
851 static MOZ_ALWAYS_INLINE void IncrementalReadBarrier(JS::GCCellPtr thing) {
852 // This is a lighter version of ExposeGCThingToActiveJS that doesn't do gray
853 // unmarking.
854
855 if (IsInsideNursery(thing.asCell())) {
856 return;
857 }
858
859 auto* cell = reinterpret_cast<TenuredCell*>(thing.asCell());
860 auto* zone = JS::shadow::Zone::from(detail::GetTenuredGCThingZone(cell));
861 if (zone->needsIncrementalBarrier() &&
862 !detail::TenuredCellIsMarkedBlack(cell)) {
863 // GC things owned by other runtimes are always black.
864 MOZ_ASSERT(!thing.mayBeOwnedByOtherRuntime());
865 PerformIncrementalReadBarrier(thing);
866 }
867 }
868
869 template <typename T>
870 extern JS_PUBLIC_API bool EdgeNeedsSweepUnbarrieredSlow(T* thingp);
871
872 static MOZ_ALWAYS_INLINE bool EdgeNeedsSweepUnbarriered(JSObject** objp) {
873 // This function does not handle updating nursery pointers. Raw JSObject
874 // pointers should be updated separately or replaced with
875 // JS::Heap<JSObject*> which handles this automatically.
876 MOZ_ASSERT(!JS::RuntimeHeapIsMinorCollecting());
877 if (IsInsideNursery(*objp)) {
878 return false;
879 }
880
881 auto zone = JS::shadow::Zone::from(detail::GetTenuredGCThingZone(*objp));
882 if (!zone->isGCSweepingOrCompacting()) {
883 return false;
884 }
885
886 return EdgeNeedsSweepUnbarrieredSlow(objp);
887 }
888
889 /*
890 * Sample data about internally mapped memory. This includes all GC heap
891 * allocations (and excludes js_alloc allocations).
892 */
893 struct ProfilerMemoryCounts {
894 size_t bytes = 0;
895 uint64_t operations = 0;
896 };
897 JS_PUBLIC_API ProfilerMemoryCounts GetProfilerMemoryCounts();
898
899 } // namespace gc
900 } // namespace js
901
902 namespace JS {
903
904 /*
905 * This should be called when an object that is marked gray is exposed to the JS
906 * engine (by handing it to running JS code or writing it into live JS
907 * data). During incremental GC, since the gray bits haven't been computed yet,
908 * we conservatively mark the object black.
909 */
910 static MOZ_ALWAYS_INLINE void ExposeObjectToActiveJS(JSObject* obj) {
911 MOZ_ASSERT(obj);
912 MOZ_ASSERT(!js::gc::EdgeNeedsSweepUnbarrieredSlow(&obj));
913 js::gc::ExposeGCThingToActiveJS(GCCellPtr(obj));
914 }
915
916 } /* namespace JS */
917
918 #endif /* js_HeapAPI_h */