Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qv4mm.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:critical reason:low-level-memory-management
4
5#include "PageAllocation.h"
6#include "PageReservation.h"
7
8#include <private/qnumeric_p.h>
9#include <private/qv4alloca_p.h>
10#include <private/qv4engine_p.h>
11#include <private/qv4identifiertable_p.h>
12#include <private/qv4mapobject_p.h>
13#include <private/qv4mm_p.h>
14#include <private/qv4object_p.h>
15#include <private/qv4profiling_p.h>
16#include <private/qv4qobjectwrapper_p.h>
17#include <private/qv4setobject_p.h>
18#include <private/qv4stackframe_p.h>
19
20#include <QtQml/qqmlengine.h>
21
22#include <QtCore/qalgorithms.h>
23#include <QtCore/qelapsedtimer.h>
24#include <QtCore/qloggingcategory.h>
25#include <QtCore/qmap.h>
26#include <QtCore/qscopedvaluerollback.h>
27
28#include <algorithm>
29#include <chrono>
30#include <cstdlib>
31
32//#define MM_STATS
33
34#if !defined(MM_STATS) && !defined(QT_NO_DEBUG)
35#define MM_STATS
36#endif
37
38#if MM_DEBUG
39#define DEBUG qDebug() << "MM:"
40#else
41#define DEBUG if (1) ; else qDebug() << "MM:"
42#endif
43
44#ifdef V4_USE_VALGRIND
45#include <valgrind/valgrind.h>
46#include <valgrind/memcheck.h>
47#endif
48
49#ifdef V4_USE_HEAPTRACK
50#include <heaptrack_api.h>
51#endif
52
53#if OS(QNX)
54#include <sys/storage.h> // __tls()
55#endif
56
57#if USE(PTHREADS) && HAVE(PTHREAD_NP_H)
58#include <pthread_np.h>
59#endif
60
61Q_STATIC_LOGGING_CATEGORY(lcGcStats, "qt.qml.gc.statistics")
62Q_STATIC_LOGGING_CATEGORY(lcGcAllocatorStats, "qt.qml.gc.allocatorStats")
63Q_STATIC_LOGGING_CATEGORY(lcGcStateTransitions, "qt.qml.gc.stateTransitions")
64Q_STATIC_LOGGING_CATEGORY(lcGcForcedRuns, "qt.qml.gc.forcedRuns")
65Q_STATIC_LOGGING_CATEGORY(lcGcStepExecution, "qt.qml.gc.stepExecution")
66
67using namespace WTF;
68
69QT_BEGIN_NAMESPACE
70
71namespace QV4 {
72
73enum {
74 MinSlotsGCLimit = QV4::Chunk::AvailableSlots*16,
75 GCOverallocation = 200 /* Max overallocation by the GC in % */
76};
77
79 enum {
80#ifdef Q_OS_RTEMS
81 NumChunks = sizeof(quint64),
82#else
83 NumChunks = 8*sizeof(quint64),
84#endif
85 SegmentSize = NumChunks*Chunk::ChunkSize,
86 };
87
88 MemorySegment(size_t size)
89 {
90 size += Chunk::ChunkSize; // make sure we can get enough 64k alignment memory
91 if (size < SegmentSize)
92 size = SegmentSize;
93
94 pageReservation = PageReservation::reserve(size, OSAllocator::JSGCHeapPages);
95 base = reinterpret_cast<Chunk *>((reinterpret_cast<quintptr>(pageReservation.base()) + Chunk::ChunkSize - 1) & ~(Chunk::ChunkSize - 1));
97 availableBytes = size - (reinterpret_cast<quintptr>(base) - reinterpret_cast<quintptr>(pageReservation.base()));
98 if (availableBytes < SegmentSize)
99 --nChunks;
100 }
102 qSwap(pageReservation, other.pageReservation);
103 qSwap(base, other.base);
104 qSwap(allocatedMap, other.allocatedMap);
105 qSwap(availableBytes, other.availableBytes);
106 qSwap(nChunks, other.nChunks);
107 }
108
110 if (base)
111 pageReservation.deallocate();
112 }
113
114 void setBit(size_t index) {
115 Q_ASSERT(index < nChunks);
116 quint64 bit = static_cast<quint64>(1) << index;
117 allocatedMap |= bit;
118 }
119 void clearBit(size_t index) {
120 Q_ASSERT(index < nChunks);
121 quint64 bit = static_cast<quint64>(1) << index;
122 allocatedMap &= ~bit;
123 }
124 bool testBit(size_t index) const {
125 Q_ASSERT(index < nChunks);
126 quint64 bit = static_cast<quint64>(1) << index;
127 return (allocatedMap & bit);
128 }
129
130 Chunk *allocate(size_t size);
131 void free(Chunk *chunk, size_t size) {
132 DEBUG << "freeing chunk" << chunk;
133 size_t index = static_cast<size_t>(chunk - base);
134 size_t end = qMin(static_cast<size_t>(NumChunks), index + (size - 1)/Chunk::ChunkSize + 1);
135 while (index < end) {
136 Q_ASSERT(testBit(index));
137 clearBit(index);
138 ++index;
139 }
140
141 size_t pageSize = WTF::pageSize();
142 size = (size + pageSize - 1) & ~(pageSize - 1);
143#if !defined(Q_OS_LINUX) && !defined(Q_OS_WIN)
144 // Linux and Windows zero out pages that have been decommitted and get committed again.
145 // unfortunately that's not true on other OSes (e.g. BSD based ones), so zero out the
146 // memory before decommit, so that we can be sure that all chunks we allocate will be
147 // zero initialized.
148 memset(chunk, 0, size);
149#endif
150 pageReservation.decommit(chunk, size);
151 }
152
153 bool contains(Chunk *c) const {
154 return c >= base && c < base + nChunks;
155 }
156
158 Chunk *base = nullptr;
161 uint nChunks = 0;
162};
163
165{
166 if (!allocatedMap && size >= SegmentSize) {
167 // chunk allocated for one huge allocation
168 Q_ASSERT(availableBytes >= size);
169 pageReservation.commit(base, size);
170 allocatedMap = ~static_cast<quint64>(0);
171 return base;
172 }
173 size_t requiredChunks = (size + sizeof(Chunk) - 1)/sizeof(Chunk);
174 uint sequence = 0;
175 Chunk *candidate = nullptr;
176 for (uint i = 0; i < nChunks; ++i) {
177 if (!testBit(i)) {
178 if (!candidate)
179 candidate = base + i;
180 ++sequence;
181 } else {
182 candidate = nullptr;
183 sequence = 0;
184 }
185 if (sequence == requiredChunks) {
186 pageReservation.commit(candidate, size);
187 for (uint i = 0; i < requiredChunks; ++i)
188 setBit(candidate - base + i);
189 DEBUG << "allocated chunk " << candidate << Qt::hex << size;
190
191 return candidate;
192 }
193 }
194 return nullptr;
195}
196
199
201 size += Chunk::HeaderSize; // space required for the Chunk header
202 size_t pageSize = WTF::pageSize();
203 size = (size + pageSize - 1) & ~(pageSize - 1); // align to page sizes
204 if (size < Chunk::ChunkSize)
205 size = Chunk::ChunkSize;
206 return size;
207 }
208
209 Chunk *allocate(size_t size = 0);
210 void free(Chunk *chunk, size_t size = 0);
211
213};
214
216{
217 size = requiredChunkSize(size);
218 for (auto &m : memorySegments) {
219 if (~m.allocatedMap) {
220 Chunk *c = m.allocate(size);
221 if (c)
222 return c;
223 }
224 }
225
226 // allocate a new segment
227 memorySegments.push_back(MemorySegment(size));
228 Chunk *c = memorySegments.back().allocate(size);
229 Q_ASSERT(c);
230 return c;
231}
232
233void ChunkAllocator::free(Chunk *chunk, size_t size)
234{
235 size = requiredChunkSize(size);
236 for (auto &m : memorySegments) {
237 if (m.contains(chunk)) {
238 m.free(chunk, size);
239 return;
240 }
241 }
242 Q_ASSERT(false);
243}
244
245#ifdef DUMP_SWEEP
247 QString s = QString::number(n, 2);
248 while (s.length() < 64)
249 s.prepend(QChar::fromLatin1('0'));
250 return s;
251}
252#define SDUMP qDebug
253#else
254QString binary(quintptr) { return QString(); }
255#define SDUMP if (1) ; else qDebug
256#endif
257
259{
260 bool hasUsedSlots = false;
261 SDUMP() << "sweeping chunk" << this;
262 HeapItem *o = realBase();
263 bool lastSlotFree = false;
264 for (uint i = 0; i < Chunk::EntriesInBitmap; ++i) {
265 // Snapshots. The destructors below may allocate, and setAllocatedSlots() then
266 // sets object and extends bits in this very word. We have to remember what we
267 // decided to free, so that we can clear exactly that further down rather than
268 // assigning the words wholesale and dropping those bits again.
271
273 Q_ASSERT((toFree & objectBitmap[i]) == toFree); // check all black objects are marked as being used
275 SDUMP() << " index=" << i;
276 SDUMP() << " toFree =" << binary(toFree);
277 SDUMP() << " black =" << binary(blackBitmap[i]);
278 SDUMP() << " object =" << binary(objectBitmap[i]);
279 SDUMP() << " extends =" << binary(e);
280 if (lastSlotFree)
281 e &= (e + 1); // clear all lowest extent bits
282 while (toFree) {
284 quintptr bit = (static_cast<quintptr>(1) << index);
285
286 toFree ^= bit; // mask out freed slot
287
288 // remove all extends slots that have been freed
289 // this is a bit of bit trickery.
290 quintptr mask = (bit << 1) - 1; // create a mask of 1's to the right of and up to the current bit
291 quintptr objmask = e | mask; // or'ing mask with e gives all ones until the end of the current object
292 quintptr result = objmask + 1;
293 Q_ASSERT(qCountTrailingZeroBits(result) - index != 0); // ensure we freed something
294 result |= mask; // ensure we don't clear stuff to the right of the current object
295 e &= result;
296
298 Heap::Base *b = *itemToFree;
299 const VTable *v = b->internalClass->vtable;
300// if (Q_UNLIKELY(classCountPtr))
301// classCountPtr(v->className);
302 if (v->destroy)
303 v->destroy(b);
304#ifdef V4_USE_HEAPTRACK
306#endif
307 }
314 hasUsedSlots |= (objectBitmap[i] != 0);
315 lastSlotFree = !((objectBitmap[i]|extendsBitmap[i]) >> (sizeof(quintptr)*8 - 1));
316 SDUMP() << " new extends =" << binary(e);
317 SDUMP() << " lastSlotFree" << lastSlotFree;
319 o += Chunk::Bits;
320 }
321 return hasUsedSlots;
322}
323
325{
326 HeapItem *o = realBase();
327 for (uint i = 0; i < Chunk::EntriesInBitmap; ++i) {
330 while (toFree) {
332 quintptr bit = (static_cast<quintptr>(1) << index);
333
334 toFree ^= bit; // mask out freed slot
335
336 // remove all extends slots that have been freed
337 // this is a bit of bit trickery.
338 quintptr mask = (bit << 1) - 1; // create a mask of 1's to the right of and up to the current bit
339 quintptr objmask = e | mask; // or'ing mask with e gives all ones until the end of the current object
340 quintptr result = objmask + 1;
341 Q_ASSERT(qCountTrailingZeroBits(result) - index != 0); // ensure we freed something
342 result |= mask; // ensure we don't clear stuff to the right of the current object
343 e &= result;
344
346 Heap::Base *b = *itemToFree;
349#ifdef V4_USE_HEAPTRACK
351#endif
352 }
355 objectBitmap[i] = 0;
356 extendsBitmap[i] = e;
357 o += Chunk::Bits;
358 }
359}
360
362{
363 memset(blackBitmap, 0, sizeof(blackBitmap));
364}
365
367{
369#if QT_POINTER_SIZE == 8
370 const int start = 0;
371#else
372 const int start = 1;
373#endif
374 uint freeSlots = 0;
376
377 for (int i = start; i < EntriesInBitmap; ++i) {
379#if QT_POINTER_SIZE == 8
380 if (!i)
381 usedSlots |= (static_cast<quintptr>(1) << (HeaderSize/SlotSize)) - 1;
382#endif
384 while (1) {
386 if (index == Bits)
387 break;
389 usedSlots &= ~((static_cast<quintptr>(1) << index) - 1);
390 while (!usedSlots) {
391 if (++i < EntriesInBitmap) {
393 } else {
395 // Overflows to 0 when counting trailing zeroes above in next iteration.
396 // Then, all the bits are zeroes and we break.
398 break;
399 }
401 }
403
405 usedSlots |= (quintptr(1) << index) - 1;
406 uint freeEnd = i*Bits + index;
408 freeSlots += nSlots;
411 uint bin = qMin(nBins - 1, nSlots);
413 bins[bin] = freeItem;
414 }
415 }
417}
418
420 Q_ASSERT((size % Chunk::SlotSize) == 0);
422
423 if (allocationStats)
425
426 HeapItem **last;
427
428 HeapItem *m;
429
430 if (slotsRequired < NumBins - 1) {
432 if (m) {
434 goto done;
435 }
436 }
437
438 if (nFree >= slotsRequired) {
439 // use bump allocation
441 m = nextFree;
444 goto done;
445 }
446
447 // search last bin for a large enough item
448 last = &freeBins[NumBins - 1];
449 while ((m = *last)) {
451 *last = m->freeData.next; // take it out of the list
452
454 if (remainingSlots == 0)
455 goto done;
456
458 if (remainingSlots > nFree) {
459 if (nFree) {
464 }
467 } else {
472 }
473 goto done;
474 }
475 last = &m->freeData.next;
476 }
477
478 if (slotsRequired < NumBins - 1) {
479 // check if we can split up another slot
480 for (size_t i = slotsRequired + 1; i < NumBins - 1; ++i) {
481 m = freeBins[i];
482 if (m) {
483 freeBins[i] = m->freeData.next; // take it out of the list
490 goto done;
491 }
492 }
493 }
494
495 if (!m) {
496 if (!forceAllocation)
497 return nullptr;
498 if (nFree) {
499 // Save any remaining slots of the current chunk
500 // for later, smaller allocations.
505 }
511 m = nextFree;
514 }
515
516done:
519#ifdef V4_USE_HEAPTRACK
521#endif
522 return m;
523}
524
526{
527 const auto firstEmptyChunkPos = partition(chunks, [this](const std::size_t i) {
528 return chunks.at(i)->sweep(engine);
529 });
531
532 nextFree = nullptr;
533 nFree = 0;
534 memset(freeBins, 0, sizeof(freeBins));
535
537
541 });
542
543 // only free the chunks at the end to avoid that the sweep() calls indirectly
544 // access freed memory
548 });
549
551}
552
554{
555 for (auto c : chunks)
556 c->freeAll(engine);
557 for (auto c : chunks) {
560 }
561}
562
564{
565 for (auto c : chunks)
566 c->resetBlackBits();
567}
568
570 MemorySegment *m = nullptr;
571 Chunk *c = nullptr;
572 if (size >= MemorySegment::SegmentSize/2) {
573 // too large to handle through the ChunkAllocator, let's get our own memory segement
574 size += Chunk::HeaderSize; // space required for the Chunk header
576 size = (size + pageSize - 1) & ~(pageSize - 1); // align to page sizes
577 m = new MemorySegment(size);
578 c = m->allocate(size);
579 } else {
581 }
582 Q_ASSERT(c);
586#ifdef V4_USE_HEAPTRACK
588#endif
589 return c->first();
590}
591
592static void freeHugeChunk(ChunkAllocator *chunkAllocator, const HugeItemAllocator::HugeChunk &c)
593{
594 HeapItem *itemToFree = c.chunk->first();
595 Heap::Base *b = *itemToFree;
596 const VTable *v = b->internalClass->vtable;
597
598 if (v->destroy)
599 v->destroy(b);
600 if (c.segment) {
601 // own memory segment
602 c.segment->free(c.chunk, c.size);
603 delete c.segment;
604 } else {
605 chunkAllocator->free(c.chunk, c.size);
606 }
607#ifdef V4_USE_HEAPTRACK
608 heaptrack_report_free(c.chunk);
609#endif
610}
611
613{
614 auto isBlack = [this] (const HugeChunk &c) {
615 bool b = c.chunk->first()->isBlack();
617 if (!b) {
620 }
621 return !b;
622 };
623
626}
627
629{
630 for (auto c : chunks)
632}
633
641
642namespace {
643using ExtraData = GCStateInfo::ExtraData;
644GCState markStart(GCStateMachine *that, ExtraData &)
645{
646 //Initialize the mark stack
647 that->mm->m_markStack = std::make_unique<MarkStack>(that->mm->engine);
648 that->mm->engine->isGCOngoing = true;
649 return GCState::MarkGlobalObject;
650}
651
652GCState markGlobalObject(GCStateMachine *that, ExtraData &)
653{
654 that->mm->engine->markObjects(that->mm->m_markStack.get());
655 return GCState::MarkJSStack;
656}
657
658GCState markJSStack(GCStateMachine *that, ExtraData &)
659{
660 that->mm->collectFromJSStack(that->mm->markStack());
661 return GCState::InitMarkPersistentValues;
662}
663
664GCState initMarkPersistentValues(GCStateMachine *that, ExtraData &stateData)
665{
666 if (!that->mm->m_persistentValues)
667 return GCState::InitMarkWeakValues; // no persistent values to mark
668 stateData = GCIteratorStorage { that->mm->m_persistentValues->begin() };
669 return GCState::MarkPersistentValues;
670}
671
672enum: int {
673 MarkLoopIterationCount = 1024,
674 MarkLoopIterationCountForDrain = 10240,
675};
676
677bool wasDrainNecessary(MarkStack *ms, QDeadlineTimer deadline)
678{
679 if (ms->remainingBeforeSoftLimit() > MarkLoopIterationCount)
680 return false;
681 // drain
682 ms->drain(deadline);
683 return true;
684}
685
686QObject *parentChainRoot(const QObject *qobject)
687{
688 QObject *root = qobject->parent();
689 if (!root)
690 return nullptr;
691
692 while (QObject *parent = root->parent())
693 root = parent;
694 return root;
695}
696
697bool hasMarkedWrapper(const QObject *qobject, ExecutionEngine *engine)
698{
699 QQmlData *ddata = QQmlData::get(qobject);
700 if (!ddata)
701 return false;
702
703 const auto isMarked = [](ReturnedValue wrapper) {
704 Heap::Base *heapObject = Value::fromReturnedValue(wrapper).heapObject();
705 return heapObject && heapObject->isMarked();
706 };
707
708 MultiplyWrappedQObjectMap *otherWrappers = engine->m_multiplyWrappedQObjects;
709 if (ddata->jsEngineId == engine->m_engineId) {
710 if (isMarked(ddata->jsWrapper.value()))
711 return true;
712 } else if (otherWrappers && ddata->hasTaintedV4Object) {
713 if (isMarked(otherWrappers->value(qobject)))
714 return true;
715 }
716
717 return ddata->hasConstWrapper && otherWrappers && isMarked(otherWrappers->value(qobject));
718}
719
720// Whether marking must keep qobject's wrappers alive:
721// qobject or the root of its parent chain is kept alive by C++.
722// If engine is not null, a root that has a marked wrapper in it also counts.
723bool isKeptAlive(const QObject *qobject, ExecutionEngine *engine = nullptr)
724{
725 if (QQmlData::keepAliveDuringGarbageCollection(qobject))
726 return true;
727
728 const QObject *root = parentChainRoot(qobject);
729 if (!root)
730 return false;
731
732 return QQmlData::keepAliveDuringGarbageCollection(root)
733 || (engine && hasMarkedWrapper(root, engine));
734}
735
736GCState markPersistentValues(GCStateMachine *that, ExtraData &stateData) {
737 auto markStack = that->mm->markStack();
738 if (wasDrainNecessary(markStack, that->deadline) && that->deadline.hasExpired())
739 return GCState::MarkPersistentValues;
740 PersistentValueStorage::Iterator& it = get<GCIteratorStorage>(stateData).it;
741 // avoid repeatedly hitting the timer constantly by batching iterations
742 for (int i = 0; i < MarkLoopIterationCount; ++i) {
743 if (!it.p)
744 return GCState::InitMarkWeakValues;
745 if (Managed *m = (*it).as<Managed>())
746 m->mark(markStack);
747 ++it;
748 }
749 return GCState::MarkPersistentValues;
750}
751
752GCState initMarkWeakValues(GCStateMachine *that, ExtraData &stateData)
753{
754 stateData = GCIteratorStorage { that->mm->m_weakValues->begin() };
755 return GCState::MarkWeakValues;
756}
757
758GCState markWeakValues(GCStateMachine *that, ExtraData &stateData)
759{
760 auto markStack = that->mm->markStack();
761 if (wasDrainNecessary(markStack, that->deadline) && that->deadline.hasExpired())
762 return GCState::MarkWeakValues;
763 PersistentValueStorage::Iterator& it = get<GCIteratorStorage>(stateData).it;
764 // avoid repeatedly hitting the timer constantly by batching iterations
765 for (int i = 0; i < MarkLoopIterationCount; ++i) {
766 if (!it.p)
767 return GCState::MarkDrain;
768 QObjectWrapper *qobjectWrapper = (*it).as<QObjectWrapper>();
769 ++it;
770 if (!qobjectWrapper)
771 continue;
772 QObject *qobject = qobjectWrapper->object();
773 if (!qobject)
774 continue;
775 if (isKeptAlive(qobject))
776 qobjectWrapper->mark(that->mm->markStack());
777 }
778 return GCState::MarkWeakValues;
779}
780
781GCState markDrain(GCStateMachine *that, ExtraData &)
782{
783 if (that->deadline.isForever()) {
784 that->mm->markStack()->drain();
785 return GCState::MarkReady;
786 }
787 auto drainState = that->mm->m_markStack->drain(that->deadline);
788 return drainState == MarkStack::DrainState::Complete
789 ? GCState::MarkReady
790 : GCState::MarkDrain;
791}
792
793GCState markReady(GCStateMachine *that, ExtraData &)
794{
795 auto isIncrementalRun = [](GCStateMachine* that){
796 return !that->mm->aggressiveGC && that->timeLimit.count() > 0;
797 };
798
799 if (that->mm->crossValidateIncrementalGC && isIncrementalRun(that))
800 return GCState::CrossValidateIncrementalMarkPhase;
801 return GCState::InitCallDestroyObjects;
802}
803
804GCState crossValidateIncrementalMarkPhase(GCStateMachine *that, ExtraData &)
805{
806 struct {
807 Chunk* operator()(Chunk* chunk) { return chunk; }
808 Chunk* operator()(const HugeItemAllocator::HugeChunk& chunk) { return chunk.chunk; }
809 } getChunk{};
810
811 auto takeBlackBitmap = [&getChunk](auto& allocator, std::vector<quintptr>& storage){
812 for (auto chunk : allocator.chunks) {
813 for (auto& bitmap : getChunk(chunk)->blackBitmap) {
814 storage.push_back(bitmap);
815 }
816 getChunk(chunk)->resetBlackBits();
817 }
818 };
819
820 auto runMarkPhase = [](GCStateMachine* that) {
821 that->reset();
822 that->mm->m_markStack.reset();
823
824 while (that->state != GCStateMachine::MarkReady) {
825 GCStateInfo& stateInfo = that->stateInfoMap[int(that->state)];
826 that->state = stateInfo.execute(that, that->stateData);
827 }
828 };
829
830 auto checkBlackBitmap = [&that, &getChunk](auto& allocator, const std::vector<quintptr>& storedBitmap) {
831 auto reportError = [&allocator, &getChunk, &that](std::size_t chunk_index, std::size_t bitmap_index, uint bit_index){
832 #ifdef QT_BUILD_INTERNAL
833 // If we're collecting errors, don't output the debug message.
834 if (auto errors = that->bitmapErrors) {
835 errors->emplace_back(chunk_index, bitmap_index, bit_index);
836 return;
837 }
838 #endif
839
840 Q_UNUSED(that);
841 auto object = reinterpret_cast<Heap::Base*>(getChunk(allocator.chunks[chunk_index])->realBase() + (bit_index + (bitmap_index*Chunk::Bits)));
842 qDebug() << "Cross Validation Error on chunk" << chunk_index
843 << "on bitmap piece" << bitmap_index << "and bit" << bit_index
844 << ((object->internalClass) ? "With type" : "")
845 << ((object->internalClass) ?
846 Managed::typeToString(Managed::Type(object->internalClass->vtable->type)) : QString());
847 };
848
849 auto original = storedBitmap.begin();
850 for (std::size_t chunk_index = 0; original != storedBitmap.end() && chunk_index < allocator.chunks.size(); ++chunk_index) {
851 for (std::size_t bitmap_index = 0; bitmap_index < Chunk::EntriesInBitmap; ++bitmap_index) {
852 if (auto differences = (~(*original)) & getChunk(allocator.chunks[chunk_index])->blackBitmap[bitmap_index]) {
853 while (differences != 0) {
854 uint bit_index = qCountTrailingZeroBits(differences);
855 reportError(chunk_index, bitmap_index, bit_index);
856 differences ^= quintptr{1} << bit_index;
857 }
858 }
859 ++original;
860 }
861 }
862 };
863
864 #ifdef QT_BUILD_INTERNAL
865 if (auto *errors = that->bitmapErrors)
866 errors->clear();
867 #endif
868
869 std::vector<quintptr> blockBitmap{};
870 blockBitmap.reserve(Chunk::EntriesInBitmap * that->mm->blockAllocator.chunks.size());
871 takeBlackBitmap(that->mm->blockAllocator, blockBitmap);
872
873 std::vector<quintptr> hugeItemBitmap{};
874 hugeItemBitmap.reserve(Chunk::EntriesInBitmap * that->mm->hugeItemAllocator.chunks.size());
875 takeBlackBitmap(that->mm->hugeItemAllocator, hugeItemBitmap);
876
877 std::vector<quintptr> internalClassBitmap{};
878 internalClassBitmap.reserve(Chunk::EntriesInBitmap * that->mm->icAllocator.chunks.size());
879 takeBlackBitmap(that->mm->icAllocator, internalClassBitmap);
880
881 runMarkPhase(that);
882
883 checkBlackBitmap(that->mm->blockAllocator, blockBitmap);
884 checkBlackBitmap(that->mm->hugeItemAllocator, hugeItemBitmap);
885 checkBlackBitmap(that->mm->icAllocator, internalClassBitmap);
886
887 return GCState::InitCallDestroyObjects;
888}
889
890/** \!internal
891collects new references from the stack, then drains the mark stack again
892*/
893void redrain(GCStateMachine *that)
894{
895 that->mm->collectFromJSStack(that->mm->markStack());
896 that->mm->m_markStack->drain();
897}
898
899GCState initCallDestroyObjects(GCStateMachine *that, ExtraData &stateData)
900{
901 // as we don't have a deletion barrier, we need to rescan the stack
902 redrain(that);
903 if (!that->mm->m_weakValues)
904 return GCState::FreeWeakMaps; // no need to call destroy objects
905
906 // Decide, without interruption, which QObjectWrappers to destroy. Recheck unmarked wrappers in
907 // case they were reparented or taken over by C++ leaving them reachable but still unmarked.
908 ExecutionEngine *engine = that->mm->engine;
909 MarkStack *markStack = that->mm->markStack();
910 GCDestroyListStorage destroyList;
911 for (auto it = that->mm->m_weakValues->begin(); it.p; ++it) {
912 Managed *m = (*it).managed();
913 if (!m || m->markBit())
914 continue;
915 QObjectWrapper *qobjectWrapper = m->as<QObjectWrapper>();
916 if (!qobjectWrapper)
917 continue;
918 QObject *qobject = qobjectWrapper->object();
919 if (qobject && isKeptAlive(qobject, engine))
920 qobjectWrapper->mark(markStack);
921 else
922 destroyList.wrappers.push_back(qobjectWrapper->d());
923 }
924
925 // The wrappers we keep alive keep everything they reference alive, too.
926 markStack->drain();
927 std::vector<Heap::QObjectWrapper *> &wrappers = destroyList.wrappers;
928 const auto isMarked = [](Heap::QObjectWrapper *wrapper) { return wrapper->isMarked(); };
929 wrappers.erase(std::remove_if(wrappers.begin(), wrappers.end(), isMarked), wrappers.end());
930
931 stateData = std::move(destroyList);
932 return GCState::CallDestroyObjects;
933}
934
935GCState callDestroyObject(GCStateMachine *that, ExtraData &stateData)
936{
937 GCDestroyListStorage &destroyList = get<GCDestroyListStorage>(stateData);
938 // destroyObject might call user code, which really shouldn't call back into the gc
939 auto oldState = std::exchange(that->mm->gcBlocked, QV4::MemoryManager::Blockness::InCriticalSection);
940 auto cleanup = qScopeGuard([&]() {
941 that->mm->gcBlocked = oldState;
942 });
943 // avoid repeatedly hitting the timer constantly by batching iterations
944 for (int i = 0; i < MarkLoopIterationCount; ++i) {
945 if (destroyList.next == destroyList.wrappers.size()) {
946 stateData = std::monostate();
947 return GCState::FreeWeakMaps;
948 }
949
950 // The wrapper may have been marked since we took the decision, for example because
951 // a destruction handler stored a reference to it. We destroy it anyway (see above).
952 Value value = Value::fromHeapObject(destroyList.wrappers[destroyList.next++]);
953 QObjectWrapper *qobjectWrapper = value.as<QObjectWrapper>();
954 Q_ASSERT(qobjectWrapper);
955
956 // we need to call destroyObject on qobjectwrappers now, so that they can emit the destroyed
957 // signal before we start sweeping the heap
958 qobjectWrapper->destroyObject(/*lastSweep =*/false);
959 }
960 return GCState::CallDestroyObjects;
961}
962
963void freeWeakMaps(MemoryManager *mm)
964{
965 for (auto [map, lastMap] = std::tuple {mm->weakMaps, &mm->weakMaps }; map; map = map->nextWeakMap) {
966 if (!map->isMarked())
967 continue;
968 map->removeUnmarkedKeys();
969 *lastMap = map;
970 lastMap = &map->nextWeakMap;
971 }
972}
973
974GCState freeWeakMaps(GCStateMachine *that, ExtraData &)
975{
976 freeWeakMaps(that->mm);
977 return GCState::FreeWeakSets;
978}
979
980void freeWeakSets(MemoryManager *mm)
981{
982 for (auto [set, lastSet] = std::tuple {mm->weakSets, &mm->weakSets}; set; set = set->nextWeakSet) {
983
984 if (!set->isMarked())
985 continue;
986 set->removeUnmarkedKeys();
987 *lastSet = set;
988 lastSet = &set->nextWeakSet;
989 }
990}
991
992GCState freeWeakSets(GCStateMachine *that, ExtraData &)
993{
994 freeWeakSets(that->mm);
995 return GCState::HandleQObjectWrappers;
996}
997
998GCState handleQObjectWrappers(GCStateMachine *that, ExtraData &)
999{
1000 that->mm->cleanupDeletedQObjectWrappersInSweep();
1001 return GCState::DoSweep;
1002}
1003
1004GCState doSweep(GCStateMachine *that, ExtraData &)
1005{
1006 auto mm = that->mm;
1007
1008 mm->engine->identifierTable->sweep();
1009 mm->blockAllocator.sweep();
1010 mm->hugeItemAllocator.sweep();
1011 mm->icAllocator.sweep();
1012
1013 // reset all black bits
1014 mm->blockAllocator.resetBlackBits();
1015 mm->hugeItemAllocator.resetBlackBits();
1016 mm->icAllocator.resetBlackBits();
1017
1018 mm->usedSlotsAfterLastFullSweep = mm->blockAllocator.usedSlotsAfterLastSweep + mm->icAllocator.usedSlotsAfterLastSweep;
1019 mm->gcBlocked = MemoryManager::Unblocked;
1020 mm->m_markStack.reset();
1021 mm->engine->isGCOngoing = false;
1022
1023 mm->updateUnmanagedHeapSizeGCLimit();
1024
1025 mm->m_persistentValues->deallocateEmptyPages();
1026 mm->m_weakValues->deallocateEmptyPages();
1027
1028 return GCState::Invalid;
1029}
1030
1031}
1032
1033
1035 : engine(engine)
1043 , aggressiveGC(!qEnvironmentVariableIsEmpty("QV4_MM_AGGRESSIVE_GC"))
1044 , crossValidateIncrementalGC(qEnvironmentVariableIsSet("QV4_MM_CROSS_VALIDATE_INCREMENTAL_GC"))
1049{
1050#ifdef V4_USE_VALGRIND
1051 VALGRIND_CREATE_MEMPOOL(this, 0, true);
1052#endif
1053 if (statistics) {
1056 }
1057
1059 gcStateMachine->mm = this;
1060
1062 markStart,
1063 false,
1064 };
1067 false,
1068 };
1071 false,
1072 };
1075 false,
1076 };
1079 false,
1080 };
1083 false,
1084 };
1087 false,
1088 };
1090 markDrain,
1091 false,
1092 };
1094 markReady,
1095 false,
1096 };
1099 false,
1100 };
1103 false,
1104 };
1107 false,
1108 };
1111 false,
1112 };
1115 true, // ensure that handleQObjectWrappers runs in isolation
1116 };
1119 false,
1120 };
1122 doSweep,
1123 false,
1124 };
1125}
1126
1140
1142{
1143#ifdef MM_STATS
1146#endif
1147
1149 Q_ASSERT(size % Chunk::SlotSize == 0);
1150
1152 memset(m, 0, size);
1153 return *m;
1154}
1155
1157{
1159 Q_ASSERT(!(size % sizeof(HeapItem)));
1160
1161 Heap::Object *o;
1163 o = static_cast<Heap::Object *>(allocData(size));
1164 } else {
1165 // Allocate both in one go through the block allocator
1167 std::size_t memberSize = align(sizeof(Heap::MemberData) + (nMembers - 1)*sizeof(Value));
1169 Heap::MemberData *m;
1170 if (totalSize > Chunk::DataSize) {
1171 o = static_cast<Heap::Object *>(allocData(size));
1173 } else {
1174 HeapItem *mh = reinterpret_cast<HeapItem *>(allocData(totalSize));
1175 Heap::Base *b = *mh;
1176 o = static_cast<Heap::Object *>(b);
1177 mh += (size >> Chunk::SlotSizeShift);
1178 m = mh->as<Heap::MemberData>();
1179 Chunk *c = mh->chunk();
1180 size_t index = mh - c->realBase();
1183 }
1185 o->memberData.set(engine, m);
1187 m->values.alloc = static_cast<uint>((memberSize - sizeof(Heap::MemberData) + sizeof(Value))/sizeof(Value));
1189 m->init();
1190 }
1191
1192 return o;
1193}
1194
1196 : m_engine(engine)
1197{
1198 m_base = (Heap::Base **)engine->gcStack->base();
1199 m_top = m_base;
1200 const size_t size = engine->maxGCStackSize() / sizeof(Heap::Base);
1202 m_softLimit = m_base + size * 3 / 4;
1203}
1204
1206{
1207 // we're not calling drain(QDeadlineTimer::Forever) as that has higher overhead
1208 while (m_top > m_base) {
1209 Heap::Base *h = pop();
1210 Q_ASSERT(h); // at this point we should only have Heap::Base objects in this area on the stack. If not, weird things might happen.
1213 }
1214}
1215
1217{
1218 do {
1219 for (int i = 0; i <= MarkLoopIterationCountForDrain; ++i) {
1220 if (m_top == m_base)
1221 return DrainState::Complete;
1222 Heap::Base *h = pop();
1223 Q_ASSERT(h); // at this point we should only have Heap::Base objects in this area on the stack. If not, weird things might happen.
1226 }
1227 } while (!deadline.hasExpired());
1228 return DrainState::Ongoing;
1229}
1230
1236
1238{
1239 if (engine->inShutdown)
1240 return;
1243 onEventLoop();
1244 }, Qt::QueuedConnection);
1245 return;
1246 }
1247 if (!gcStateMachine->inProgress())
1248 return;
1249
1250 if (collectorStatistics) {
1252 if (!gcStateMachine->inProgress())
1253 collectorStatistics->end(this);
1254 } else {
1256 }
1257}
1258
1259
1264
1266{
1267
1269 Managed *m = (*it).managed();
1270 if (!m || m->markBit())
1271 continue;
1272 // we need to call destroyObject on qobjectwrappers now, so that they can emit the destroyed
1273 // signal before we start sweeping the heap
1275 qobjectWrapper->destroyObject(/*lastSweep = */ true);
1276 }
1277 }
1278
1279 freeWeakMaps(this);
1280 freeWeakSets(this);
1281
1283
1284 // reset all black bits
1288
1292}
1293
1294/*
1295 \internal
1296 Helper function used in sweep to clean up the (to-be-freed) QObjectWrapper
1297 Used both in MemoryManager::sweep, and the corresponding gc statemachine phase
1298*/
1300{
1301 // onDestruction handlers may have accessed other QObject wrappers and reset their value, so ensure
1302 // that they are all set to undefined.
1304 Managed *m = (*it).managed();
1305 if (!m || m->markBit())
1306 continue;
1307 (*it) = Value::undefinedValue();
1308 }
1309
1310 // Now it is time to free QV4::QObjectWrapper Value, we must check the Value's tag to make sure its object has been destroyed
1312 if (pendingCount) {
1315 for (int i = 0; i < pendingCount; ++i) {
1317 if (v->isUndefined() || v->isEmpty())
1319 else
1321 }
1323 }
1324
1327 if (it.value().isNullOrUndefined())
1329 else
1330 ++it;
1331 }
1332 }
1333}
1334
1335bool MemoryManager::shouldRunGC() const
1336{
1339 return true;
1340 return false;
1341}
1342
1343static size_t dumpBins(BlockAllocator *b, const char *title)
1344{
1345 const QLoggingCategory &stats = lcGcAllocatorStats();
1346 size_t totalSlotMem = 0;
1347 if (title)
1348 qDebug(stats) << "Slot map for" << title << "allocator:";
1349 for (uint i = 0; i < BlockAllocator::NumBins; ++i) {
1350 uint nEntries = 0;
1351 HeapItem *h = b->freeBins[i];
1352 while (h) {
1353 ++nEntries;
1354 totalSlotMem += h->freeData.availableSlots;
1355 h = h->freeData.next;
1356 }
1357 if (title)
1358 qDebug(stats) << " number of entries in slot" << i << ":" << nEntries;
1359 }
1360 SDUMP() << " large slot map";
1361 HeapItem *h = b->freeBins[BlockAllocator::NumBins - 1];
1362 while (h) {
1363 SDUMP() << " " << Qt::hex << (quintptr(h)/32) << h->freeData.availableSlots;
1364 h = h->freeData.next;
1365 }
1366
1367 if (title)
1368 qDebug(stats) << " total mem in bins" << totalSlotMem*Chunk::SlotSize;
1369 return totalSlotMem*Chunk::SlotSize;
1370}
1371
1372/*!
1373 \internal
1374 Precondition: Incremental garbage collection must be currently active
1375 Finishes incremental garbage collection, unless in a critical section
1376 Code entering a critical section is expected to check if we need to
1377 force a gc completion, and to trigger the gc again if necessary
1378 when exiting the critcial section.
1379 Returns \c true if the gc cycle completed, false otherwise.
1380 */
1382{
1385 << "Tried to force the GC to complete a run but failed due to being in a critical section.";
1386 return false;
1387 }
1388
1389 const bool incrementalGCIsAlreadyRunning = m_markStack != nullptr;
1391
1392 qCDebug(lcGcForcedRuns) << "Forcing the GC to complete a run.";
1393
1395 if (collectorStatistics) {
1396 while (gcStateMachine->inProgress())
1398 collectorStatistics->end(this);
1399 } else {
1400 while (gcStateMachine->inProgress())
1402 }
1403
1405 return true;
1406}
1407
1409{
1410 runGC();
1411 if (m_markStack != nullptr)
1413}
1414
1416{
1417 if (gcBlocked != Unblocked) {
1418 return;
1419 }
1420
1422
1423 if (statistics) {
1428 }
1429
1430 if (collectorStatistics) {
1431 if (!gcStateMachine->inProgress())
1434 if (!gcStateMachine->inProgress())
1435 collectorStatistics->end(this);
1436 } else {
1438 }
1439
1440
1441 if (statistics) {
1444 }
1445}
1446
1451
1456
1461
1463{
1465 // more than 75% full, raise limit
1467 unmanagedHeapSize) * 2;
1468 } else if (unmanagedHeapSize * 4 <= unmanagedHeapSizeGCLimit) {
1469 // less than 25% full, lower limit
1472 }
1473
1474 if (aggressiveGC && !engine->inShutdown) {
1475 // ensure we don't 'loose' any memory
1476 // but not during shutdown, because than we skip parts of sweep
1477 // and use freeAll instead
1479 == blockAllocator.usedMem() + dumpBins(&blockAllocator, nullptr));
1481 == icAllocator.usedMem() + dumpBins(&icAllocator, nullptr));
1482 }
1483}
1484
1490
1496
1498{
1499 delete m_persistentValues;
1500 dumpStats();
1501
1502 // do one last non-incremental sweep to clean up C++ objects
1503 // first, abort any on-going incremental gc operation
1504 setGCTimeLimit(-1);
1505 if (engine->isGCOngoing) {
1506 engine->isGCOngoing = false;
1507 // Aborting the incremental run drops the mark stack, so we must also clear the
1508 // blocked state. Otherwise the final sweep below runs destruction handlers with
1509 // gcBlocked still set, and any GCCriticalSection they open would try to mark
1510 // through the now-absent mark stack.
1517 }
1518 // then sweep
1519 lastSweep();
1520
1524
1525 delete m_weakValues;
1526#ifdef V4_USE_VALGRIND
1528#endif
1529 delete chunkAllocator;
1530}
1531
1532
1534{
1535 if (!statistics)
1536 return;
1537
1538 const QLoggingCategory &stats = lcGcStats();
1539 qDebug(stats) << "Qml GC memory allocation statistics:";
1540 qDebug(stats) << "Total memory allocated:" << statistics->maxAllocatedMem;
1541 qDebug(stats) << "Max memory used before a GC run:" << statistics->maxUsedBeforeGC;
1542 qDebug(stats) << "Max memory used after a GC run:" << statistics->maxUsedAfterGC;
1543 qDebug(stats) << "Requests for different item sizes:";
1544 for (int i = 1; i < BlockAllocator::NumBins - 1; ++i)
1545 qDebug(stats) << " <" << (i << Chunk::SlotSizeShift) << " bytes: " << statistics->allocations[i];
1546 qDebug(stats) << " >=" << ((BlockAllocator::NumBins - 1) << Chunk::SlotSizeShift) << " bytes: " << statistics->allocations[BlockAllocator::NumBins - 1];
1547}
1548
1550{
1553 while (v < top) {
1554 Managed *m = v->managed();
1555 if (m) {
1556 Q_ASSERT(m->inUse());
1557 // Skip pointers to already freed objects, they are bogus as well
1558 m->mark(markStack);
1559 }
1560 ++v;
1561 }
1562
1563 for (auto *frame = engine->currentStackFrame; frame; frame = frame->parentFrame()) {
1564 if (frame->isJSTypesFrame()) {
1565 // Generator frames don't live on the JS stack, but in a heap object that the
1566 // interpreter writes to without write barrier.
1568 static_cast<const JSTypesStackFrame *>(frame)->markJSFrame(markStack);
1569 continue;
1570 }
1571
1573 = static_cast<const MetaTypesStackFrame *>(frame)->locals()) {
1574 // Actual AOT-compiled functions initialize the locals firsth thing when they
1575 // are called. However, the ScopedStackFrame has no locals, but still uses a
1576 // MetaTypesStackFrame.
1578 }
1579 }
1580}
1581
1584{
1585 // base assumption: target 60fps, use at most 1/3 of time for gc
1586 // unless overridden by env variable
1587 bool ok = false;
1588 auto envTimeLimit = qEnvironmentVariableIntValue("QV4_GC_TIMELIMIT", &ok );
1589 if (!ok)
1590 envTimeLimit = (1000 / 60) / 3;
1591 if (envTimeLimit > 0)
1593 else
1594 timeLimit = std::chrono::milliseconds { 0 };
1595}
1596
1597static void logStepTiming(GCStateMachine* that, quint64 timing) {
1598 auto registerTimingWithResetOnOverflow = [](
1599 GCStateMachine::StepTiming& storage, quint64 timing, GCState state
1600 ) {
1601 auto wouldOverflow = [](quint64 lhs, quint64 rhs) {
1602 return rhs > 0 && lhs > std::numeric_limits<quint64>::max() - rhs;
1603 };
1604
1605 if (wouldOverflow(storage.rolling_sum, timing) || wouldOverflow(storage.count, 1)) {
1606 qDebug(lcGcStepExecution) << "Resetting timings storage for"
1607 << QMetaEnum::fromType<GCState>().key(state) << "due to overflow.";
1608 storage.rolling_sum = timing;
1609 storage.count = 1;
1610 } else {
1611 storage.rolling_sum += timing;
1612 storage.count += 1;
1613 }
1614 };
1615
1616 GCStateMachine::StepTiming& storage = that->executionTiming[that->state];
1617 registerTimingWithResetOnOverflow(storage, timing, that->state);
1618
1619 qDebug(lcGcStepExecution) << "Performed" << QMetaEnum::fromType<GCState>().key(that->state)
1620 << "in" << timing << "microseconds";
1621 qDebug(lcGcStepExecution) << "This step was performed" << storage.count << " time(s), executing in"
1622 << (storage.rolling_sum / storage.count) << "microseconds on average.";
1623}
1624
1625static GCState executeWithLoggingIfEnabled(GCStateMachine* that, GCStateInfo& stateInfo) {
1626 if (!that->collectTimings)
1627 return stateInfo.execute(that, that->stateData);
1628
1629 QElapsedTimer timer;
1630 timer.start();
1631 GCState next = stateInfo.execute(that, that->stateData);
1632 logStepTiming(that, timer.nsecsElapsed()/1000);
1633 return next;
1634}
1635
1636static void redrainDuringSweep(GCStateMachine *that)
1637{
1638 if (that->state > GCState::InitCallDestroyObjects) {
1639 /* initCallDestroyObjects is the last action which drains the mark
1640 stack by default. But as our write-barrier might end up putting
1641 objects on the markStack which still reference other objects.
1642 Especially when we call user code triggered by Component.onDestruction,
1643 but also when we run into a timeout.
1644 We don't redrain before InitCallDestroyObjects, as that would
1645 potentially lead to useless busy-work (e.g., if the last referencs
1646 to objects are removed while the mark phase is running)
1647 */
1648 redrain(that);
1649 }
1650}
1651
1653 if (timeLimit.count() > 0) {
1655 bool deadlineExpired = false;
1656 do {
1657 redrainDuringSweep(this);
1658 qCDebug(lcGcStateTransitions) << "Preparing to execute the"
1659 << QMetaEnum::fromType<GCState>().key(state) << "state";
1662 qCDebug(lcGcStateTransitions) << "Transitioning to the"
1663 << QMetaEnum::fromType<GCState>().key(state) << "state";
1665 break;
1666 } while (!(deadlineExpired = deadline.hasExpired()) && state != GCState::Invalid);
1667 if (deadlineExpired)
1669 if (state != GCState::Invalid)
1671 mm->onEventLoop();
1672 }, Qt::QueuedConnection);
1673 } else {
1675 while (state != GCState::Invalid) {
1676 redrainDuringSweep(this);
1677 qCDebug(lcGcStateTransitions) << "Preparing to execute the"
1678 << QMetaEnum::fromType<GCState>().key(state) << "state";
1681 qCDebug(lcGcStateTransitions) << "Transitioning to the"
1682 << QMetaEnum::fromType<GCState>().key(state) << "state";
1683 }
1684 }
1685}
1686
1699
1701{
1703
1709
1710 qDebug(stats) << "========== GC ==========";
1711#ifdef MM_STATS
1712 qDebug(stats) << " Triggered by alloc request of" << mm->lastAllocRequestedSlots << "slots.";
1713 qDebug(stats) << " Allocations since last GC" << mm->allocationCount;
1714 mm->allocationCount = 0;
1715#endif
1717 qDebug(stats) << "Allocated" << allocatedMem << "bytes in" << oldChunks << "chunks";
1718 qDebug(stats) << "Fragmented memory before GC" << (allocatedMem - regularItemsBefore);
1719 dumpBins(&mm->blockAllocator, "Block");
1720 dumpBins(&mm->icAllocator, "InternalClass");
1721}
1722
1730
1732{
1734
1737
1739 qDebug(stats) << "triggered by unmanaged heap:";
1740 qDebug(stats) << " old unmanaged heap size:" << oldUnmanagedSize;
1741 qDebug(stats) << " new unmanaged heap:" << mm->unmanagedHeapSize;
1742 qDebug(stats) << " unmanaged heap limit:" << mm->unmanagedHeapSizeGCLimit;
1743 }
1744 const size_t memInBins = dumpBins(&mm->blockAllocator, "Block")
1745 + dumpBins(&mm->icAllocator, "InternalClasss");
1746 qDebug(stats) << "Garbage collection took" << (gcTime / 1000) << "us.";
1747
1748 qDebug(stats) << "Regular item memory before GC:" << regularItemsBefore;
1749 qDebug(stats) << "Regular item memory after GC:" << regularItemsAfter;
1750 qDebug(stats) << "Freed up bytes :" << (regularItemsBefore - regularItemsAfter);
1751 qDebug(stats) << "Freed up chunks :" << (oldChunks - mm->blockAllocator.chunks.size());
1754 if (lost)
1755 qDebug(stats) << "!!!!!!!!!!!!!!!!!!!!! LOST MEM:" << lost << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!";
1757 qDebug(stats) << "Large item memory before GC:" << largeItemsBefore;
1758 qDebug(stats) << "Large item memory after GC:" << largeItemsAfter;
1759 qDebug(stats) << "Large item memory freed up:" << (largeItemsBefore - largeItemsAfter);
1760 }
1761
1762 qDebug(stats) << "======== End GC ========";
1763}
1764
1765} // namespace QV4
1766
1767QT_END_NAMESPACE
1768
1769#include "moc_qv4mm_p.cpp"
Definition qjsvalue.h:24
static void logStepTiming(GCStateMachine *that, quint64 timing)
Definition qv4mm.cpp:1597
static size_t dumpBins(BlockAllocator *b, const char *title)
Definition qv4mm.cpp:1343
QString binary(quintptr)
Definition qv4mm.cpp:254
@ MinSlotsGCLimit
Definition qv4mm.cpp:74
@ GCOverallocation
Definition qv4mm.cpp:75
static void freeHugeChunk(ChunkAllocator *chunkAllocator, const HugeItemAllocator::HugeChunk &c)
Definition qv4mm.cpp:592
static GCState executeWithLoggingIfEnabled(GCStateMachine *that, GCStateInfo &stateInfo)
Definition qv4mm.cpp:1625
static void redrainDuringSweep(GCStateMachine *that)
Definition qv4mm.cpp:1636
QT_BEGIN_NAMESPACE Q_STATIC_LOGGING_CATEGORY(lcSynthesizedIterableAccess, "qt.iterable.synthesized", QtWarningMsg)
#define SDUMP
Definition qv4mm.cpp:255
#define MM_STATS
Definition qv4mm.cpp:35
void free(Chunk *chunk, size_t size=0)
Definition qv4mm.cpp:233
size_t requiredChunkSize(size_t size)
Definition qv4mm.cpp:200
Chunk * allocate(size_t size=0)
Definition qv4mm.cpp:215
std::vector< MemorySegment > memorySegments
Definition qv4mm.cpp:212
void free(Chunk *chunk, size_t size)
Definition qv4mm.cpp:131
Chunk * allocate(size_t size)
Definition qv4mm.cpp:164
MemorySegment(size_t size)
Definition qv4mm.cpp:88
PageReservation pageReservation
Definition qv4mm.cpp:157
void setBit(size_t index)
Definition qv4mm.cpp:114
size_t availableBytes
Definition qv4mm.cpp:160
bool testBit(size_t index) const
Definition qv4mm.cpp:124
quint64 allocatedMap
Definition qv4mm.cpp:159
void clearBit(size_t index)
Definition qv4mm.cpp:119
bool contains(Chunk *c) const
Definition qv4mm.cpp:153
MemorySegment(MemorySegment &&other)
Definition qv4mm.cpp:101