5#include "PageAllocation.h"
6#include "PageReservation.h"
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>
20#include <QtQml/qqmlengine.h>
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>
34#if !defined(MM_STATS) && !defined(QT_NO_DEBUG)
39#define DEBUG qDebug() << "MM:"
41#define DEBUG if (1
) ; else qDebug() << "MM:"
45#include <valgrind/valgrind.h>
46#include <valgrind/memcheck.h>
49#ifdef V4_USE_HEAPTRACK
50#include <heaptrack_api.h>
54#include <sys/storage.h>
57#if USE(PTHREADS) && HAVE(PTHREAD_NP_H)
58#include <pthread_np.h>
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")
81 NumChunks =
sizeof(quint64),
90 size += Chunk::ChunkSize;
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)
102 qSwap(pageReservation, other.pageReservation);
103 qSwap(base, other.base);
104 qSwap(allocatedMap, other.allocatedMap);
105 qSwap(availableBytes, other.availableBytes);
111 pageReservation.deallocate();
116 quint64 bit =
static_cast<quint64>(1) << index;
121 quint64 bit =
static_cast<quint64>(1) << index;
122 allocatedMap &= ~bit;
126 quint64 bit =
static_cast<quint64>(1) << index;
127 return (allocatedMap & bit);
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));
141 size_t pageSize = WTF::pageSize();
142 size = (size + pageSize - 1) & ~(pageSize - 1);
143#if !defined(Q_OS_LINUX) && !defined(Q_OS_WIN)
148 memset(chunk, 0, size);
150 pageReservation.decommit(chunk, size);
154 return c >= base && c < base + nChunks;
166 if (!allocatedMap && size >= SegmentSize) {
168 Q_ASSERT(availableBytes >= size);
169 pageReservation.commit(base, size);
170 allocatedMap = ~
static_cast<quint64>(0);
173 size_t requiredChunks = (size +
sizeof(Chunk) - 1)/
sizeof(Chunk);
175 Chunk *candidate =
nullptr;
176 for (uint i = 0; i <
nChunks; ++i) {
179 candidate = base + i;
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;
201 size += Chunk::HeaderSize;
202 size_t pageSize = WTF::pageSize();
203 size = (size + pageSize - 1) & ~(pageSize - 1);
204 if (size < Chunk::ChunkSize)
205 size = Chunk::ChunkSize;
210 void free(Chunk *chunk, size_t size = 0);
217 size = requiredChunkSize(size);
218 for (
auto &m : memorySegments) {
219 if (~m.allocatedMap) {
220 Chunk *c = m.allocate(size);
227 memorySegments.push_back(MemorySegment(size));
228 Chunk *c = memorySegments.back().allocate(size);
235 size = requiredChunkSize(size);
236 for (
auto &m : memorySegments) {
237 if (m.contains(chunk)) {
255#define SDUMP if (1
) ; else qDebug
261 SDUMP() <<
"sweeping chunk" <<
this;
275 SDUMP() <<
" index=" <<
i;
304#ifdef V4_USE_HEAPTRACK
349#ifdef V4_USE_HEAPTRACK
369#if QT_POINTER_SIZE == 8
379#if QT_POINTER_SIZE == 8
449 while ((
m = *
last)) {
519#ifdef V4_USE_HEAPTRACK
586#ifdef V4_USE_HEAPTRACK
594 HeapItem *itemToFree = c.chunk->first();
595 Heap::Base *b = *itemToFree;
596 const VTable *v = b->internalClass->vtable;
602 c.segment->free(c.chunk, c.size);
605 chunkAllocator->free(c.chunk, c.size);
607#ifdef V4_USE_HEAPTRACK
608 heaptrack_report_free(c.chunk);
643using ExtraData = GCStateInfo::ExtraData;
644GCState markStart(GCStateMachine *that, ExtraData &)
647 that->mm->m_markStack = std::make_unique<MarkStack>(that->mm->engine);
648 that->mm->engine->isGCOngoing =
true;
649 return GCState::MarkGlobalObject;
652GCState markGlobalObject(GCStateMachine *that, ExtraData &)
654 that->mm->engine->markObjects(that->mm->m_markStack.get());
655 return GCState::MarkJSStack;
658GCState markJSStack(GCStateMachine *that, ExtraData &)
660 that->mm->collectFromJSStack(that->mm->markStack());
661 return GCState::InitMarkPersistentValues;
664GCState initMarkPersistentValues(GCStateMachine *that, ExtraData &stateData)
666 if (!that->mm->m_persistentValues)
667 return GCState::InitMarkWeakValues;
668 stateData = GCIteratorStorage { that->mm->m_persistentValues->begin() };
669 return GCState::MarkPersistentValues;
673 MarkLoopIterationCount = 1024,
674 MarkLoopIterationCountForDrain = 10240,
677bool wasDrainNecessary(MarkStack *ms, QDeadlineTimer deadline)
679 if (ms->remainingBeforeSoftLimit() > MarkLoopIterationCount)
686QObject *parentChainRoot(
const QObject *qobject)
688 QObject *root = qobject->parent();
692 while (QObject *parent = root->parent())
697bool hasMarkedWrapper(
const QObject *qobject, ExecutionEngine *engine)
699 QQmlData *ddata = QQmlData::get(qobject);
703 const auto isMarked = [](ReturnedValue wrapper) {
704 Heap::Base *heapObject = Value::fromReturnedValue(wrapper).heapObject();
705 return heapObject && heapObject->isMarked();
708 MultiplyWrappedQObjectMap *otherWrappers = engine->m_multiplyWrappedQObjects;
709 if (ddata->jsEngineId == engine->m_engineId) {
710 if (isMarked(ddata->jsWrapper.value()))
712 }
else if (otherWrappers && ddata->hasTaintedV4Object) {
713 if (isMarked(otherWrappers->value(qobject)))
717 return ddata->hasConstWrapper && otherWrappers && isMarked(otherWrappers->value(qobject));
723bool isKeptAlive(
const QObject *qobject, ExecutionEngine *engine =
nullptr)
725 if (QQmlData::keepAliveDuringGarbageCollection(qobject))
728 const QObject *root = parentChainRoot(qobject);
732 return QQmlData::keepAliveDuringGarbageCollection(root)
733 || (engine && hasMarkedWrapper(root, engine));
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;
742 for (
int i = 0; i < MarkLoopIterationCount; ++i) {
744 return GCState::InitMarkWeakValues;
745 if (Managed *m = (*it).as<Managed>())
749 return GCState::MarkPersistentValues;
752GCState initMarkWeakValues(GCStateMachine *that, ExtraData &stateData)
754 stateData = GCIteratorStorage { that->mm->m_weakValues->begin() };
755 return GCState::MarkWeakValues;
758GCState markWeakValues(GCStateMachine *that, ExtraData &stateData)
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;
765 for (
int i = 0; i < MarkLoopIterationCount; ++i) {
767 return GCState::MarkDrain;
768 QObjectWrapper *qobjectWrapper = (*it).as<QObjectWrapper>();
772 QObject *qobject = qobjectWrapper->object();
775 if (isKeptAlive(qobject))
776 qobjectWrapper->mark(that->mm->markStack());
778 return GCState::MarkWeakValues;
781GCState markDrain(GCStateMachine *that, ExtraData &)
783 if (that->deadline.isForever()) {
784 that->mm->markStack()->drain();
785 return GCState::MarkReady;
787 auto drainState = that->mm->m_markStack->drain(that->deadline);
788 return drainState == MarkStack::DrainState::Complete
790 : GCState::MarkDrain;
793GCState markReady(GCStateMachine *that, ExtraData &)
795 auto isIncrementalRun = [](GCStateMachine* that){
796 return !that->mm->aggressiveGC && that->timeLimit.count() > 0;
799 if (that->mm->crossValidateIncrementalGC && isIncrementalRun(that))
800 return GCState::CrossValidateIncrementalMarkPhase;
801 return GCState::InitCallDestroyObjects;
804GCState crossValidateIncrementalMarkPhase(GCStateMachine *that, ExtraData &)
807 Chunk* operator()(Chunk* chunk) {
return chunk; }
808 Chunk* operator()(
const HugeItemAllocator::HugeChunk& chunk) {
return chunk.chunk; }
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);
816 getChunk(chunk)->resetBlackBits();
820 auto runMarkPhase = [](GCStateMachine* that) {
822 that->mm->m_markStack.reset();
824 while (that->state != GCStateMachine::MarkReady) {
825 GCStateInfo& stateInfo = that->stateInfoMap[
int(that->state)];
826 that->state = stateInfo.execute(that, that->stateData);
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
834 if (
auto errors = that->bitmapErrors) {
835 errors->emplace_back(chunk_index, bitmap_index, bit_index);
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());
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;
864 #ifdef QT_BUILD_INTERNAL
865 if (
auto *errors = that->bitmapErrors)
869 std::vector<quintptr> blockBitmap{};
870 blockBitmap.reserve(Chunk::EntriesInBitmap * that->mm->blockAllocator.chunks.size());
871 takeBlackBitmap(that->mm->blockAllocator, blockBitmap);
873 std::vector<quintptr> hugeItemBitmap{};
874 hugeItemBitmap.reserve(Chunk::EntriesInBitmap * that->mm->hugeItemAllocator.chunks.size());
875 takeBlackBitmap(that->mm->hugeItemAllocator, hugeItemBitmap);
877 std::vector<quintptr> internalClassBitmap{};
878 internalClassBitmap.reserve(Chunk::EntriesInBitmap * that->mm->icAllocator.chunks.size());
879 takeBlackBitmap(that->mm->icAllocator, internalClassBitmap);
883 checkBlackBitmap(that->mm->blockAllocator, blockBitmap);
884 checkBlackBitmap(that->mm->hugeItemAllocator, hugeItemBitmap);
885 checkBlackBitmap(that->mm->icAllocator, internalClassBitmap);
887 return GCState::InitCallDestroyObjects;
891
892
893void redrain(GCStateMachine *that)
895 that->mm->collectFromJSStack(that->mm->markStack());
896 that->mm->m_markStack->drain();
899GCState initCallDestroyObjects(GCStateMachine *that, ExtraData &stateData)
903 if (!that->mm->m_weakValues)
904 return GCState::FreeWeakMaps;
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())
915 QObjectWrapper *qobjectWrapper = m->as<QObjectWrapper>();
918 QObject *qobject = qobjectWrapper->object();
919 if (qobject && isKeptAlive(qobject, engine))
920 qobjectWrapper->mark(markStack);
922 destroyList.wrappers.push_back(qobjectWrapper->d());
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());
931 stateData =
std::move(destroyList);
932 return GCState::CallDestroyObjects;
935GCState callDestroyObject(GCStateMachine *that, ExtraData &stateData)
937 GCDestroyListStorage &destroyList = get<GCDestroyListStorage>(stateData);
939 auto oldState = std::exchange(that->mm->gcBlocked, QV4::MemoryManager::Blockness::InCriticalSection);
940 auto cleanup = qScopeGuard([&]() {
941 that->mm->gcBlocked = oldState;
944 for (
int i = 0; i < MarkLoopIterationCount; ++i) {
945 if (destroyList.next == destroyList.wrappers.size()) {
946 stateData = std::monostate();
947 return GCState::FreeWeakMaps;
952 Value value = Value::fromHeapObject(destroyList.wrappers[destroyList.next++]);
953 QObjectWrapper *qobjectWrapper = value.as<QObjectWrapper>();
954 Q_ASSERT(qobjectWrapper);
958 qobjectWrapper->destroyObject(
false);
960 return GCState::CallDestroyObjects;
963void freeWeakMaps(MemoryManager *mm)
965 for (
auto [map, lastMap] =
std::tuple {mm->weakMaps, &mm->weakMaps }; map; map = map->nextWeakMap) {
966 if (!map->isMarked())
968 map->removeUnmarkedKeys();
970 lastMap = &map->nextWeakMap;
974GCState freeWeakMaps(GCStateMachine *that, ExtraData &)
976 freeWeakMaps(that->mm);
977 return GCState::FreeWeakSets;
980void freeWeakSets(MemoryManager *mm)
982 for (
auto [set, lastSet] =
std::tuple {mm->weakSets, &mm->weakSets}; set; set = set->nextWeakSet) {
984 if (!set->isMarked())
986 set->removeUnmarkedKeys();
988 lastSet = &set->nextWeakSet;
992GCState freeWeakSets(GCStateMachine *that, ExtraData &)
994 freeWeakSets(that->mm);
995 return GCState::HandleQObjectWrappers;
998GCState handleQObjectWrappers(GCStateMachine *that, ExtraData &)
1000 that->mm->cleanupDeletedQObjectWrappersInSweep();
1001 return GCState::DoSweep;
1004GCState doSweep(GCStateMachine *that, ExtraData &)
1008 mm->engine->identifierTable->sweep();
1009 mm->blockAllocator.sweep();
1010 mm->hugeItemAllocator.sweep();
1011 mm->icAllocator.sweep();
1014 mm->blockAllocator.resetBlackBits();
1015 mm->hugeItemAllocator.resetBlackBits();
1016 mm->icAllocator.resetBlackBits();
1018 mm->usedSlotsAfterLastFullSweep = mm->blockAllocator.usedSlotsAfterLastSweep + mm->icAllocator.usedSlotsAfterLastSweep;
1019 mm->gcBlocked = MemoryManager::Unblocked;
1020 mm->m_markStack.reset();
1021 mm->engine->isGCOngoing =
false;
1023 mm->updateUnmanagedHeapSizeGCLimit();
1025 mm->m_persistentValues->deallocateEmptyPages();
1026 mm->m_weakValues->deallocateEmptyPages();
1028 return GCState::Invalid;
1050#ifdef V4_USE_VALGRIND
1295
1296
1297
1298
1345 const QLoggingCategory &stats = lcGcAllocatorStats();
1346 size_t totalSlotMem = 0;
1348 qDebug(stats) <<
"Slot map for" << title <<
"allocator:";
1349 for (uint i = 0; i < BlockAllocator::NumBins; ++i) {
1351 HeapItem *h = b->freeBins[i];
1354 totalSlotMem += h->freeData.availableSlots;
1355 h = h->freeData.next;
1358 qDebug(stats) <<
" number of entries in slot" << i <<
":" << nEntries;
1360 SDUMP() <<
" large slot map";
1361 HeapItem *h = b->freeBins[BlockAllocator::NumBins - 1];
1363 SDUMP() <<
" " << Qt::hex << (quintptr(h)/32) << h->freeData.availableSlots;
1364 h = h->freeData.next;
1368 qDebug(stats) <<
" total mem in bins" << totalSlotMem*Chunk::SlotSize;
1369 return totalSlotMem*Chunk::SlotSize;
1373
1374
1375
1376
1377
1378
1379
1380
1385 <<
"Tried to force the GC to complete a run but failed due to being in a critical section.";
1526#ifdef V4_USE_VALGRIND
1539 qDebug(
stats) <<
"Qml GC memory allocation statistics:";
1543 qDebug(
stats) <<
"Requests for different item sizes:";
1598 auto registerTimingWithResetOnOverflow = [](
1599 GCStateMachine::StepTiming& storage, quint64 timing, GCState state
1601 auto wouldOverflow = [](quint64 lhs, quint64 rhs) {
1602 return rhs > 0 && lhs > std::numeric_limits<quint64>::max() - rhs;
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;
1611 storage.rolling_sum += timing;
1616 GCStateMachine::StepTiming& storage = that->executionTiming[that->state];
1617 registerTimingWithResetOnOverflow(storage, timing, that->state);
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.";
1626 if (!that->collectTimings)
1627 return stateInfo.execute(that, that->stateData);
1629 QElapsedTimer timer;
1631 GCState next = stateInfo.execute(that, that->stateData);
1632 logStepTiming(that, timer.nsecsElapsed()/1000);
1638 if (that->state > GCState::InitCallDestroyObjects) {
1640
1641
1642
1643
1644
1645
1646
1647
1755 qDebug(
stats) <<
"!!!!!!!!!!!!!!!!!!!!! LOST MEM:" <<
lost <<
"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!";
1769#include "moc_qv4mm_p.cpp"
static void logStepTiming(GCStateMachine *that, quint64 timing)
static size_t dumpBins(BlockAllocator *b, const char *title)
static void freeHugeChunk(ChunkAllocator *chunkAllocator, const HugeItemAllocator::HugeChunk &c)
static GCState executeWithLoggingIfEnabled(GCStateMachine *that, GCStateInfo &stateInfo)
static void redrainDuringSweep(GCStateMachine *that)
QT_BEGIN_NAMESPACE Q_STATIC_LOGGING_CATEGORY(lcSynthesizedIterableAccess, "qt.iterable.synthesized", QtWarningMsg)
void free(Chunk *chunk, size_t size=0)
size_t requiredChunkSize(size_t size)
Chunk * allocate(size_t size=0)
std::vector< MemorySegment > memorySegments
void free(Chunk *chunk, size_t size)
Chunk * allocate(size_t size)
MemorySegment(size_t size)
PageReservation pageReservation
void setBit(size_t index)
bool testBit(size_t index) const
void clearBit(size_t index)
bool contains(Chunk *c) const
MemorySegment(MemorySegment &&other)