Debian Codegraph @

js/src/gc/Tenuring.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 /*
8 * Implementation of nursery eviction (tenuring).
9 */
10
11 #include "gc/Tenuring.h"
12
13 #include "gc/Cell.h"
14 #include "gc/GCInternals.h"
15 #include "gc/GCProbes.h"
16 #include "gc/Pretenuring.h"
17 #include "gc/Zone.h"
18 #include "jit/JitCode.h"
19 #include "js/TypeDecls.h"
20 #include "proxy/Proxy.h"
21 #include "vm/BigIntType.h"
22 #include "vm/JSScript.h"
23 #include "vm/NativeObject.h"
24 #include "vm/Runtime.h"
25 #include "vm/TypedArrayObject.h"
26
27 #include "gc/Heap-inl.h"
28 #include "gc/Marking-inl.h"
29 #include "gc/ObjectKind-inl.h"
30 #include "gc/StoreBuffer-inl.h"
31 #include "gc/TraceMethods-inl.h"
32 #include "vm/JSObject-inl.h"
33 #include "vm/PlainObject-inl.h"
34 #include "vm/StringType-inl.h"
35 using namespace js;
36 using namespace js::gc;
37
38 constexpr size_t MAX_DEDUPLICATABLE_STRING_LENGTH = 500;
39
40 #ifdef JS_GC_ZEAL
41 class js::gc::PromotionStats {
42 static constexpr size_t AttentionThreshold = 100;
43
44 size_t objectCount = 0;
45 size_t stringCount = 0;
46 size_t bigIntCount = 0;
47
48 using BaseShapeCountMap =
49 HashMap<BaseShape*, size_t, PointerHasher<BaseShape*>, SystemAllocPolicy>;
50 BaseShapeCountMap objectCountByBaseShape;
51
52 using AllocKindCountArray =
53 mozilla::EnumeratedArray<AllocKind, size_t, size_t(AllocKind::LIMIT)>;
54 AllocKindCountArray stringCountByKind;
55
56 bool hadOOM = false;
57
58 struct LabelAndCount {
59 char label[32] = {'\0'};
60 size_t count = 0;
61 };
62 using CountsVector = Vector<LabelAndCount, 0, SystemAllocPolicy>;
63
64 public:
65 void notePromotedObject(JSObject* obj);
66 void notePromotedString(JSString* str);
67 void notePromotedBigInt(JS::BigInt* bi);
68
69 bool shouldPrintReport() const;
70 void printReport(JSContext* cx, const JS::AutoRequireNoGC& nogc);
71
72 private:
73 void printObjectCounts(JSContext* cx, const JS::AutoRequireNoGC& nogc);
74 void printStringCounts();
75
76 void printCounts(CountsVector& counts, size_t total);
77 void printLine(const char* name, size_t count, size_t total);
78
79 UniqueChars getConstructorName(JSContext* cx, BaseShape* baseShape,
80 const JS::AutoRequireNoGC& nogc);
81 };
82 #endif // JS_GC_ZEAL
83
84 TenuringTracer::TenuringTracer(JSRuntime* rt, Nursery* nursery,
85 bool tenureEverything)
86 : JSTracer(rt, JS::TracerKind::Tenuring,
87 JS::WeakMapTraceAction::TraceKeysAndValues),
88 nursery_(*nursery),
89 tenureEverything(tenureEverything) {
90 stringDeDupSet.emplace();
91 }
92
93 TenuringTracer::~TenuringTracer() = default;
94
95 size_t TenuringTracer::getPromotedSize() const {
96 return promotedSize + promotedCells * sizeof(NurseryCellHeader);
97 }
98
99 size_t TenuringTracer::getPromotedCells() const { return promotedCells; }
100
101 void TenuringTracer::onObjectEdge(JSObject** objp, const char* name) {
102 JSObject* obj = *objp;
103 if (!nursery_.inCollectedRegion(obj)) {
104 MOZ_ASSERT(!obj->isForwarded());
105 return;
106 }
107
108 *objp = promoteOrForward(obj);
109 MOZ_ASSERT(!(*objp)->isForwarded());
110 }
111
112 JSObject* TenuringTracer::promoteOrForward(JSObject* obj) {
113 MOZ_ASSERT(nursery_.inCollectedRegion(obj));
114
115 if (obj->isForwarded()) {
116 const gc::RelocationOverlay* overlay = gc::RelocationOverlay::fromCell(obj);
117 obj = static_cast<JSObject*>(overlay->forwardingAddress());
118 if (IsInsideNursery(obj)) {
119 promotedToNursery = true;
120 }
121 return obj;
122 }
123
124 return promoteObject(obj);
125 }
126
127 JSObject* TenuringTracer::promoteObject(JSObject* obj) {
128 MOZ_ASSERT(IsInsideNursery(obj));
129 MOZ_ASSERT(!obj->isForwarded());
130
131 #ifdef JS_GC_ZEAL
132 if (promotionStats) {
133 promotionStats->notePromotedObject(obj);
134 }
135 #endif
136
137 // Take a fast path for promoting a plain object as this is by far the most
138 // common case.
139 if (obj->is<PlainObject>()) {
140 return promotePlainObject(&obj->as<PlainObject>());
141 }
142
143 return promoteObjectSlow(obj);
144 }
145
146 void TenuringTracer::onStringEdge(JSString** strp, const char* name) {
147 JSString* str = *strp;
148 if (!nursery_.inCollectedRegion(str)) {
149 return;
150 }
151
152 *strp = promoteOrForward(str);
153 }
154
155 JSString* TenuringTracer::promoteOrForward(JSString* str) {
156 MOZ_ASSERT(nursery_.inCollectedRegion(str));
157
158 if (str->isForwarded()) {
159 const gc::RelocationOverlay* overlay = gc::RelocationOverlay::fromCell(str);
160 str = static_cast<JSString*>(overlay->forwardingAddress());
161 if (IsInsideNursery(str)) {
162 promotedToNursery = true;
163 }
164 return str;
165 }
166
167 return promoteString(str);
168 }
169
170 void TenuringTracer::onBigIntEdge(JS::BigInt** bip, const char* name) {
171 JS::BigInt* bi = *bip;
172 if (!nursery_.inCollectedRegion(bi)) {
173 return;
174 }
175
176 *bip = promoteOrForward(bi);
177 }
178
179 JS::BigInt* TenuringTracer::promoteOrForward(JS::BigInt* bi) {
180 MOZ_ASSERT(nursery_.inCollectedRegion(bi));
181
182 if (bi->isForwarded()) {
183 const gc::RelocationOverlay* overlay = gc::RelocationOverlay::fromCell(bi);
184 bi = static_cast<JS::BigInt*>(overlay->forwardingAddress());
185 if (IsInsideNursery(bi)) {
186 promotedToNursery = true;
187 }
188 return bi;
189 }
190
191 return promoteBigInt(bi);
192 }
193
194 // Ignore edges to cell kinds that are not allocated in the nursery.
195 void TenuringTracer::onSymbolEdge(JS::Symbol** symp, const char* name) {}
196 void TenuringTracer::onScriptEdge(BaseScript** scriptp, const char* name) {}
197 void TenuringTracer::onShapeEdge(Shape** shapep, const char* name) {}
198 void TenuringTracer::onRegExpSharedEdge(RegExpShared** sharedp,
199 const char* name) {}
200 void TenuringTracer::onBaseShapeEdge(BaseShape** basep, const char* name) {}
201 void TenuringTracer::onGetterSetterEdge(GetterSetter** gsp, const char* name) {}
202 void TenuringTracer::onPropMapEdge(PropMap** mapp, const char* name) {}
203 void TenuringTracer::onJitCodeEdge(jit::JitCode** codep, const char* name) {}
204 void TenuringTracer::onScopeEdge(Scope** scopep, const char* name) {}
205 void TenuringTracer::onSmallBufferEdge(SmallBuffer** sizedp, const char* name) {
206 }
207
208 void TenuringTracer::traverse(JS::Value* thingp) {
209 MOZ_ASSERT(!nursery().inCollectedRegion(thingp));
210
211 Value value = *thingp;
212 CheckTracedThing(this, value);
213
214 if (!value.isGCThing()) {
215 return;
216 }
217
218 Cell* cell = value.toGCThing();
219 if (!nursery_.inCollectedRegion(cell)) {
220 return;
221 }
222
223 if (cell->isForwarded()) {
224 const gc::RelocationOverlay* overlay =
225 gc::RelocationOverlay::fromCell(cell);
226 Cell* target = overlay->forwardingAddress();
227 thingp->changeGCThingPayload(target);
228 if (IsInsideNursery(target)) {
229 promotedToNursery = true;
230 }
231 return;
232 }
233
234 // We only care about a few kinds of GC thing here and this generates much
235 // tighter code than using MapGCThingTyped.
236 if (value.isObject()) {
237 JSObject* obj = promoteObject(&value.toObject());
238 MOZ_ASSERT(obj != &value.toObject());
239 *thingp = JS::ObjectValue(*obj);
240 return;
241 }
242 if (value.isString()) {
243 JSString* str = promoteString(value.toString());
244 MOZ_ASSERT(str != value.toString());
245 *thingp = JS::StringValue(str);
246 return;
247 }
248 MOZ_ASSERT(value.isBigInt());
249 JS::BigInt* bi = promoteBigInt(value.toBigInt());
250 MOZ_ASSERT(bi != value.toBigInt());
251 *thingp = JS::BigIntValue(bi);
252 }
253
254 void TenuringTracer::traverse(wasm::AnyRef* thingp) {
255 MOZ_ASSERT(!nursery().inCollectedRegion(thingp));
256
257 wasm::AnyRef value = *thingp;
258 CheckTracedThing(this, value);
259
260 Cell* cell = value.toGCThing();
261 if (!nursery_.inCollectedRegion(cell)) {
262 return;
263 }
264
265 wasm::AnyRef post = wasm::AnyRef::invalid();
266 switch (value.kind()) {
267 case wasm::AnyRefKind::Object: {
268 JSObject* obj = promoteOrForward(&value.toJSObject());
269 MOZ_ASSERT(obj != &value.toJSObject());
270 post = wasm::AnyRef::fromJSObject(*obj);
271 break;
272 }
273 case wasm::AnyRefKind::String: {
274 JSString* str = promoteOrForward(value.toJSString());
275 MOZ_ASSERT(str != value.toJSString());
276 post = wasm::AnyRef::fromJSString(str);
277 break;
278 }
279 case wasm::AnyRefKind::I31:
280 case wasm::AnyRefKind::Null: {
281 // This function must only be called for GC things.
282 MOZ_CRASH();
283 }
284 }
285
286 *thingp = post;
287 }
288
289 class MOZ_RAII TenuringTracer::AutoPromotedAnyToNursery {
290 public:
291 explicit AutoPromotedAnyToNursery(TenuringTracer& trc) : trc_(trc) {
292 trc.promotedToNursery = false;
293 }
294 explicit operator bool() const { return trc_.promotedToNursery; }
295
296 private:
297 TenuringTracer& trc_;
298 };
299
300 template <typename T>
301 void js::gc::StoreBuffer::MonoTypeBuffer<T>::trace(TenuringTracer& mover,
302 StoreBuffer* owner) {
303 mozilla::ReentrancyGuard g(*owner);
304 MOZ_ASSERT(owner->isEnabled());
305
306 if (last_) {
307 last_.trace(mover);
308 }
309
310 for (typename StoreSet::Range r = stores_.all(); !r.empty(); r.popFront()) {
311 r.front().trace(mover);
312 }
313 }
314
315 namespace js::gc {
316 template void StoreBuffer::MonoTypeBuffer<StoreBuffer::ValueEdge>::trace(
317 TenuringTracer&, StoreBuffer* owner);
318 template void StoreBuffer::MonoTypeBuffer<StoreBuffer::SlotsEdge>::trace(
319 TenuringTracer&, StoreBuffer* owner);
320 template void StoreBuffer::MonoTypeBuffer<StoreBuffer::WasmAnyRefEdge>::trace(
321 TenuringTracer&, StoreBuffer* owner);
322 template struct StoreBuffer::MonoTypeBuffer<StoreBuffer::StringPtrEdge>;
323 template struct StoreBuffer::MonoTypeBuffer<StoreBuffer::BigIntPtrEdge>;
324 template struct StoreBuffer::MonoTypeBuffer<StoreBuffer::ObjectPtrEdge>;
325 } // namespace js::gc
326
327 void js::gc::StoreBuffer::SlotsEdge::trace(TenuringTracer& mover) const {
328 NativeObject* obj = object();
329 MOZ_ASSERT(IsCellPointerValid(obj));
330
331 // Beware JSObject::swap exchanging a native object for a non-native one.
332 if (!obj->is<NativeObject>()) {
333 return;
334 }
335
336 MOZ_ASSERT(!IsInsideNursery(obj), "obj shouldn't live in nursery.");
337
338 TenuringTracer::AutoPromotedAnyToNursery promotedToNursery(mover);
339
340 if (kind() == ElementKind) {
341 uint32_t initLen = obj->getDenseInitializedLength();
342 uint32_t numShifted = obj->getElementsHeader()->numShiftedElements();
343 uint32_t clampedStart = start_;
344 clampedStart = numShifted < clampedStart ? clampedStart - numShifted : 0;
345 clampedStart = std::min(clampedStart, initLen);
346 uint32_t clampedEnd = start_ + count_;
347 clampedEnd = numShifted < clampedEnd ? clampedEnd - numShifted : 0;
348 clampedEnd = std::min(clampedEnd, initLen);
349 MOZ_ASSERT(clampedStart <= clampedEnd);
350 auto* slotStart =
351 static_cast<HeapSlot*>(obj->getDenseElements() + clampedStart);
352 uint32_t nslots = clampedEnd - clampedStart;
353 mover.traceObjectElements(slotStart->unbarrieredAddress(), nslots);
354 } else {
355 uint32_t start = std::min(start_, obj->slotSpan());
356 uint32_t end = std::min(start_ + count_, obj->slotSpan());
357 MOZ_ASSERT(start <= end);
358 mover.traceObjectSlots(obj, start, end);
359 }
360
361 if (promotedToNursery) {
362 mover.runtime()->gc.storeBuffer().putSlot(obj, kind(), start_, count_);
363 }
364 }
365
366 static inline void TraceWholeCell(TenuringTracer& mover, JSObject* object) {
367 mover.traceObject(object);
368 }
369
370 void JSDependentString::setBase(JSLinearString* newBase) {
371 // This compiles down to a single assignment, with no type test.
372 if (isAtomRef()) {
373 MOZ_ASSERT(newBase->isAtom());
374 d.s.u3.atom = &newBase->asAtom();
375 } else {
376 MOZ_ASSERT(newBase->canOwnDependentChars());
377 d.s.u3.base = newBase;
378 }
379
380 if (isTenured() && !newBase->isTenured()) {
381 MOZ_ASSERT(!InCollectedNurseryRegion(newBase));
382 newBase->storeBuffer()->putWholeCell(this);
383 }
384 }
385
386 static void TraceWholeCell(TenuringTracer& mover, JSString* str) {
387 if (str->isDependent() && !str->isAtomRef()) {
388 // For tenured dependent strings -> nursery base string edges, promote the
389 // base immediately and then use its old chars pointer to find the offset
390 // needed to update the dependent string's pointer if the base string moves
391 // its chars.
392 JSDependentString* dep = &str->asDependent();
393 JSLinearString* base = dep->rootBaseDuringMinorGC();
394 if (InCollectedNurseryRegion(base)) {
395 mover.promoteOrForward(base);
396 dep->updateToPromotedBase(base);
397 } else {
398 // Set base to (promoted) root base.
399 dep->setBase(base);
400 }
401 return;
402 }
403
404 str->traceChildren(&mover);
405 }
406
407 static inline void TraceWholeCell(TenuringTracer& mover, BaseScript* script) {
408 script->traceChildren(&mover);
409 }
410
411 static inline void TraceWholeCell(TenuringTracer& mover,
412 jit::JitCode* jitcode) {
413 jitcode->traceChildren(&mover);
414 }
415
416 template <typename T>
417 bool TenuringTracer::traceBufferedCells(Arena* arena, ArenaCellSet* cells) {
418 for (size_t i = 0; i < MaxArenaCellIndex; i += cells->BitsPerWord) {
419 ArenaCellSet::WordT bitset = cells->getWord(i / cells->BitsPerWord);
420 while (bitset) {
421 size_t bit = i + js::detail::CountTrailingZeroes(bitset);
422 bitset &= bitset - 1; // Clear the low bit.
423
424 auto cell =
425 reinterpret_cast<T*>(uintptr_t(arena) + ArenaCellIndexBytes * bit);
426
427 TenuringTracer::AutoPromotedAnyToNursery promotedToNursery(*this);
428
429 TraceWholeCell(*this, cell);
430
431 if (promotedToNursery) {
432 runtime()->gc.storeBuffer().putWholeCell(cell);
433 }
434 }
435 }
436
437 return false;
438 }
439
440 bool ArenaCellSet::trace(TenuringTracer& mover) {
441 check();
442
443 arena->bufferedCells() = &ArenaCellSet::Empty;
444
445 JS::TraceKind kind = MapAllocToTraceKind(arena->getAllocKind());
446 switch (kind) {
447 case JS::TraceKind::Object:
448 return mover.traceBufferedCells<JSObject>(arena, this);
449 break;
450 case JS::TraceKind::String:
451 return mover.traceBufferedCells<JSString>(arena, this);
452 break;
453 case JS::TraceKind::Script:
454 return mover.traceBufferedCells<BaseScript>(arena, this);
455 break;
456 case JS::TraceKind::JitCode:
457 return mover.traceBufferedCells<jit::JitCode>(arena, this);
458 break;
459 default:
460 MOZ_CRASH("Unexpected trace kind");
461 }
462 }
463
464 void js::gc::StoreBuffer::WholeCellBuffer::trace(TenuringTracer& mover,
465 StoreBuffer* owner) {
466 MOZ_ASSERT(owner->isEnabled());
467
468 ArenaCellSet** sweepListTail = &sweepHead_;
469
470 for (LifoAlloc::Enum e(*storage_); !e.empty();) {
471 ArenaCellSet* cellSet = e.read<ArenaCellSet>();
472 bool needsSweep = cellSet->trace(mover);
473 if (needsSweep) {
474 MOZ_ASSERT(!*sweepListTail);
475 *sweepListTail = cellSet;
476 sweepListTail = &cellSet->next;
477 }
478 }
479 }
480
481 namespace js::gc {
482 // StringRelocationOverlay assists with updating the string chars
483 // pointers of dependent strings when their base strings are
484 // deduplicated. It stores:
485 // - nursery chars of potential root base strings
486 // - the original pointer to the original root base (still in the nursery if it
487 // was originally in the nursery, even if it has been forwarded to a promoted
488 // string now).
489 //
490 // StringRelocationOverlay exploits the fact that the 3rd word of a JSString's
491 // RelocationOverlay is not utilized and can be used to store extra information.
492 class StringRelocationOverlay : public RelocationOverlay {
493 union {
494 // nursery chars of a root base
495 const JS::Latin1Char* nurseryCharsLatin1;
496 const char16_t* nurseryCharsTwoByte;
497
498 // The nursery base can be forwarded, which becomes a string relocation
499 // overlay, or it is not yet forwarded and is simply the (nursery) base
500 // string.
501 JSLinearString* nurseryBaseOrRelocOverlay;
502
503 // For ropes. Present only to simplify the generated code.
504 JSString* unusedLeftChild;
505 };
506
507 public:
508 StringRelocationOverlay(Cell* dst, const JS::Latin1Char* chars)
509 : RelocationOverlay(dst), nurseryCharsLatin1(chars) {}
510
511 StringRelocationOverlay(Cell* dst, const char16_t* chars)
512 : RelocationOverlay(dst), nurseryCharsTwoByte(chars) {}
513
514 StringRelocationOverlay(Cell* dst, JSLinearString* origBase)
515 : RelocationOverlay(dst), nurseryBaseOrRelocOverlay(origBase) {}
516
517 StringRelocationOverlay(Cell* dst, JSString* origLeftChild)
518 : RelocationOverlay(dst), unusedLeftChild(origLeftChild) {}
519
520 static const StringRelocationOverlay* fromCell(const Cell* cell) {
521 return static_cast<const StringRelocationOverlay*>(cell);
522 }
523
524 static StringRelocationOverlay* fromCell(Cell* cell) {
525 return static_cast<StringRelocationOverlay*>(cell);
526 }
527
528 void setNext(StringRelocationOverlay* next) {
529 RelocationOverlay::setNext(next);
530 }
531
532 StringRelocationOverlay* next() const {
533 MOZ_ASSERT(isForwarded());
534 return (StringRelocationOverlay*)next_;
535 }
536
537 template <typename CharT>
538 MOZ_ALWAYS_INLINE const CharT* savedNurseryChars() const {
539 if constexpr (std::is_same_v<CharT, JS::Latin1Char>) {
540 return savedNurseryCharsLatin1();
541 } else {
542 return savedNurseryCharsTwoByte();
543 }
544 }
545
546 const MOZ_ALWAYS_INLINE JS::Latin1Char* savedNurseryCharsLatin1() const {
547 MOZ_ASSERT(!forwardingAddress()->as<JSString>()->hasBase());
548 return nurseryCharsLatin1;
549 }
550
551 const MOZ_ALWAYS_INLINE char16_t* savedNurseryCharsTwoByte() const {
552 MOZ_ASSERT(!forwardingAddress()->as<JSString>()->hasBase());
553 return nurseryCharsTwoByte;
554 }
555
556 JSLinearString* savedNurseryBaseOrRelocOverlay() const {
557 MOZ_ASSERT(forwardingAddress()->as<JSString>()->hasBase());
558 return nurseryBaseOrRelocOverlay;
559 }
560
561 // Transform a nursery string to a StringRelocationOverlay that is forwarded
562 // to a promoted string.
563 inline static StringRelocationOverlay* forwardDependentString(JSString* src,
564 Cell* dst);
565
566 // Usually only called on non-dependent strings, except for the case where a
567 // dependent string is converted to a linear string.
568 static StringRelocationOverlay* forwardString(JSString* src, Cell* dst) {
569 MOZ_ASSERT(!src->isForwarded());
570 MOZ_ASSERT(!dst->isForwarded());
571
572 JS::AutoCheckCannotGC nogc;
573
574 // Initialize the overlay for a non-dependent string (that could be the root
575 // base of other strings), remember nursery non-inlined chars.
576 //
577 // Note that this will store the chars pointer even when it is known that it
578 // will never be used (!canOwnDependentChar()), or a left child pointer of
579 // a rope that will never get used, in order to simplify the generated code
580 // to do an unconditional store.
581 //
582 // All of these compile down to
583 // header_.value_ = dst | 1; /* offset 0 */
584 // StringRelocationOverlay.union = d.s.u2; /* offset 16 <- offset 8 */
585 if (src->isLinear()) {
586 if (src->hasTwoByteChars()) {
587 auto* nurseryCharsTwoByte = src->asLinear().twoByteChars(nogc);
588 return new (src) StringRelocationOverlay(dst, nurseryCharsTwoByte);
589 }
590 auto* nurseryCharsLatin1 = src->asLinear().latin1Chars(nogc);
591 return new (src) StringRelocationOverlay(dst, nurseryCharsLatin1);
592 } else {
593 return new (src) StringRelocationOverlay(
594 dst, dst->as<JSString>()->asRope().leftChild());
595 }
596 }
597 };
598
599 /* static */
600 StringRelocationOverlay* StringRelocationOverlay::forwardDependentString(
601 JSString* src, Cell* dst) {
602 MOZ_ASSERT(src->isDependent());
603 MOZ_ASSERT(!src->isForwarded());
604 MOZ_ASSERT(!dst->isForwarded());
605 JSLinearString* origBase = src->asDependent().rootBaseDuringMinorGC();
606 return new (src) StringRelocationOverlay(dst, origBase);
607 }
608
609 } // namespace js::gc
610
611 JSLinearString* JSDependentString::rootBaseDuringMinorGC() {
612 JSLinearString* root = this;
613 while (MaybeForwarded(root)->hasBase()) {
614 if (root->isForwarded()) {
615 root = js::gc::StringRelocationOverlay::fromCell(root)
616 ->savedNurseryBaseOrRelocOverlay();
617 } else {
618 // Possibly nursery or tenured string (not an overlay).
619 root = root->nurseryBaseOrRelocOverlay();
620 }
621 }
622 return root;
623 }
624
625 template <typename CharT>
626 static bool PtrIsWithinRange(const CharT* ptr,
627 const mozilla::Range<const CharT>& valid) {
628 return size_t(ptr - valid.begin().get()) <= valid.length();
629 }
630
631 /* static */
632 template <typename CharT>
633 void JSLinearString::maybeCloneCharsOnPromotionTyped(JSLinearString* str) {
634 MOZ_ASSERT(!InCollectedNurseryRegion(str), "str should have been promoted");
635 MOZ_ASSERT(str->isDependent());
636 JSLinearString* root = str->asDependent().rootBaseDuringMinorGC();
637 if (InCollectedNurseryRegion(root)) {
638 // Can still fixup the original chars pointer.
639 return;
640 }
641
642 // If the base has not moved its chars, continue using them.
643 JS::AutoCheckCannotGC nogc;
644 const CharT* chars = str->chars<CharT>(nogc);
645 if (PtrIsWithinRange(chars, root->range<CharT>(nogc))) {
646 return;
647 }
648
649 // Clone the chars.
650 js::AutoEnterOOMUnsafeRegion oomUnsafe;
651 size_t len = str->length();
652 size_t nbytes = len * sizeof(CharT);
653 CharT* data =
654 str->zone()->pod_arena_malloc<CharT>(js::StringBufferArena, len);
655 if (!data) {
656 oomUnsafe.crash("cloning at-risk dependent string");
657 }
658 js_memcpy(data, chars, nbytes);
659
660 // Overwrite the dest string with a new linear string.
661 new (str) JSLinearString(data, len, false /* hasBuffer */);
662 if (str->isTenured()) {
663 str->zone()->addCellMemory(str, nbytes, js::MemoryUse::StringContents);
664 } else {
665 AutoEnterOOMUnsafeRegion oomUnsafe;
666 JSRuntime* rt = str->runtimeFromAnyThread();
667 if (!rt->gc.nursery().registerMallocedBuffer(data, nbytes)) {
668 oomUnsafe.crash("maybeCloneCharsOnPromotionTyped");
669 }
670 }
671 }
672
673 template void JSLinearString::maybeCloneCharsOnPromotionTyped<JS::Latin1Char>(
674 JSLinearString* str);
675 template void JSLinearString::maybeCloneCharsOnPromotionTyped<char16_t>(
676 JSLinearString* str);
677
678 // Update a promoted dependent string with a nursery base. The base chain will
679 // have been collapsed to a single link, so only the simple case of a promoted
680 // dependent string with a nursery base needs to be considered.
681 template <typename CharT>
682 void JSDependentString::updateToPromotedBaseImpl(JSLinearString* base) {
683 MOZ_ASSERT(!InCollectedNurseryRegion(this));
684 MOZ_ASSERT(IsInsideNursery(base));
685 MOZ_ASSERT(!Forwarded(base)->hasBase(), "base chain should be collapsed");
686 MOZ_ASSERT(base->isForwarded(), "root base should be kept alive");
687 auto* baseOverlay = js::gc::StringRelocationOverlay::fromCell(base);
688 const CharT* oldBaseChars = baseOverlay->savedNurseryChars<CharT>();
689
690 // We have the base's original chars pointer and its current chars pointer.
691 // Update our chars pointer, which is an offset from the original base
692 // chars, and make it point to the same offset within the root's chars.
693 // (Most of the time, the base chars didn't move and so this has no
694 // effect.)
695 const CharT* oldChars = JSString::nonInlineCharsRaw<CharT>();
696 size_t offset = oldChars - oldBaseChars;
697 JSLinearString* promotedBase = Forwarded(base);
698 MOZ_ASSERT(offset < promotedBase->length());
699
700 const CharT* newBaseChars =
701 promotedBase->JSString::nonInlineCharsRaw<CharT>();
702 relocateBaseAndChars(promotedBase, newBaseChars, offset);
703 }
704
705 inline void JSDependentString::updateToPromotedBase(JSLinearString* base) {
706 // The base should have been traced.
707 MOZ_ASSERT(base->isForwarded() || !InCollectedNurseryRegion(base));
708
709 if (hasTwoByteChars()) {
710 updateToPromotedBaseImpl<char16_t>(base);
711 } else {
712 updateToPromotedBaseImpl<JS::Latin1Char>(base);
713 }
714 }
715
716 template <typename T>
717 void js::gc::StoreBuffer::CellPtrEdge<T>::trace(TenuringTracer& mover) const {
718 static_assert(std::is_base_of_v<Cell, T>, "T must be a Cell type");
719 static_assert(!GCTypeIsTenured<T>(), "T must not be a tenured Cell type");
720
721 T* thing = *edge;
722 if (!thing) {
723 return;
724 }
725
726 MOZ_ASSERT(IsCellPointerValid(thing));
727 MOZ_ASSERT(thing->getTraceKind() == JS::MapTypeToTraceKind<T>::kind);
728
729 if (std::is_same_v<JSString, T>) {
730 // Nursery string deduplication requires all tenured string -> nursery
731 // string edges to be registered with the whole cell buffer in order to
732 // correctly set the non-deduplicatable bit.
733 MOZ_ASSERT(!mover.runtime()->gc.isPointerWithinTenuredCell(
734 edge, JS::TraceKind::String));
735 }
736
737 if (!mover.nursery().inCollectedRegion(thing)) {
738 return;
739 }
740
741 *edge = mover.promoteOrForward(thing);
742
743 if (IsInsideNursery(*edge)) {
744 mover.runtime()->gc.storeBuffer().putCell(edge);
745 }
746 }
747
748 void js::gc::StoreBuffer::ValueEdge::trace(TenuringTracer& mover) const {
749 if (!isGCThing()) {
750 return;
751 }
752
753 TenuringTracer::AutoPromotedAnyToNursery promotedToNursery(mover);
754
755 mover.traverse(edge);
756
757 if (promotedToNursery) {
758 mover.runtime()->gc.storeBuffer().putValue(edge);
759 }
760 }
761
762 void js::gc::StoreBuffer::WasmAnyRefEdge::trace(TenuringTracer& mover) const {
763 if (!isGCThing()) {
764 return;
765 }
766
767 TenuringTracer::AutoPromotedAnyToNursery promotedToNursery(mover);
768
769 mover.traverse(edge);
770
771 if (promotedToNursery) {
772 mover.runtime()->gc.storeBuffer().putWasmAnyRef(edge);
773 }
774 }
775
776 // Visit all object children of the object and trace them.
777 void js::gc::TenuringTracer::traceObject(JSObject* obj) {
778 const JSClass* clasp = obj->getClass();
779 MOZ_ASSERT(clasp);
780
781 if (clasp->hasTrace()) {
782 clasp->doTrace(this, obj);
783 }
784
785 if (!obj->is<NativeObject>()) {
786 return;
787 }
788
789 NativeObject* nobj = &obj->as<NativeObject>();
790 if (!nobj->hasEmptyElements()) {
791 HeapSlotArray elements = nobj->getDenseElements();
792 Value* elems = elements.begin()->unbarrieredAddress();
793 traceObjectElements(elems, nobj->getDenseInitializedLength());
794 }
795
796 traceObjectSlots(nobj, 0, nobj->slotSpan());
797 }
798
799 void js::gc::TenuringTracer::traceObjectSlots(NativeObject* nobj,
800 uint32_t start, uint32_t end) {
801 auto traceRange = [this](HeapSlot* slotStart, HeapSlot* slotEnd) {
802 traceSlots(slotStart->unbarrieredAddress(), slotEnd->unbarrieredAddress());
803 };
804 nobj->forEachSlotRange(start, end, traceRange);
805 }
806
807 void js::gc::TenuringTracer::traceObjectElements(JS::Value* vp,
808 uint32_t count) {
809 traceSlots(vp, vp + count);
810 }
811
812 void js::gc::TenuringTracer::traceSlots(Value* vp, Value* end) {
813 for (; vp != end; ++vp) {
814 traverse(vp);
815 }
816 }
817
818 void js::gc::TenuringTracer::traceString(JSString* str) {
819 AutoPromotedAnyToNursery promotedToNursery(*this);
820 str->traceChildren(this);
821 if (str->isTenured() && promotedToNursery) {
822 runtime()->gc.storeBuffer().putWholeCell(str);
823 }
824 }
825
826 #ifdef DEBUG
827 static inline uintptr_t OffsetFromChunkStart(void* p) {
828 return uintptr_t(p) & gc::ChunkMask;
829 }
830 static inline size_t OffsetToChunkEnd(void* p) {
831 uintptr_t offsetFromStart = OffsetFromChunkStart(p);
832 MOZ_ASSERT(offsetFromStart < ChunkSize);
833 return ChunkSize - offsetFromStart;
834 }
835 #endif
836
837 /* Insert the given relocation entry into the list of things to visit. */
838 inline void js::gc::TenuringTracer::insertIntoObjectFixupList(
839 RelocationOverlay* entry) {
840 entry->setNext(objHead);
841 objHead = entry;
842 }
843
844 template <typename T>
845 inline T* js::gc::TenuringTracer::alloc(Zone* zone, AllocKind kind, Cell* src) {
846 AllocSite* site = NurseryCellHeader::from(src)->allocSite();
847 site->incPromotedCount();
848
849 void* ptr = allocCell<T::TraceKind>(zone, kind, site, src);
850 auto* cell = reinterpret_cast<T*>(ptr);
851 if (IsInsideNursery(cell)) {
852 MOZ_ASSERT(!nursery().inCollectedRegion(cell));
853 promotedToNursery = true;
854 }
855
856 return cell;
857 }
858
859 template <JS::TraceKind traceKind>
860 void* js::gc::TenuringTracer::allocCell(Zone* zone, AllocKind allocKind,
861 AllocSite* site, Cell* src) {
862 MOZ_ASSERT(zone == src->zone());
863
864 if (!shouldTenure(zone, traceKind, src)) {
865 // Allocations from the optimized alloc site continue to use that site,
866 // otherwise a special promoted alloc site it used.
867 if (site->kind() != AllocSite::Kind::Optimized) {
868 site = &zone->pretenuring.promotedAllocSite(traceKind);
869 }
870
871 size_t thingSize = Arena::thingSize(allocKind);
872 void* ptr = nursery_.tryAllocateCell(site, thingSize, traceKind);
873 if (MOZ_LIKELY(ptr)) {
874 return ptr;
875 }
876
877 JSContext* cx = runtime()->mainContextFromOwnThread();
878 ptr = CellAllocator::RetryNurseryAlloc<NoGC>(cx, traceKind, allocKind,
879 thingSize, site);
880 if (MOZ_LIKELY(ptr)) {
881 return ptr;
882 }
883
884 // The nursery is full. This is unlikely but can happen. Fall through to
885 // the tenured allocation path.
886 }
887
888 return AllocateTenuredCellInGC(zone, allocKind);
889 }
890
891 JSString* js::gc::TenuringTracer::allocString(JSString* src, Zone* zone,
892 AllocKind dstKind) {
893 JSString* dst = alloc<JSString>(zone, dstKind, src);
894 promotedSize += moveString(dst, src, dstKind);
895 promotedCells++;
896
897 return dst;
898 }
899
900 bool js::gc::TenuringTracer::shouldTenure(Zone* zone, JS::TraceKind traceKind,
901 Cell* cell) {
902 return tenureEverything || !zone->allocKindInNursery(traceKind) ||
903 nursery_.shouldTenure(cell);
904 }
905
906 JSObject* js::gc::TenuringTracer::promoteObjectSlow(JSObject* src) {
907 MOZ_ASSERT(IsInsideNursery(src));
908 MOZ_ASSERT(!src->is<PlainObject>());
909
910 AllocKind dstKind = src->allocKindForTenure(nursery());
911 auto* dst = alloc<JSObject>(src->nurseryZone(), dstKind, src);
912
913 size_t srcSize = Arena::thingSize(dstKind);
914
915 // Arrays and Tuples do not necessarily have the same AllocKind between src
916 // and dst. We deal with this by copying elements manually, possibly
917 // re-inlining them if there is adequate room inline in dst.
918 //
919 // For Arrays and Tuples we're reducing promotedSize to the smaller srcSize
920 // because moveElements() accounts for all Array or Tuple elements,
921 // even if they are inlined.
922 if (src->is<FixedLengthTypedArrayObject>()) {
923 auto* tarray = &src->as<FixedLengthTypedArrayObject>();
924 // Typed arrays with inline data do not necessarily have the same
925 // AllocKind between src and dst. The nursery does not allocate an
926 // inline data buffer that has the same size as the slow path will do.
927 // In the slow path, the Typed Array Object stores the inline data
928 // in the allocated space that fits the AllocKind. In the fast path,
929 // the nursery will allocate another buffer that is directly behind the
930 // minimal JSObject. That buffer size plus the JSObject size is not
931 // necessarily as large as the slow path's AllocKind size.
932 if (tarray->hasInlineElements()) {
933 AllocKind srcKind =
934 GetGCObjectKind(FixedLengthTypedArrayObject::FIXED_DATA_START);
935 size_t headerSize = Arena::thingSize(srcKind);
936 srcSize = headerSize + tarray->byteLength();
937 }
938 } else if (src->canHaveFixedElements()) {
939 srcSize = sizeof(NativeObject);
940 }
941
942 promotedSize += srcSize;
943 promotedCells++;
944
945 // Copy the Cell contents.
946 MOZ_ASSERT(OffsetFromChunkStart(src) >= sizeof(ChunkBase));
947 MOZ_ASSERT(OffsetToChunkEnd(src) >= srcSize);
948 js_memcpy(dst, src, srcSize);
949
950 // Move the slots and elements, if we need to.
951 if (src->is<NativeObject>()) {
952 NativeObject* ndst = &dst->as<NativeObject>();
953 NativeObject* nsrc = &src->as<NativeObject>();
954 promotedSize += moveSlots(ndst, nsrc);
955 promotedSize += moveElements(ndst, nsrc, dstKind);
956 }
957
958 JSObjectMovedOp op = dst->getClass()->extObjectMovedOp();
959 MOZ_ASSERT_IF(src->is<ProxyObject>(), op == proxy_ObjectMoved);
960 if (op) {
961 // Tell the hazard analysis that the object moved hook can't GC.
962 JS::AutoSuppressGCAnalysis nogc;
963 promotedSize += op(dst, src);
964 } else {
965 MOZ_ASSERT_IF(src->getClass()->hasFinalize(),
966 CanNurseryAllocateFinalizedClass(src->getClass()));
967 }
968
969 RelocationOverlay* overlay = RelocationOverlay::forwardCell(src, dst);
970 insertIntoObjectFixupList(overlay);
971
972 gcprobes::PromoteToTenured(src, dst);
973 return dst;
974 }
975
976 inline JSObject* js::gc::TenuringTracer::promotePlainObject(PlainObject* src) {
977 // Fast path version of promoteObjectSlow() for specialized for PlainObject.
978
979 MOZ_ASSERT(IsInsideNursery(src));
980
981 AllocKind dstKind = src->allocKindForTenure();
982 auto* dst = alloc<PlainObject>(src->nurseryZone(), dstKind, src);
983
984 size_t srcSize = Arena::thingSize(dstKind);
985 promotedSize += srcSize;
986 promotedCells++;
987
988 // Copy the Cell contents.
989 MOZ_ASSERT(OffsetFromChunkStart(src) >= sizeof(ChunkBase));
990 MOZ_ASSERT(OffsetToChunkEnd(src) >= srcSize);
991 js_memcpy(dst, src, srcSize);
992
993 // Move the slots and elements.
994 promotedSize += moveSlots(dst, src);
995 promotedSize += moveElements(dst, src, dstKind);
996
997 MOZ_ASSERT(!dst->getClass()->extObjectMovedOp());
998
999 RelocationOverlay* overlay = RelocationOverlay::forwardCell(src, dst);
1000 insertIntoObjectFixupList(overlay);
1001
1002 gcprobes::PromoteToTenured(src, dst);
1003 return dst;
1004 }
1005
1006 size_t js::gc::TenuringTracer::moveSlots(NativeObject* dst, NativeObject* src) {
1007 /* Fixed slots have already been copied over. */
1008 if (!src->hasDynamicSlots()) {
1009 return 0;
1010 }
1011
1012 size_t count = src->numDynamicSlots();
1013 size_t allocSize = ObjectSlots::allocSize(count);
1014
1015 ObjectSlots* header = src->getSlotsHeader();
1016 Nursery::WasBufferMoved result =
1017 nursery().maybeMoveBufferOnPromotion(&header, dst, allocSize);
1018 if (result == Nursery::BufferNotMoved) {
1019 return 0;
1020 }
1021
1022 dst->slots_ = header->slots();
1023 if (count) {
1024 nursery().setSlotsForwardingPointer(src->slots_, dst->slots_, count);
1025 }
1026 return allocSize;
1027 }
1028
1029 size_t js::gc::TenuringTracer::moveElements(NativeObject* dst,
1030 NativeObject* src,
1031 AllocKind dstKind) {
1032 if (src->hasEmptyElements()) {
1033 return 0;
1034 }
1035
1036 ObjectElements* srcHeader = src->getElementsHeader();
1037 size_t nslots = srcHeader->numAllocatedElements();
1038 size_t allocSize = nslots * sizeof(HeapSlot);
1039
1040 // Shifted elements are copied too.
1041 uint32_t numShifted = srcHeader->numShiftedElements();
1042
1043 void* unshiftedHeader = src->getUnshiftedElementsHeader();
1044
1045 /* Unlike other objects, Arrays and Tuples can have fixed elements. */
1046 if (src->canHaveFixedElements() && nslots <= GetGCKindSlots(dstKind)) {
1047 dst->as<NativeObject>().setFixedElements();
1048 js_memcpy(dst->getElementsHeader(), unshiftedHeader, allocSize);
1049 dst->elements_ += numShifted;
1050 dst->getElementsHeader()->flags |= ObjectElements::FIXED;
1051 nursery().setElementsForwardingPointer(srcHeader, dst->getElementsHeader(),
1052 srcHeader->capacity);
1053 return allocSize;
1054 }
1055
1056 /* TODO Bug 874151: Prefer to put element data inline if we have space. */
1057
1058 Nursery::WasBufferMoved result =
1059 nursery().maybeMoveBufferOnPromotion(&unshiftedHeader, dst, allocSize);
1060 if (result == Nursery::BufferNotMoved) {
1061 return 0;
1062 }
1063
1064 dst->elements_ =
1065 static_cast<ObjectElements*>(unshiftedHeader)->elements() + numShifted;
1066 dst->getElementsHeader()->flags &= ~ObjectElements::FIXED;
1067 nursery().setElementsForwardingPointer(srcHeader, dst->getElementsHeader(),
1068 srcHeader->capacity);
1069 return allocSize;
1070 }
1071
1072 inline void js::gc::TenuringTracer::insertIntoStringFixupList(
1073 StringRelocationOverlay* entry) {
1074 entry->setNext(stringHead);
1075 stringHead = entry;
1076 }
1077
1078 JSString* js::gc::TenuringTracer::promoteString(JSString* src) {
1079 MOZ_ASSERT(IsInsideNursery(src));
1080 MOZ_ASSERT(!src->isForwarded());
1081 MOZ_ASSERT(!src->isExternal());
1082
1083 #ifdef JS_GC_ZEAL
1084 if (promotionStats) {
1085 promotionStats->notePromotedString(src);
1086 }
1087 #endif
1088
1089 AllocKind dstKind = src->getAllocKind();
1090 Zone* zone = src->nurseryZone();
1091
1092 // If this string is in the StringToAtomCache, try to deduplicate it by using
1093 // the atom. Don't do this for dependent strings because they're more
1094 // complicated. See StringRelocationOverlay and DeduplicationStringHasher
1095 // comments.
1096 MOZ_ASSERT(!src->isAtom());
1097 if (src->isLinear() && src->inStringToAtomCache() &&
1098 src->isDeduplicatable() && !src->hasBase()) {
1099 JSLinearString* linear = &src->asLinear();
1100 JSAtom* atom = runtime()->caches().stringToAtomCache.lookupInMap(linear);
1101 // The string will not be present in the cache if it was previously promoted
1102 // to the second nursery generation.
1103 if (atom) {
1104 // Only deduplicate if both strings have the same encoding, to not confuse
1105 // dependent strings.
1106 if (src->hasTwoByteChars() == atom->hasTwoByteChars()) {
1107 // The StringToAtomCache isn't used for inline strings (due to the
1108 // minimum length) so canOwnDependentChars must be true for both src and
1109 // atom. This means if there are dependent strings floating around using
1110 // str's chars, they will be able to use the chars from the atom.
1111 static_assert(StringToAtomCache::MinStringLength >
1112 JSFatInlineString::MAX_LENGTH_LATIN1);
1113 static_assert(StringToAtomCache::MinStringLength >
1114 JSFatInlineString::MAX_LENGTH_TWO_BYTE);
1115 MOZ_ASSERT(src->canOwnDependentChars());
1116 MOZ_ASSERT(atom->canOwnDependentChars());
1117
1118 StringRelocationOverlay::forwardString(src, atom);
1119 gcprobes::PromoteToTenured(src, atom);
1120 return atom;
1121 }
1122 }
1123 }
1124
1125 JSString* dst;
1126
1127 // A live nursery string can only get deduplicated when:
1128 // 1. Its length is smaller than MAX_DEDUPLICATABLE_STRING_LENGTH:
1129 // Hashing a long string can affect performance.
1130 // 2. It is linear:
1131 // Deduplicating every node in it would end up doing O(n^2) hashing work.
1132 // 3. It is deduplicatable:
1133 // The JSString NON_DEDUP_BIT flag is unset.
1134 // 4. It matches an entry in stringDeDupSet.
1135 // 5. It is moved to the tenured heap.
1136
1137 if (shouldTenure(zone, JS::TraceKind::String, src) &&
1138 src->length() < MAX_DEDUPLICATABLE_STRING_LENGTH && src->isLinear() &&
1139 src->isDeduplicatable() && stringDeDupSet.isSome()) {
1140 src->clearBitsOnTenure();
1141 auto p = stringDeDupSet->lookupForAdd(src);
1142 if (p) {
1143 // Deduplicate to the looked-up string!
1144 dst = *p;
1145 MOZ_ASSERT(dst->isTenured()); // Never deduplicate to a from-space cell.
1146 zone->stringStats.ref().noteDeduplicated(src->length(), src->allocSize());
1147 if (src->isDependent()) {
1148 StringRelocationOverlay::forwardDependentString(&src->asDependent(),
1149 dst);
1150 } else {
1151 StringRelocationOverlay::forwardString(src, dst);
1152 }
1153 gcprobes::PromoteToTenured(src, dst);
1154 return dst;
1155 }
1156
1157 dst = allocString(src, zone, dstKind);
1158
1159 // In some situations, a string may be converted to a different type when
1160 // tenured. Currently, this only happens when a dependent string's chain of
1161 // base strings makes it impossible to recover its data, in which case it
1162 // will get converted to a regular linear string. In order to avoid
1163 // rehashing and some complexity, do not deduplicate to such strings.
1164 if (dst->flags() == src->flags()) {
1165 using DedupHasher [[maybe_unused]] = DeduplicationStringHasher<JSString*>;
1166 MOZ_ASSERT(DedupHasher::hash(src) == DedupHasher::hash(dst),
1167 "src and dst must have the same hash for lookupForAdd");
1168
1169 if (!stringDeDupSet->add(p, dst)) {
1170 // When there is oom caused by the stringDeDupSet, stop deduplicating
1171 // strings.
1172 stringDeDupSet.reset();
1173 }
1174 }
1175 } else {
1176 dst = allocString(src, zone, dstKind);
1177 if (dst->isTenured()) {
1178 src->clearBitsOnTenure();
1179 dst->clearBitsOnTenure();
1180 }
1181 }
1182
1183 gcprobes::PromoteToTenured(src, dst);
1184 zone->stringStats.ref().noteTenured(src->allocSize());
1185
1186 if (dst->isDependent()) {
1187 // Dependent string:
1188 // - root base was tenured => done
1189 // - otherwise => promote the root base if it has not already been
1190 // promoted, then update the dependent string's chars pointer based on
1191 // the root base's original chars pointer (stored in its
1192 // StringRelocationOverlay during promotion)
1193
1194 JSLinearString* base = src->asDependent().rootBaseDuringMinorGC();
1195
1196 // Limited recursion: the root base cannot be dependent, so this will not
1197 // recurse again.
1198 JSString* promotedBase =
1199 InCollectedNurseryRegion(base) ? promoteOrForward(base) : base;
1200 MOZ_ASSERT(!promotedBase->isDependent());
1201
1202 dst->asDependent().setBase(&promotedBase->asLinear());
1203 if (InCollectedNurseryRegion(base)) {
1204 dst->asDependent().updateToPromotedBase(base);
1205 }
1206
1207 StringRelocationOverlay::forwardDependentString(src, dst);
1208 } else {
1209 // Non-dependent string: store the original chars pointer in the nursery
1210 // cell (for future promotions of any dependent strings that use this string
1211 // as a base), then forward to the promoted cell.
1212
1213 StringRelocationOverlay::forwardString(src, dst);
1214 if (dst->isRope()) {
1215 // Enqueue for recursion through the children.
1216 insertIntoStringFixupList(StringRelocationOverlay::fromCell(src));
1217 }
1218 }
1219
1220 MOZ_ASSERT_IF(dst->isTenured() && dst->isLinear(), dst->isDeduplicatable());
1221
1222 return dst;
1223 }
1224
1225 JS::BigInt* js::gc::TenuringTracer::promoteBigInt(JS::BigInt* src) {
1226 MOZ_ASSERT(IsInsideNursery(src));
1227 MOZ_ASSERT(!src->isForwarded());
1228
1229 #ifdef JS_GC_ZEAL
1230 if (promotionStats) {
1231 promotionStats->notePromotedBigInt(src);
1232 }
1233 #endif
1234
1235 AllocKind dstKind = src->getAllocKind();
1236 Zone* zone = src->nurseryZone();
1237
1238 JS::BigInt* dst = alloc<JS::BigInt>(zone, dstKind, src);
1239 promotedSize += moveBigInt(dst, src, dstKind);
1240 promotedCells++;
1241
1242 RelocationOverlay::forwardCell(src, dst);
1243
1244 gcprobes::PromoteToTenured(src, dst);
1245 return dst;
1246 }
1247
1248 void js::gc::TenuringTracer::collectToObjectFixedPoint() {
1249 while (RelocationOverlay* p = objHead) {
1250 MOZ_ASSERT(nursery().inCollectedRegion(p));
1251 objHead = objHead->next();
1252 auto* obj = static_cast<JSObject*>(p->forwardingAddress());
1253
1254 MOZ_ASSERT_IF(IsInsideNursery(obj), !nursery().inCollectedRegion(obj));
1255
1256 AutoPromotedAnyToNursery promotedAnyToNursery(*this);
1257 traceObject(obj);
1258 if (obj->isTenured() && promotedAnyToNursery) {
1259 runtime()->gc.storeBuffer().putWholeCell(obj);
1260 }
1261 }
1262 }
1263
1264 void js::gc::TenuringTracer::collectToStringFixedPoint() {
1265 // Recurse through ropes.
1266
1267 while (StringRelocationOverlay* p = stringHead) {
1268 MOZ_ASSERT(nursery().inCollectedRegion(p));
1269 stringHead = stringHead->next();
1270
1271 auto* promotedStr = static_cast<JSString*>(p->forwardingAddress());
1272 MOZ_ASSERT_IF(IsInsideNursery(promotedStr),
1273 !nursery().inCollectedRegion(promotedStr));
1274
1275 // To ensure the NON_DEDUP_BIT was reset properly.
1276 MOZ_ASSERT(!promotedStr->isAtom());
1277 MOZ_ASSERT_IF(promotedStr->isTenured() && promotedStr->isLinear(),
1278 promotedStr->isDeduplicatable());
1279
1280 MOZ_ASSERT(promotedStr->isRope());
1281 traceString(promotedStr);
1282 }
1283 }
1284
1285 size_t js::gc::TenuringTracer::moveString(JSString* dst, JSString* src,
1286 AllocKind dstKind) {
1287 size_t size = Arena::thingSize(dstKind);
1288
1289 MOZ_ASSERT_IF(dst->isTenured(),
1290 dst->asTenured().getAllocKind() == src->getAllocKind());
1291
1292 // Copy the Cell contents.
1293 MOZ_ASSERT(OffsetToChunkEnd(src) >= size);
1294 js_memcpy(dst, src, size);
1295
1296 if (src->isDependent()) {
1297 // Special case: if src is a dependent string whose base chain goes through
1298 // tenured space, then it may point to dead chars -- either because its root
1299 // base was deduplicated, or its root base's chars were allocated in the
1300 // nursery. If src's chars pointer will no longer be valid once minor GC is
1301 // complete, give it its own copy of the chars.
1302 //
1303 // Note that the size of any cloned data is *not* included in the "number
1304 // of bytes tenured" return value here, since the donor owns them and may
1305 // still be alive and we don't want to double-count.
1306 JSLinearString::maybeCloneCharsOnPromotion(&dst->asDependent());
1307 return size;
1308 }
1309
1310 if (!src->hasOutOfLineChars()) {
1311 return size;
1312 }
1313
1314 if (src->ownsMallocedChars()) {
1315 void* chars = src->asLinear().nonInlineCharsRaw();
1316 nursery().removeMallocedBufferDuringMinorGC(chars);
1317 nursery().trackMallocedBufferOnPromotion(
1318 chars, dst, dst->asLinear().allocSize(), MemoryUse::StringContents);
1319 return size;
1320 }
1321
1322 if (src->asLinear().hasStringBuffer()) {
1323 auto* buffer = src->asLinear().stringBuffer();
1324 if (dst->isTenured()) {
1325 // Increment the buffer's refcount because the tenured string now has a
1326 // reference to it. The nursery's reference will be released at the end of
1327 // the minor GC in Nursery::sweep.
1328 buffer->AddRef();
1329 AddCellMemory(dst, dst->asLinear().allocSize(),
1330 MemoryUse::StringContents);
1331 }
1332 return size;
1333 }
1334
1335 // String data is in the nursery and needs to be moved to the malloc heap.
1336
1337 MOZ_ASSERT(nursery().isInside(src->asLinear().nonInlineCharsRaw()));
1338
1339 if (src->hasLatin1Chars()) {
1340 size += dst->asLinear().maybeMallocCharsOnPromotion<Latin1Char>(&nursery());
1341 } else {
1342 size += dst->asLinear().maybeMallocCharsOnPromotion<char16_t>(&nursery());
1343 }
1344
1345 return size;
1346 }
1347
1348 size_t js::gc::TenuringTracer::moveBigInt(JS::BigInt* dst, JS::BigInt* src,
1349 AllocKind dstKind) {
1350 size_t size = Arena::thingSize(dstKind);
1351
1352 MOZ_ASSERT_IF(dst->isTenured(),
1353 dst->asTenured().getAllocKind() == src->getAllocKind());
1354
1355 // Copy the Cell contents.
1356 MOZ_ASSERT(OffsetToChunkEnd(src) >= size);
1357 js_memcpy(dst, src, size);
1358
1359 MOZ_ASSERT(dst->zone() == src->nurseryZone());
1360
1361 if (!src->hasHeapDigits()) {
1362 return size;
1363 }
1364
1365 size_t length = dst->digitLength();
1366 size_t nbytes = length * sizeof(JS::BigInt::Digit);
1367
1368 Nursery::WasBufferMoved result =
1369 nursery().maybeMoveNurseryOrMallocBufferOnPromotion(
1370 &dst->heapDigits_, dst, nbytes, MemoryUse::BigIntDigits);
1371 if (result == Nursery::BufferMoved) {
1372 nursery().setDirectForwardingPointer(src->heapDigits_, dst->heapDigits_);
1373 size += nbytes;
1374 }
1375
1376 return size;
1377 }
1378
1379 template <typename Key>
1380 /* static */
1381 inline HashNumber DeduplicationStringHasher<Key>::hash(const Lookup& lookup) {
1382 JS::AutoCheckCannotGC nogc;
1383 HashNumber strHash;
1384
1385 // Include flags in the hash. A string relocation overlay stores either the
1386 // nursery root base chars or the dependent string nursery base, but does not
1387 // indicate which one. If strings with different string types were
1388 // deduplicated, for example, a dependent string gets deduplicated into an
1389 // extensible string, the base chain would be broken and the root base would
1390 // be unreachable.
1391
1392 if (lookup->asLinear().hasLatin1Chars()) {
1393 strHash = mozilla::HashString(lookup->asLinear().latin1Chars(nogc),
1394 lookup->length());
1395 } else {
1396 MOZ_ASSERT(lookup->asLinear().hasTwoByteChars());
1397 strHash = mozilla::HashString(lookup->asLinear().twoByteChars(nogc),
1398 lookup->length());
1399 }
1400
1401 return mozilla::HashGeneric(strHash, lookup->zone(), lookup->flags());
1402 }
1403
1404 template <typename Key>
1405 /* static */
1406 MOZ_ALWAYS_INLINE bool DeduplicationStringHasher<Key>::match(
1407 const Key& key, const Lookup& lookup) {
1408 if (!key->sameLengthAndFlags(*lookup) ||
1409 key->asTenured().zone() != lookup->zone() ||
1410 key->asTenured().getAllocKind() != lookup->getAllocKind()) {
1411 return false;
1412 }
1413
1414 JS::AutoCheckCannotGC nogc;
1415
1416 if (key->asLinear().hasLatin1Chars()) {
1417 MOZ_ASSERT(lookup->asLinear().hasLatin1Chars());
1418 return EqualChars(key->asLinear().latin1Chars(nogc),
1419 lookup->asLinear().latin1Chars(nogc), lookup->length());
1420 }
1421
1422 MOZ_ASSERT(key->asLinear().hasTwoByteChars());
1423 MOZ_ASSERT(lookup->asLinear().hasTwoByteChars());
1424 return EqualChars(key->asLinear().twoByteChars(nogc),
1425 lookup->asLinear().twoByteChars(nogc), lookup->length());
1426 }
1427
1428 #ifdef JS_GC_ZEAL
1429
1430 void TenuringTracer::initPromotionReport() {
1431 MOZ_ASSERT(!promotionStats);
1432 promotionStats = MakeUnique<PromotionStats>();
1433 // Ignore OOM.
1434 }
1435
1436 void TenuringTracer::printPromotionReport(
1437 JSContext* cx, JS::GCReason reason, const JS::AutoRequireNoGC& nogc) const {
1438 if (!promotionStats || !promotionStats->shouldPrintReport()) {
1439 return;
1440 }
1441
1442 size_t minorGCCount = runtime()->gc.minorGCCount();
1443 double usedBytes = double(nursery_.previousGC.nurseryUsedBytes);
1444 double capacityBytes = double(nursery_.previousGC.nurseryCapacity);
1445 double fractionPromoted = double(getPromotedSize()) / usedBytes;
1446 double usedMB = usedBytes / (1024 * 1024);
1447 double capacityMB = capacityBytes / (1024 * 1024);
1448 fprintf(stderr, "Promotion stats for minor GC %zu:\n", minorGCCount);
1449 fprintf(stderr, " Reason: %s\n", ExplainGCReason(reason));
1450 fprintf(stderr, " Nursery size: %4.1f MB used of %4.1f MB\n", usedMB,
1451 capacityMB);
1452 fprintf(stderr, " Promotion rate: %5.1f%%\n", fractionPromoted);
1453
1454 promotionStats->printReport(cx, nogc);
1455 }
1456
1457 void PromotionStats::notePromotedObject(JSObject* obj) {
1458 objectCount++;
1459
1460 BaseShape* baseShape = obj->shape()->base();
1461 auto ptr = objectCountByBaseShape.lookupForAdd(baseShape);
1462 if (!ptr) {
1463 if (!objectCountByBaseShape.add(ptr, baseShape, 0)) {
1464 hadOOM = true;
1465 return;
1466 }
1467 }
1468 ptr->value()++;
1469 }
1470
1471 void PromotionStats::notePromotedString(JSString* str) {
1472 stringCount++;
1473
1474 AllocKind kind = str->getAllocKind();
1475 stringCountByKind[kind]++;
1476 }
1477
1478 void PromotionStats::notePromotedBigInt(JS::BigInt* bi) { bigIntCount++; }
1479
1480 bool PromotionStats::shouldPrintReport() const {
1481 if (hadOOM) {
1482 return false;
1483 }
1484
1485 return objectCount || stringCount || bigIntCount;
1486 }
1487
1488 void PromotionStats::printReport(JSContext* cx,
1489 const JS::AutoRequireNoGC& nogc) {
1490 if (objectCount) {
1491 fprintf(stderr, " Objects promoted: %zu\n", objectCount);
1492 printObjectCounts(cx, nogc);
1493 }
1494
1495 if (stringCount) {
1496 fprintf(stderr, " Strings promoted: %zu\n", stringCount);
1497 printStringCounts();
1498 }
1499
1500 if (bigIntCount) {
1501 fprintf(stderr, " BigInts promoted: %zu\n", bigIntCount);
1502 }
1503 }
1504
1505 void PromotionStats::printObjectCounts(JSContext* cx,
1506 const JS::AutoRequireNoGC& nogc) {
1507 CountsVector counts;
1508
1509 for (auto r = objectCountByBaseShape.all(); !r.empty(); r.popFront()) {
1510 size_t count = r.front().value();
1511 if (count < AttentionThreshold) {
1512 continue;
1513 }
1514
1515 BaseShape* baseShape = r.front().key();
1516
1517 const char* className = baseShape->clasp()->name;
1518
1519 UniqueChars constructorName = getConstructorName(cx, baseShape, nogc);
1520 const char* constructorChars = constructorName ? constructorName.get() : "";
1521
1522 LabelAndCount entry;
1523 snprintf(entry.label, sizeof(entry.label), "%s %s", className,
1524 constructorChars);
1525 entry.count = count;
1526 if (!counts.append(entry)) {
1527 return;
1528 }
1529 }
1530
1531 printCounts(counts, objectCount);
1532 }
1533
1534 UniqueChars PromotionStats::getConstructorName(
1535 JSContext* cx, BaseShape* baseShape, const JS::AutoRequireNoGC& nogc) {
1536 TaggedProto taggedProto = baseShape->proto();
1537 if (taggedProto.isDynamic()) {
1538 return nullptr;
1539 }
1540
1541 JSObject* proto = taggedProto.toObjectOrNull();
1542 if (!proto) {
1543 return nullptr;
1544 }
1545
1546 MOZ_ASSERT(!proto->isForwarded());
1547
1548 AutoRealm ar(cx, proto);
1549 bool found;
1550 Value value;
1551 if (!GetOwnPropertyPure(cx, proto, NameToId(cx->names().constructor), &value,
1552 &found)) {
1553 return nullptr;
1554 }
1555
1556 if (!found || !value.isObject()) {
1557 return nullptr;
1558 }
1559
1560 JSFunction* constructor = &value.toObject().as<JSFunction>();
1561 JSAtom* atom = constructor->maybePartialDisplayAtom();
1562 if (!atom) {
1563 return nullptr;
1564 }
1565
1566 return EncodeAscii(cx, atom);
1567 }
1568
1569 void PromotionStats::printStringCounts() {
1570 CountsVector counts;
1571 for (AllocKind kind : AllAllocKinds()) {
1572 size_t count = stringCountByKind[kind];
1573 if (count < AttentionThreshold) {
1574 continue;
1575 }
1576
1577 const char* name = AllocKindName(kind);
1578 LabelAndCount entry;
1579 strncpy(entry.label, name, sizeof(entry.label));
1580 entry.label[sizeof(entry.label) - 1] = 0;
1581 entry.count = count;
1582 if (!counts.append(entry)) {
1583 return;
1584 }
1585 }
1586
1587 printCounts(counts, stringCount);
1588 }
1589
1590 void PromotionStats::printCounts(CountsVector& counts, size_t total) {
1591 std::sort(counts.begin(), counts.end(),
1592 [](const auto& a, const auto& b) { return a.count > b.count; });
1593
1594 size_t max = std::min(counts.length(), size_t(10));
1595 for (size_t i = 0; i < max; i++) {
1596 const auto& entry = counts[i];
1597 printLine(entry.label, entry.count, total);
1598 }
1599 }
1600
1601 void PromotionStats::printLine(const char* name, size_t count, size_t total) {
1602 double percent = 100.0 * double(count) / double(total);
1603 fprintf(stderr, " %5.1f%%: %s\n", percent, name);
1604 }
1605
1606 #endif
1607
1608 MinorSweepingTracer::MinorSweepingTracer(JSRuntime* rt)
1609 : GenericTracerImpl(rt, JS::TracerKind::MinorSweeping,
1610 JS::WeakMapTraceAction::TraceKeysAndValues) {
1611 MOZ_ASSERT(CurrentThreadCanAccessRuntime(runtime()));
1612 MOZ_ASSERT(JS::RuntimeHeapIsMinorCollecting());
1613 }
1614
1615 template <typename T>
1616 inline void MinorSweepingTracer::onEdge(T** thingp, const char* name) {
1617 T* thing = *thingp;
1618 if (thing->isTenured()) {
1619 MOZ_ASSERT(!IsForwarded(thing));
1620 return;
1621 }
1622
1623 MOZ_ASSERT(runtime()->gc.nursery().inCollectedRegion(thing));
1624 if (IsForwarded(thing)) {
1625 *thingp = Forwarded(thing);
1626 return;
1627 }
1628
1629 *thingp = nullptr;
1630 }