File: metaobjectregistry.cpp

package info (click to toggle)
gammaray 3.1.0%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 24,796 kB
  • sloc: cpp: 109,174; ansic: 2,156; sh: 336; python: 274; yacc: 90; lex: 82; xml: 61; makefile: 28; javascript: 9; ruby: 5
file content (396 lines) | stat: -rw-r--r-- 13,090 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
/*
  metaobjectregistry.cpp

  This file is part of GammaRay, the Qt application inspection and manipulation tool.

  SPDX-FileCopyrightText: 2012 Klarälvdalens Datakonsult AB, a KDAB Group company <info@kdab.com>
  Author: Kevin Funk <kevin.funk@kdab.com>

  SPDX-License-Identifier: GPL-2.0-or-later

  Contact KDAB at <info@kdab.com> for commercial licensing options.
*/

#include "metaobjectregistry.h"

#include <core/execution.h>
#include <core/probe.h>
#include <core/qmetaobjectvalidator.h>

#include <common/metatypedeclarations.h>
#include <common/tools/metaobjectbrowser/qmetaobjectmodel.h>

#include <QDebug>
#include <QThread>
#include <QTimer>

#include <algorithm>
#include <cassert>

#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
#include <QBitArray>
#include <QEasingCurve>
#include <QUuid>
#include <QJsonValue>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <QCborArray>
#include <QCborMap>
#include <QModelIndex>
#include <private/qmetatype_p.h>
#endif

using namespace GammaRay;

namespace GammaRay {
/**
 * Open QObject for access to protected data members
 */
class UnprotectedQObject : public QObject
{
public:
    inline QObjectData *data() const
    {
        return d_ptr.data();
    }
};
}

/**
 * Return true in case the object has a dynamic meta object
 *
 * If you look at the code generated by moc you'll see this:
 * @code
 * const QMetaObject *GammaRay::MessageModel::metaObject() const
 * {
 *     return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
 * }
 * @endcode
 *
 * QtQuick uses dynamic meta objects (subclasses of QAbstractDynamicMetaObject, defined in qobject_h.p)
 * for QML types. It's possible that these meta objects get destroyed
 * at runtime, so we need to protect against this.
 *
 * @note We cannot say if a specific QMetaObject* is dynamic or not
 * (QMetaObject is non-polymorphic, so we cannot dynamic_cast to QAbstractDynamicMetaObject*),
 * we can just judge by looking at QObjectData of QObject*
 * -- hence the QObject* parameter in hasDynamicMetaObject.
 *
 * @return Return true in case metaObject() does not point to staticMetaObject.
 */
#if defined(Q_CC_CLANG) || defined(Q_CC_GNU)
// keep it working in UBSAN
__attribute__((no_sanitize("vptr")))
#endif
static inline bool
hasDynamicMetaObject(const QObject *object)
{
    return reinterpret_cast<const UnprotectedQObject *>(object)->data()->metaObject != nullptr;
}

MetaObjectRegistry::MetaObjectRegistry(QObject *parent)
    : QObject(parent)
{
    qRegisterMetaType<const QMetaObject *>();
    scanMetaTypes();
}

MetaObjectRegistry::~MetaObjectRegistry() = default;

QVariant MetaObjectRegistry::data(const QMetaObject *metaObject, MetaObjectData type) const
{
    switch (type) {
    case ClassName:
        return m_metaObjectInfoMap.value(metaObject).className;
    case Valid:
        return isValid(metaObject);
    case SelfCount:
        if (inheritsQObject(metaObject))
            return m_metaObjectInfoMap.value(metaObject).selfCount;
        return QStringLiteral("-");
    case InclusiveCount:
        if (inheritsQObject(metaObject))
            return m_metaObjectInfoMap.value(metaObject).inclusiveCount;
        return QStringLiteral("-");
    case SelfAliveCount:
        if (inheritsQObject(metaObject))
            return m_metaObjectInfoMap.value(metaObject).selfAliveCount;
        return QStringLiteral("-");
    case InclusiveAliveCount:
        if (inheritsQObject(metaObject))
            return m_metaObjectInfoMap.value(metaObject).inclusiveAliveCount;
        return QStringLiteral("-");
    }
    return QVariant();
}

bool MetaObjectRegistry::isValid(const QMetaObject *metaObject) const
{
    const auto it = m_metaObjectInfoMap.constFind(metaObject);
    if (it == m_metaObjectInfoMap.constEnd())
        return false;
    return !(*it).invalid;
}

bool MetaObjectRegistry::isStatic(const QMetaObject *metaObject) const
{
    const auto it = m_metaObjectInfoMap.constFind(metaObject);
    if (it == m_metaObjectInfoMap.constEnd())
        return false;
    return (*it).isStatic;
}

const QMetaObject *MetaObjectRegistry::parentOf(const QMetaObject *metaObject) const
{
    return m_childParentMap.value(metaObject);
}

QVector<const QMetaObject *> MetaObjectRegistry::childrenOf(const QMetaObject *metaObject) const
{
    return m_parentChildMap.value(metaObject);
}

bool MetaObjectRegistry::inheritsQObject(const QMetaObject *metaObject) const
{
    while (metaObject) {
        if (metaObject == &QObject::staticMetaObject)
            return true;
        metaObject = m_childParentMap.value(metaObject);
    }

    return false;
}

void MetaObjectRegistry::objectAdded(QObject *obj)
{
    // Probe::objectFullyConstructed calls us and ensures this already
    Q_ASSERT(thread() == QThread::currentThread());
    Q_ASSERT(Probe::instance()->isValidObject(obj));

    Q_ASSERT(!obj->parent() || Probe::instance()->isValidObject(obj->parent()));

    const QMetaObject *metaObject = obj->metaObject();
    metaObject = addMetaObject(metaObject, hasDynamicMetaObject(obj));

    /*
     * This will increase these values:
     * - selfCount for that particular @p metaObject
     * - inclusiveCount for @p metaObject and *all* ancestors
     *
     * Complexity-wise the inclusive count calculation should be okay,
     * since the number of ancestors should be rather small
     * (QMetaObject class hierarchy is rather a broad than a deep tree structure)
     *
     * If this yields some performance issues, we might need to remove the inclusive
     * costs calculation altogether (a calculate-on-request pattern should be even slower)
     */
    m_metaObjectMap.insert(obj, metaObject);
    auto &info = m_metaObjectInfoMap[metaObject];
    ++info.selfCount;
    ++info.selfAliveCount;
    if (info.isDynamic)
        addAliveInstance(obj, metaObject);

    // increase inclusive counts
    const QMetaObject *current = metaObject;
    while (current) {
        auto &info = m_metaObjectInfoMap[current];
        ++info.inclusiveCount;
        ++info.inclusiveAliveCount;
        info.invalid = false;
        emit dataChanged(current);
        current = parentOf(current);
    }
}

#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
// Lifted from Qt
struct MetaTypeCoreHelper final : public QMetaTypeModuleHelper
{
    template<typename T, typename LiteralWrapper = std::conditional_t<std::is_same_v<T, QString>, QLatin1String, const char *>>
    static inline bool convertToBool(const T &source)
    {
        T str = source.toLower();
        return !(str.isEmpty() || str == LiteralWrapper("0") || str == LiteralWrapper("false"));
    }

    const QtPrivate::QMetaTypeInterface *interfaceForType(int type) const override
    {
        switch (type) {
            QT_FOR_EACH_STATIC_PRIMITIVE_TYPE(QT_METATYPE_CONVERT_ID_TO_TYPE)
            QT_FOR_EACH_STATIC_PRIMITIVE_POINTER(QT_METATYPE_CONVERT_ID_TO_TYPE)
            QT_FOR_EACH_STATIC_CORE_CLASS(QT_METATYPE_CONVERT_ID_TO_TYPE)
            QT_FOR_EACH_STATIC_CORE_POINTER(QT_METATYPE_CONVERT_ID_TO_TYPE)
            QT_FOR_EACH_STATIC_CORE_TEMPLATE(QT_METATYPE_CONVERT_ID_TO_TYPE)
        default:
            return nullptr;
        }
    }
};

Q_GLOBAL_STATIC(MetaTypeCoreHelper, qMetaTypeCoreHelper)

static const QMetaTypeModuleHelper *qModuleHelperForType(int type)
{
    if (type <= QMetaType::LastCoreType)
        return qMetaTypeCoreHelper;
    if (type >= QMetaType::FirstGuiType && type <= QMetaType::LastGuiType)
        return qMetaTypeGuiHelper;
    else if (type >= QMetaType::FirstWidgetsType && type <= QMetaType::LastWidgetsType)
        return qMetaTypeWidgetsHelper;
    return nullptr;
}

bool MetaObjectRegistry::isTypeIdRegistered(int type)
{
    if (auto moduleHelper = qModuleHelperForType(type))
        return moduleHelper->interfaceForType(type) != nullptr;
    return false;
}
#endif

void MetaObjectRegistry::scanMetaTypes()
{
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
    for (int mtId = 0; mtId <= QMetaType::User; ++mtId) {
        if (!isTypeIdRegistered(mtId))
            continue;
        if (const QMetaObject *mt = QMetaType::metaObjectForType(mtId)) {
            addMetaObject(mt);
        }
    }

    for (int mtId = QMetaType::User + 1; QMetaType::isRegistered(mtId); ++mtId) {
        if (const QMetaObject *mt = QMetaType::metaObjectForType(mtId))
            addMetaObject(mt);
    }
    addMetaObject(&Qt::staticMetaObject);
#else
    for (int mtId = 0; mtId <= QMetaType::User || QMetaType::isRegistered(mtId); ++mtId) {
        if (!QMetaType::isRegistered(mtId))
            continue;
        const auto *mt = QMetaType::metaObjectForType(mtId);
        if (mt)
            addMetaObject(mt);
    }
    addMetaObject(&staticQtMetaObject);
#endif
}

const QMetaObject *MetaObjectRegistry::addMetaObject(const QMetaObject *metaObject, bool mergeDynamic)
{
    if (isKnownMetaObject(metaObject))
        return metaObject;

    const QMetaObject *parentMetaObject = metaObject->superClass();
    if (parentMetaObject && !isKnownMetaObject(parentMetaObject)) {
        // add parent first
        parentMetaObject = addMetaObject(metaObject->superClass(), mergeDynamic);
    }

    const auto isStatic = Execution::isReadOnlyData(metaObject);
    if (!isStatic && mergeDynamic) {
        const QByteArray name(metaObject->className());
        const auto it = m_metaObjectNameMap.constFind(name);
        if (it != m_metaObjectNameMap.constEnd())
            return *it; // ### we could do some sanity checking here if the QMO content is really identical, in case they just happen to have the same name
        m_metaObjectNameMap.insert(name, metaObject);
    }

    auto &info = m_metaObjectInfoMap[metaObject];
    info.className = metaObject->className();
    info.isStatic = isStatic;
    info.isDynamic = !isStatic && mergeDynamic;
    // make the parent immediately retrieveable, so that slots connected to
    // beforeMetaObjectAdded() can use parentOf().
    m_childParentMap.insert(metaObject, parentMetaObject);

    QVector<const QMetaObject *> &children = m_parentChildMap[parentMetaObject];

    emit beforeMetaObjectAdded(metaObject);
    children.push_back(metaObject);
    emit afterMetaObjectAdded(metaObject);
    return metaObject;
}

void MetaObjectRegistry::objectRemoved(QObject *obj)
{
    Q_ASSERT(thread() == QThread::currentThread());

    // decrease counter
    const QMetaObject *metaObject = m_metaObjectMap.take(obj);
    if (!metaObject)
        return;

    auto &info = m_metaObjectInfoMap[metaObject];
    assert(!info.className.isEmpty()); // ie. we found the entry
    if (info.selfAliveCount == 0) {
        // something went wrong, but let's just ignore this event in case of assert
        return;
    }

    --info.selfAliveCount;
    assert(info.selfAliveCount >= 0);
    if (info.isDynamic)
        removeAliveInstance(obj, metaObject);

    // decrease inclusive counts
    const QMetaObject *current = metaObject;
    while (current) {
        MetaObjectInfo &info = m_metaObjectInfoMap[current];
        --info.inclusiveAliveCount;
        assert(info.inclusiveAliveCount >= 0);
        emit dataChanged(current);
        const QMetaObject *parent = m_childParentMap.value(current);
        // there is no way to detect when a QMetaObject is getting actually destroyed,
        // so mark them as invalid when there are no objects if that type alive anymore.
        if (info.inclusiveAliveCount == 0 && !info.isStatic) {
            info.invalid = true;
        }
        current = parent;
    }
}

bool MetaObjectRegistry::isKnownMetaObject(const QMetaObject *metaObject) const
{
    return m_childParentMap.contains(metaObject);
}

const QMetaObject *MetaObjectRegistry::aliveInstance(const QMetaObject *metaObject) const
{
    const auto it = m_aliveInstances.find(metaObject);
    if (it == m_aliveInstances.end())
        return metaObject; // static QMO
    if (it.value().isEmpty())
        return nullptr;
    return it.value().at(0);
}

void MetaObjectRegistry::addAliveInstance(QObject *obj, const QMetaObject *canonicalMO)
{
    auto aliveMO = obj->metaObject();
    m_dynamicMetaObjectMap.insert(obj, aliveMO);
    m_canonicalMetaObjectMap.insert(aliveMO, canonicalMO);
    auto &alivePool = m_aliveInstances[canonicalMO];
    auto it = std::lower_bound(alivePool.begin(), alivePool.end(), aliveMO);
    alivePool.insert(it, aliveMO);
}

void MetaObjectRegistry::removeAliveInstance(QObject *obj, const QMetaObject *canonicalMO)
{
    auto aliveMO = m_dynamicMetaObjectMap.take(obj);
    auto &alivePool = m_aliveInstances[canonicalMO];
    auto it = std::lower_bound(alivePool.begin(), alivePool.end(), aliveMO);
    if (it != alivePool.end() && *it == aliveMO)
        alivePool.erase(it);
    m_canonicalMetaObjectMap.remove(aliveMO);
}

const QMetaObject *MetaObjectRegistry::canonicalMetaObject(const QMetaObject *metaObject) const
{
    const auto it = m_canonicalMetaObjectMap.find(metaObject);
    if (it != m_canonicalMetaObjectMap.end())
        return *it;
    return metaObject;
}