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
qqmlpropertycache.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 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:significant
4
6
7#include <private/qqmlengine_p.h>
8#include <private/qqmlbinding_p.h>
9#include <private/qqmlvmemetaobject_p.h>
10
11#include <private/qmetaobject_p.h>
12#include <private/qmetaobjectbuilder_p.h>
13#include <private/qqmlpropertycachemethodarguments_p.h>
14#include <private/qqmlsignalnames_p.h>
15
16#include <private/qv4codegen_p.h>
17#include <private/qv4value_p.h>
18
19#include <QtCore/qdebug.h>
20#include <QtCore/QCryptographicHash>
21#include <QtCore/private/qtools_p.h>
22
23#include <limits.h>
24#include <algorithm>
25
26#ifdef Q_CC_MSVC
27// nonstandard extension used : zero-sized array in struct/union.
28# pragma warning( disable : 4200 )
29#endif
30
31QT_BEGIN_NAMESPACE
32
33#define Q_INT16_MAX 32767
34
36namespace detail {
37
38static inline bool hasInvalidModifierCombintation(const QQmlPropertyData &overridingProperty)
39{
40 return (overridingProperty.isVirtual() && overridingProperty.isFinal())
41 || (overridingProperty.doesOverride() && overridingProperty.isFinal())
42 || (overridingProperty.isVirtual() && overridingProperty.doesOverride());
43}
44
45/*
46 * Performs minimal validation of property override semantics.
47 *
48 * This function checks whether an existing property can be overridden.
49 * It distinguishes between the following cases:
50 * - No base property exists → Status::NoOverride
51 * - Base property is marked final → Status::OverridingFinal
52 * - Otherwise → Status::Valid
53 *
54 * The minimal check is used in contexts where only basic inheritance
55 * constraints (existence and finality) must be verified.
56 */
57static inline Status checkMinimal(const QQmlPropertyData *const existingProperty)
58{
59 if (!existingProperty)
60 return Status::NoOverride;
61
62 if (existingProperty->isFinal()) {
64 }
65
66 return Status::Valid;
67}
68
69/*
70 * Performs full validation of property override semantics.
71 *
72 * This function enforces the full set of rules for `virtual`, `override`,
73 * and `final` keyword combinations when resolving property overrides.
74 * It verifies:
75 *
76 * - If `override` is specified but no base property exists,
77 * the override is invalid (Status::MissingBase).
78 *
79 * - If `override` is NOT specified and no base property exists,
80 * then there is no override (Status::NoOverride).
81 *
82 * - If the base property is final, overriding is not allowed
83 * (Status::OverridingFinal).
84 *
85 * - If the base property is invokable and overriding is not (and vice-versa),
86 * override is invalid (Status::InvokabilityMismatch).
87 *
88 * - If the base property is not virtual, but 'override' is present
89 * overriding is not allowed (Status::OverridingNonVirtualError),
90 * otherwise it returns Status::OverridingNonVirtual
91 *
92 * - If no `override` or `final` keyword is specified for an existing virtual base,
93 * the override specifier is missing (Status::MissingOverrideOrFinalSpecifier).
94 *
95 * Returns Status::Valid if the combination is semantically correct.
96 */
97static inline Status checkFull(const QQmlPropertyData &overridingProperty,
98 const QQmlPropertyData *const existingProperty)
99{
100 const auto overrideKeyword = overridingProperty.doesOverride();
101 if (overrideKeyword && !existingProperty) {
102 return Status::MissingBase;
103 }
104
105 const auto minimalCheckRes = checkMinimal(existingProperty);
106 if (minimalCheckRes != Status::Valid) {
107 return minimalCheckRes;
108 }
109
110 // if the property doesn't exist we should have returned MissingBase or NoOverride already
111 Q_ASSERT(existingProperty);
112 if (overridingProperty.isFunction() != existingProperty->isFunction()) {
114 }
115
116 if (!existingProperty->isVirtual()) {
117 return overrideKeyword ? Status::OverridingNonVirtualError
119 }
120
121 const auto overrideOrFinal = overrideKeyword || overridingProperty.isFinal();
122 if (!overrideOrFinal) {
124 }
125
126 return Status::Valid;
127}
128
129static inline Status check(const QQmlPropertyData &overridingProperty,
130 const QQmlPropertyData *const existingProperty, CheckMode mode)
131{
132 Q_ASSERT(!hasInvalidModifierCombintation(overridingProperty));
133
134 switch (mode) {
136 return detail::checkMinimal(existingProperty);
137 case CheckMode::Full:
138 return detail::checkFull(overridingProperty, existingProperty);
139 default:
140 Q_UNREACHABLE_RETURN(Status::Unknown);
141 }
142}
143} // namespace detail
144
145Status handleOverride(QQmlPropertyData &overridingProperty, QQmlPropertyData *existingProperty,
146 CheckMode mode)
147{
148 const auto status = detail::check(overridingProperty, existingProperty, mode);
149
150 if (isValidOverride(status)) {
151 overridingProperty.markAsOverrideOf(existingProperty);
152 }
153 return status;
154}
155
156} // namespace OverrideSemantics
157
158static int metaObjectSignalCount(const QMetaObject *metaObject)
159{
160 int signalCount = 0;
161 for (const QMetaObject *obj = metaObject; obj; obj = obj->superClass())
162 signalCount += QMetaObjectPrivate::get(obj)->signalCount;
163 return signalCount;
164}
165
166QQmlPropertyData::Flags
167QQmlPropertyData::flagsForProperty(const QMetaProperty &p)
168{
169 QQmlPropertyData::Flags flags;
170
171 flags.setIsConstant(p.isConstant());
172 flags.setIsWritable(p.isWritable());
173 flags.setIsResettable(p.isResettable());
174 flags.setIsFinal(p.isFinal());
175 flags.setIsVirtual(p.isVirtual());
176 flags.setDoesOverride(p.isOverride());
177 flags.setIsRequired(p.isRequired());
178 flags.setIsBindable(p.isBindable());
179
180
181 const QMetaType metaType = p.metaType();
182 int propType = metaType.id();
183 if (p.isEnumType()) {
184 flags.setType(QQmlPropertyData::Flags::EnumType);
185 } else if (metaType.flags() & QMetaType::PointerToQObject) {
186 flags.setType(QQmlPropertyData::Flags::QObjectDerivedType);
187 } else if (propType == QMetaType::QVariant) {
188 flags.setType(QQmlPropertyData::Flags::QVariantType);
189 } else if (metaType.flags() & QMetaType::IsQmlList) {
190 flags.setType(QQmlPropertyData::Flags::QListType);
191 }
192
193 return flags;
194}
195
196void QQmlPropertyData::load(const QMetaProperty &p)
197{
198 Q_ASSERT(p.revision() <= std::numeric_limits<quint16>::max());
199 setCoreIndex(p.propertyIndex());
200 setNotifyIndex(QMetaObjectPrivate::signalIndex(p.notifySignal()));
201 setFlags(flagsForProperty(p));
202 setRevision(QTypeRevision::fromEncodedVersion(p.revision()));
203 QMetaType type = p.metaType();
204 setPropType(type);
205}
206
207void QQmlPropertyData::load(const QMetaMethod &m)
208{
209 setCoreIndex(m.methodIndex());
210 m_flags.setType(Flags::FunctionType);
211
212 // We need to set the constructor, signal, constant, arguments, V4Function, cloned flags.
213 // These are specific to methods and change with each method.
214 // The same QQmlPropertyData may be loaded with multiple methods in sequence.
215
216 switch (m.methodType()) {
217 case QMetaMethod::Signal:
218 m_flags.setIsSignal(true);
219 m_flags.setIsConstructor(false);
220 setPropType(m.returnMetaType());
221 break;
222 case QMetaMethod::Constructor:
223 m_flags.setIsSignal(false);
224 m_flags.setIsConstructor(true);
225 break;
226 default:
227 m_flags.setIsSignal(false);
228 m_flags.setIsConstructor(false);
229 setPropType(m.returnMetaType());
230 break;
231 }
232
233 m_flags.setIsConstant(m.isConst());
234
235 const int paramCount = m.parameterCount();
236 if (paramCount) {
237 m_flags.setHasArguments(true);
238 m_flags.setIsV4Function(
239 paramCount == 1 &&
240 m.parameterMetaType(0) == QMetaType::fromType<QQmlV4FunctionPtr>());
241 } else {
242 m_flags.setHasArguments(false);
243 m_flags.setIsV4Function(false);
244 }
245
246 m_flags.setIsCloned(m.attributes() & QMetaMethod::Cloned);
247
248 Q_ASSERT(m.revision() <= std::numeric_limits<quint16>::max());
249 setRevision(QTypeRevision::fromEncodedVersion(m.revision()));
250}
251
252Q_LOGGING_CATEGORY(qqmlPropertyCacheAppend, "qt.qml.propertyCache.append", QtWarningMsg)
253
254/*!
255 \internal
256 Creates a standalone QQmlPropertyCache of \a metaObject. It is separate from the usual
257 QQmlPropertyCache hierarchy. It's parent is not equal to any other QQmlPropertyCache
258 created from QObject::staticMetaObject, for example.
259*/
260QQmlPropertyCache::Ptr QQmlPropertyCache::createStandalone(
261 const QMetaObject *metaObject, QTypeRevision metaObjectRevision)
262{
263 Q_ASSERT(metaObject);
264
265 Ptr result;
266 if (const QMetaObject *super = metaObject->superClass()) {
267 result = createStandalone(
268 super, metaObjectRevision)->copyAndAppend(metaObject, metaObjectRevision);
269 } else {
270 result.adopt(new QQmlPropertyCache(metaObject));
271 result->update(metaObject);
272 }
273
274 if (metaObjectRevision.isValid() && metaObjectRevision != QTypeRevision::zero()) {
275 // Set the revision of the meta object that this cache describes to be
276 // 'metaObjectRevision'. This is useful when constructing a property cache
277 // from a type that was created directly in C++, and not through QML. For such
278 // types, the revision for each recorded QMetaObject would normally be zero, which
279 // would exclude any revisioned properties.
280 for (int metaObjectOffset = 0; metaObjectOffset < result->allowedRevisionCache.size();
281 ++metaObjectOffset) {
282 result->allowedRevisionCache[metaObjectOffset] = metaObjectRevision;
283 }
284 }
285
286 return result;
287}
288
289QQmlPropertyCache::~QQmlPropertyCache()
290{
291 QQmlPropertyCacheMethodArguments *args = argumentsCache;
292 while (args) {
293 QQmlPropertyCacheMethodArguments *next = args->next;
294 delete args->names;
295 free(args);
296 args = next;
297 }
298
299 // We must clear this prior to releasing the parent incase it is a
300 // linked hash
301 stringCache.clear();
302}
303
304QQmlPropertyCache::Ptr QQmlPropertyCache::copy(const QQmlMetaObjectPointer &mo, int reserve) const
305{
306 QQmlPropertyCache::Ptr cache = QQmlPropertyCache::Ptr(
307 new QQmlPropertyCache(mo, _handleOverride), QQmlPropertyCache::Ptr::Adopt);
308 cache->_parent.reset(this);
309 cache->propertyIndexCacheStart = propertyIndexCache.size() + propertyIndexCacheStart;
310 cache->methodIndexCacheStart = methodIndexCache.size() + methodIndexCacheStart;
311 cache->signalHandlerIndexCacheStart = signalHandlerIndexCache.size() + signalHandlerIndexCacheStart;
312 cache->stringCache.linkAndReserve(stringCache, reserve);
313 cache->allowedRevisionCache = allowedRevisionCache;
314 cache->_defaultPropertyName = _defaultPropertyName;
315 cache->_listPropertyAssignBehavior = _listPropertyAssignBehavior;
316
317 return cache;
318}
319
320QQmlPropertyCache::Ptr QQmlPropertyCache::copy() const
321{
322 return copy(_metaObject, 0);
323}
324
325QQmlPropertyCache::Ptr QQmlPropertyCache::copyAndReserve(
326 int propertyCount, int methodCount, int signalCount, int enumCount) const
327{
328 QQmlPropertyCache::Ptr rv = copy(
329 QQmlMetaObjectPointer(), propertyCount + methodCount + signalCount);
330 rv->propertyIndexCache.reserve(propertyCount);
331 rv->methodIndexCache.reserve(methodCount);
332 rv->signalHandlerIndexCache.reserve(signalCount);
333 rv->enumCache.reserve(enumCount);
334 return rv;
335}
336
337QQmlPropertyCache::AppendResult
338QQmlPropertyCache::appendAlias(const QString &name, QQmlPropertyData::Flags flags, int coreIndex,
339 QMetaType propType, QTypeRevision version, int notifyIndex,
340 int encodedTargetIndex, int targetObjectId)
341{
342 QQmlPropertyData data;
343 data.setPropType(propType);
344 data.setCoreIndex(coreIndex);
345 data.setNotifyIndex(notifyIndex);
346 flags.setIsAlias(true);
347 data.setFlags(flags);
348 data.setAliasTarget(encodedTargetIndex);
349 data.setAliasTargetObjectId(targetObjectId);
350 data.setTypeVersion(version);
351
352 return appendPropertyAttr(name, std::move(data));
353}
354
355QQmlPropertyCache::AppendResult
356QQmlPropertyCache::appendComponentWrapper(int coreIndex, int wrappedObjectIndex)
357{
358 QQmlPropertyData data;
359 data.setCoreIndex(coreIndex);
360 QQmlPropertyData::Flags flags;
361 flags.setType(QQmlPropertyData::Flags::ComponentWrapperType);
362 data.setFlags(flags);
363 data.setWrappedObjectIndex(wrappedObjectIndex);
364
365 // Use a sentinel name so that defaultProperty() can find the wrapper.
366 // NB: We're not actually using the default property as default property. We only
367 // need some property to hold the wrapped object index.
368 _defaultPropertyName = QStringLiteral(".qt_component_wrapper__");
369 return appendPropertyAttr(_defaultPropertyName, std::move(data));
370}
371
372void QQmlPropertyCache::appendSignal(const QString &name, QQmlPropertyData::Flags flags,
373 int coreIndex, const QMetaType *types,
374 const QList<QByteArray> &names)
375{
376 QQmlPropertyData data;
377 data.setPropType(QMetaType());
378 data.setCoreIndex(coreIndex);
379 data.setFlags(flags);
380 data.setArguments(nullptr);
381
382 QQmlPropertyData handler = data;
383 handler.m_flags.setIsSignalHandler(true);
384
385 if (types) {
386 const auto argumentCount = names.size();
387 QQmlPropertyCacheMethodArguments *args = createArgumentsObject(argumentCount, names);
388 new (args->types) QMetaType; // Invalid return type
389 ::memcpy(args->types + 1, types, argumentCount * sizeof(QMetaType));
390 data.setArguments(args);
391 }
392
393 QQmlPropertyData *old = findNamedProperty(name);
394 const auto overrideStatus = _handleOverride(data, old, OverrideSemantics::CheckMode::Minimal);
395 maybeLog(overrideStatus, name);
396 // remove assert when checkMode is expanded and adjust handling correspondingly. For now it
397 // verifies that some code-path work in the same way as before introduction of virtual and
398 // override keywords
399 Q_ASSERT(overrideStatus == OverrideSemantics::Status::NoOverride
400 || overrideStatus == OverrideSemantics::Status::Valid
401 || overrideStatus == OverrideSemantics::Status::OverridingFinal);
402 if (overrideStatus == OverrideSemantics::Status::OverridingFinal) {
403 // TODO QTBUG-141728
404 // Insert the overridden member and its signal once more, to keep the counts in sync
405 methodIndexCache.append(*old);
406 handler = *old;
407 handler.m_flags.setIsSignalHandler(true);
408 signalHandlerIndexCache.append(handler);
409 return;
410 }
411
412 int methodIndex = methodIndexCache.size();
413 methodIndexCache.append(data);
414
415 int signalHandlerIndex = signalHandlerIndexCache.size();
416 signalHandlerIndexCache.append(handler);
417
418 const QString handlerName = QQmlSignalNames::signalNameToHandlerName(name);
419
420 setNamedProperty(name, methodIndex + methodOffset(), methodIndexCache.data() + methodIndex);
421 setNamedProperty(handlerName, signalHandlerIndex + signalOffset(),
422 signalHandlerIndexCache.data() + signalHandlerIndex);
423}
424
425void QQmlPropertyCache::appendMethod(const QString &name, QQmlPropertyData::Flags flags,
426 int coreIndex, QMetaType returnType,
427 const QList<QByteArray> &names,
428 const QList<QMetaType> &parameterTypes)
429{
430 int argumentCount = names.size();
431
432 QQmlPropertyData data;
433 data.setPropType(returnType);
434 data.setCoreIndex(coreIndex);
435 data.setFlags(flags);
436 QQmlPropertyData *old = findNamedProperty(name);
437 const auto overrideStatus = _handleOverride(data, old, OverrideSemantics::CheckMode::Minimal);
438 maybeLog(overrideStatus, name);
439 // remove assert when checkMode is expanded and adjust handling correspondingly. For now it
440 // verifies that some code-path work in the same way as before introduction of virtual and
441 // override keywords
442 Q_ASSERT(overrideStatus == OverrideSemantics::Status::NoOverride
443 || overrideStatus == OverrideSemantics::Status::Valid
444 || overrideStatus == OverrideSemantics::Status::OverridingFinal);
445 if (overrideStatus == OverrideSemantics::Status::OverridingFinal) {
446 // TODO QTBUG-141728
447 // Insert the overridden member once more, to keep the counts in sync
448 methodIndexCache.append(*old);
449 return;
450 }
451
452 QQmlPropertyCacheMethodArguments *args = createArgumentsObject(argumentCount, names);
453 new (args->types) QMetaType(returnType);
454 for (int ii = 0; ii < argumentCount; ++ii)
455 new (args->types + ii + 1) QMetaType(parameterTypes.at(ii));
456 data.setArguments(args);
457
458 int methodIndex = methodIndexCache.size();
459 methodIndexCache.append(data);
460
461 setNamedProperty(name, methodIndex + methodOffset(), methodIndexCache.data() + methodIndex);
462}
463
464void QQmlPropertyCache::appendEnum(const QString &name, const QList<QQmlEnumValue> &values)
465{
466 QQmlEnumData data;
467 data.name = name;
468 data.values = values;
469 enumCache.append(data);
470}
471
472// Returns this property cache's metaObject, creating it if necessary.
473const QMetaObject *QQmlPropertyCache::createMetaObject() const
474{
475 if (_metaObject.isNull()) {
476 QMetaObjectBuilder builder;
477 toMetaObjectBuilder(builder);
478 builder.setSuperClass(_parent->createMetaObject());
479 _metaObject.setSharedOnce(builder.toMetaObject());
480 }
481
482 return _metaObject.metaObject();
483}
484
485const QQmlPropertyData *QQmlPropertyCache::maybeUnresolvedProperty(int index) const
486{
487 if (index < 0 || index >= propertyCount())
488 return nullptr;
489
490 const QQmlPropertyData *rv = nullptr;
491 if (index < propertyIndexCacheStart)
492 return _parent->maybeUnresolvedProperty(index);
493 else
494 rv = const_cast<const QQmlPropertyData *>(&propertyIndexCache.at(index - propertyIndexCacheStart));
495 return rv;
496}
497
498const QQmlPropertyData *QQmlPropertyCache::defaultProperty() const
499{
500 return property(defaultPropertyName(), nullptr, nullptr);
501}
502
503void QQmlPropertyCache::setParent(QQmlPropertyCache::ConstPtr newParent)
504{
505 if (_parent != newParent)
506 _parent = std::move(newParent);
507}
508
509QQmlPropertyCache::Ptr
510QQmlPropertyCache::copyAndAppend(const QMetaObject *metaObject,
511 QTypeRevision typeVersion,
512 QQmlPropertyData::Flags propertyFlags,
513 QQmlPropertyData::Flags methodFlags,
514 QQmlPropertyData::Flags signalFlags) const
515{
516 Q_ASSERT(QMetaObjectPrivate::get(metaObject)->revision >= 4);
517
518 // Reserve enough space in the name hash for all the methods (including signals), all the
519 // signal handlers and all the properties. This assumes no name clashes, but this is the
520 // common case.
521 QQmlPropertyCache::Ptr rv = copy(
522 metaObject,
523 QMetaObjectPrivate::get(metaObject)->methodCount
524 + QMetaObjectPrivate::get(metaObject)->signalCount
525 + QMetaObjectPrivate::get(metaObject)->propertyCount);
526
527 rv->append(metaObject, typeVersion, propertyFlags, methodFlags, signalFlags);
528
529 return rv;
530}
531
532static QHashedString signalNameToHandlerName(const QHashedString &methodName)
533{
534 return QQmlSignalNames::signalNameToHandlerName(methodName);
535}
536
537static QHashedString signalNameToHandlerName(const QHashedCStringRef &methodName)
538{
539 return QQmlSignalNames::signalNameToHandlerName(
540 QLatin1StringView{ methodName.constData(), methodName.length() });
541}
542
543static inline std::pair<bool, int> deriveEncodingAndLength(const char *str)
544{
545 char utf8 = 0;
546 const char *cptr = str;
547 while (*cptr != 0) {
548 utf8 |= *cptr & 0x80;
549 ++cptr;
550 }
551 return std::make_pair(utf8, cptr - str);
552}
553
554void QQmlPropertyCache::append(const QMetaObject *metaObject,
555 QTypeRevision typeVersion,
556 QQmlPropertyData::Flags propertyFlags,
557 QQmlPropertyData::Flags methodFlags,
558 QQmlPropertyData::Flags signalFlags)
559{
560 allowedRevisionCache.append(QTypeRevision::zero());
561
562 int methodCount = metaObject->methodCount();
563 Q_ASSERT(QMetaObjectPrivate::get(metaObject)->revision >= 4);
564 int signalCount = metaObjectSignalCount(metaObject);
565 int classInfoCount = QMetaObjectPrivate::get(metaObject)->classInfoCount;
566
567 if (classInfoCount) {
568 int classInfoOffset = metaObject->classInfoOffset();
569 for (int ii = 0; ii < classInfoCount; ++ii) {
570 int idx = ii + classInfoOffset;
571 QMetaClassInfo mci = metaObject->classInfo(idx);
572 const char *name = mci.name();
573 if (0 == qstrcmp(name, "DefaultProperty")) {
574 _defaultPropertyName = QString::fromUtf8(mci.value());
575 } else if (0 == qstrcmp(name, "qt_QmlJSWrapperFactoryMethod")) {
576 const char * const factoryMethod = mci.value();
577 _jsFactoryMethodIndex = metaObject->indexOfSlot(factoryMethod);
578 if (_jsFactoryMethodIndex != -1)
579 _jsFactoryMethodIndex -= metaObject->methodOffset();
580 } else if (0 == qstrcmp(name, "QML.ListPropertyAssignBehavior")) {
581 _listPropertyAssignBehavior = mci.value();
582 }
583 }
584 }
585
586 //Used to block access to QObject::destroyed() and QObject::deleteLater() from QML
587 static const int destroyedIdx1 = QObject::staticMetaObject.indexOfSignal("destroyed(QObject*)");
588 static const int destroyedIdx2 = QObject::staticMetaObject.indexOfSignal("destroyed()");
589 static const int deleteLaterIdx = QObject::staticMetaObject.indexOfSlot("deleteLater()");
590 // These indices don't apply to gadgets, so don't block them.
591 // It is enough to check for QObject::staticMetaObject here because the loop below excludes
592 // methods of parent classes: It starts at metaObject->methodOffset()
593 const bool preventDestruction = (metaObject == &QObject::staticMetaObject);
594
595 int methodOffset = metaObject->methodOffset();
596 int signalOffset = signalCount - QMetaObjectPrivate::get(metaObject)->signalCount;
597
598 // update() should have reserved enough space in the vector that this doesn't cause a realloc
599 // and invalidate the stringCache.
600 methodIndexCache.resize(methodCount - methodIndexCacheStart);
601 signalHandlerIndexCache.resize(signalCount - signalHandlerIndexCacheStart);
602 int signalHandlerIndex = signalOffset;
603 for (int ii = methodOffset; ii < methodCount; ++ii) {
604 if (preventDestruction && (ii == destroyedIdx1 || ii == destroyedIdx2 || ii == deleteLaterIdx))
605 continue;
606 const QMetaMethod &m = metaObject->method(ii);
607 if (m.access() == QMetaMethod::Private)
608 continue;
609
610 // Extract method name
611 // It's safe to keep the raw name pointer
612 Q_ASSERT(QMetaObjectPrivate::get(metaObject)->revision >= 7);
613
614 QQmlPropertyData *data = &methodIndexCache[ii - methodIndexCacheStart];
615 QQmlPropertyData *sigdata = nullptr;
616
617 if (m.methodType() == QMetaMethod::Signal)
618 data->setFlags(signalFlags);
619 else
620 data->setFlags(methodFlags);
621
622 data->load(m);
623
624 Q_ASSERT((allowedRevisionCache.size() - 1) < Q_INT16_MAX);
625 data->setMetaObjectOffset(allowedRevisionCache.size() - 1);
626
627 if (data->isSignal()) {
628 sigdata = &signalHandlerIndexCache[signalHandlerIndex - signalHandlerIndexCacheStart];
629 *sigdata = *data;
630 sigdata->m_flags.setIsSignalHandler(true);
631 }
632
633 const auto doSetNamedProperty = [&](const auto &methodName) {
634 QQmlPropertyData *old = nullptr;
635 if (StringCache::mapped_type *it = stringCache.value(methodName)) {
636 const auto overrideStatus = _handleOverride(*data, (old = it->second),
637 OverrideSemantics::CheckMode::Minimal);
638 maybeLog(overrideStatus, methodName);
639 // remove assert when checkMode is expanded and adjust handling correspondingly. For
640 // now it verifies that some code-path work in the same way as before introduction
641 // of virtual and override keywords
642 Q_ASSERT(overrideStatus == OverrideSemantics::Status::NoOverride
643 || overrideStatus == OverrideSemantics::Status::Valid
644 || overrideStatus == OverrideSemantics::Status::OverridingFinal);
645 if (overrideStatus == OverrideSemantics::Status::OverridingFinal) {
646 // TODO QTBUG-141728
647 *data = *old;
648 if (sigdata) {
649 // Keep the signal counts in sync,
650 // even if the "old" data has no real signal.
651 *sigdata = *old;
652 sigdata->m_flags.setIsSignalHandler(true);
653 ++signalHandlerIndex;
654 }
655 return;
656 }
657 }
658
659 setNamedProperty(methodName, ii, data);
660
661 if (data->isSignal()) {
662
663 // TODO: Remove this once we can. Signals should not be overridable.
664 if constexpr (std::is_same_v<std::decay_t<decltype(methodName)>, QHashedCStringRef>)
665 data->m_flags.setIsOverridableSignal(true);
666
667 setNamedProperty(signalNameToHandlerName(methodName), ii, sigdata);
668 ++signalHandlerIndex;
669 }
670 };
671
672 const char *str = m.nameView().constData();
673 const auto [isUtf8, len] = deriveEncodingAndLength(str);
674 if (isUtf8)
675 doSetNamedProperty(QHashedString(QString::fromUtf8(str, len)));
676 else
677 doSetNamedProperty(QHashedCStringRef(str, len));
678 }
679
680 int propCount = metaObject->propertyCount();
681 int propOffset = metaObject->propertyOffset();
682
683 // update() should have reserved enough space in the vector that this doesn't cause a realloc
684 // and invalidate the stringCache.
685 propertyIndexCache.resize(propCount - propertyIndexCacheStart);
686 for (int ii = propOffset; ii < propCount; ++ii) {
687 QMetaProperty p = metaObject->property(ii);
688 if (!p.isScriptable())
689 continue;
690
691 // TODO QTBUG-141728
692 QQmlPropertyData *data = &propertyIndexCache[ii - propertyIndexCacheStart];
693
694 data->setFlags(propertyFlags);
695 data->load(p);
696 data->setTypeVersion(typeVersion);
697
698 Q_ASSERT((allowedRevisionCache.size() - 1) < Q_INT16_MAX);
699 data->setMetaObjectOffset(allowedRevisionCache.size() - 1);
700
701 const auto doSetNamedProperty = [this](const auto &propName, int index, auto *propData) {
702 QQmlPropertyData *existingPropData = findNamedProperty(propName);
703 const auto overrideStatus = _handleOverride(*propData, existingPropData,
704 OverrideSemantics::CheckMode::Full);
705 maybeLog(overrideStatus, propName);
706 if (!OverrideSemantics::isValidOverride(overrideStatus)) {
707 if (existingPropData) {
708 // TODO QTBUG-141728
709 *propData = *existingPropData;
710 }
711 return;
712 }
713
714 setNamedProperty(propName, index, propData);
715 };
716
717 const char *str = p.name();
718 const auto [isUtf8, len] = deriveEncodingAndLength(str);
719 if (isUtf8)
720 doSetNamedProperty(QHashedString(QString::fromUtf8(str, len)), ii, data);
721 else
722 doSetNamedProperty(QHashedCStringRef(str, len), ii, data);
723
724 bool isGadget = true;
725 for (const QMetaObject *it = metaObject; it != nullptr; it = it->superClass()) {
726 if (it == &QObject::staticMetaObject)
727 isGadget = false;
728 }
729
730 // otherwise always dispatch over a 'normal' meta-call so the QQmlValueType can intercept
731 if (!isGadget && !data->isAlias())
732 data->trySetStaticMetaCallFunction(metaObject->d.static_metacall, ii - propOffset);
733 }
734}
735
736void QQmlPropertyCache::update(const QMetaObject *metaObject)
737{
738 Q_ASSERT(metaObject);
739 stringCache.clear();
740
741 // Preallocate enough space in the index caches for all the properties/methods/signals that
742 // are not cached in a parent cache so that the caches never need to be reallocated as this
743 // would invalidate pointers stored in the stringCache.
744 int pc = metaObject->propertyCount();
745 int mc = metaObject->methodCount();
746 int sc = metaObjectSignalCount(metaObject);
747 propertyIndexCache.reserve(pc - propertyIndexCacheStart);
748 methodIndexCache.reserve(mc - methodIndexCacheStart);
749 signalHandlerIndexCache.reserve(sc - signalHandlerIndexCacheStart);
750
751 // Reserve enough space in the stringCache for all properties/methods/signals including those
752 // cached in a parent cache.
753 stringCache.reserve(pc + mc + sc);
754
755 if (metaObject)
756 append(metaObject, QTypeRevision());
757}
758
759/*! \internal
760 invalidates and updates the PropertyCache if the QMetaObject has changed.
761 This function is used in the tooling to update dynamic properties.
762*/
763void QQmlPropertyCache::invalidate(const QMetaObject *metaObject)
764{
765 propertyIndexCache.clear();
766 methodIndexCache.clear();
767 signalHandlerIndexCache.clear();
768
769 argumentsCache = nullptr;
770
771 int pc = metaObject->propertyCount();
772 int mc = metaObject->methodCount();
773 int sc = metaObjectSignalCount(metaObject);
774 int reserve = pc + mc + sc;
775
776 if (parent()) {
777 propertyIndexCacheStart = parent()->propertyIndexCache.size() + parent()->propertyIndexCacheStart;
778 methodIndexCacheStart = parent()->methodIndexCache.size() + parent()->methodIndexCacheStart;
779 signalHandlerIndexCacheStart = parent()->signalHandlerIndexCache.size() + parent()->signalHandlerIndexCacheStart;
780 stringCache.linkAndReserve(parent()->stringCache, reserve);
781 append(metaObject, QTypeRevision());
782 } else {
783 propertyIndexCacheStart = 0;
784 methodIndexCacheStart = 0;
785 signalHandlerIndexCacheStart = 0;
786 update(metaObject);
787 }
788}
789
790const QQmlPropertyData *QQmlPropertyCache::findProperty(
791 StringCache::ConstIterator it, QObject *object,
792 const QQmlRefPointer<QQmlContextData> &context) const
793{
794 QQmlData *data = (object ? QQmlData::get(object) : nullptr);
795 const QQmlVMEMetaObject *vmemo = nullptr;
796 if (data && data->hasVMEMetaObject) {
797 QObjectPrivate *op = QObjectPrivate::get(object);
798 vmemo = static_cast<const QQmlVMEMetaObject *>(op->metaObject);
799 }
800 return findProperty(it, vmemo, context);
801}
802
803namespace {
804
805inline bool contextHasNoExtensions(const QQmlRefPointer<QQmlContextData> &context)
806{
807 // This context has no extension if its parent is the engine's rootContext,
808 // which has children but no imports
809 const QQmlRefPointer<QQmlContextData> parent = context->parent();
810 return (!parent || !parent->imports());
811}
812
813inline int maximumIndexForProperty(const QQmlPropertyData *prop, const int methodCount, const int signalCount, const int propertyCount)
814{
815 return prop->isFunction() ? methodCount
816 : prop->isSignalHandler() ? signalCount
817 : propertyCount;
818}
819
820}
821
822const QQmlPropertyData *QQmlPropertyCache::findProperty(
823 StringCache::ConstIterator it, const QQmlVMEMetaObject *vmemo,
824 const QQmlRefPointer<QQmlContextData> &context) const
825{
826 StringCache::ConstIterator end = stringCache.end();
827
828 if (it != end) {
829 const QQmlPropertyData *result = it.value().second;
830
831 // If there exists a typed property (not a function or signal handler), of the
832 // right name available to the specified context, we need to return that
833 // property rather than any subsequent override
834
835 if (vmemo && context && !contextHasNoExtensions(context)) {
836 // Find the meta-object that corresponds to the supplied context
837 do {
838 if (vmemo->contextData() == context)
839 break;
840
841 vmemo = vmemo->parentVMEMetaObject();
842 } while (vmemo);
843 }
844
845 if (vmemo) {
846 const int methodCount = vmemo->cache->methodCount();
847 const int signalCount = vmemo->cache->signalCount();
848 const int propertyCount = vmemo->cache->propertyCount();
849
850 // Ensure that the property we resolve to is accessible from this meta-object
851 do {
852 const StringCache::mapped_type &property(it.value());
853
854 if (property.first < maximumIndexForProperty(property.second, methodCount, signalCount, propertyCount)) {
855 // This property is available in the specified context
856 if (property.second->isFunction() || property.second->isSignalHandler()) {
857 // Prefer the earlier resolution
858 } else {
859 // Prefer the typed property to any previous property found
860 result = property.second;
861 }
862 break;
863 }
864
865 // See if there is a better candidate
866 it = stringCache.findNext(it);
867 } while (it != end);
868 }
869
870 return result;
871 }
872
873 return nullptr;
874}
875
876// Note, this function is called when adding aliases, hence data.isEnum() can possibly be true
877QQmlPropertyCache::AppendResult QQmlPropertyCache::appendPropertyAttr(const QString &name,
878 QQmlPropertyData &&data)
879{
880 QQmlPropertyData *old = findNamedProperty(name);
881 const auto overrideStatus = _handleOverride(data, old, OverrideSemantics::CheckMode::Full);
882 maybeLog(overrideStatus, name);
883 if (!OverrideSemantics::isValidOverride(overrideStatus)) {
884 // TODO QTBUG-141728
885 // Insert the overridden member once more, to keep the counts in sync
886 propertyIndexCache.append(old ? *old : data);
887 return q23::make_unexpected(overrideStatus);
888 }
889
890 const int index = propertyIndexCache.size();
891 propertyIndexCache.append(std::move(data));
892
893 setNamedProperty(name, index + propertyOffset(), propertyIndexCache.data() + index);
894 return {};
895}
896
897void QQmlPropertyData::markAsOverrideOf(QQmlPropertyData *predecessor)
898{
899 Q_ASSERT(predecessor != this);
900
901 if (!predecessor) {
902 return;
903 }
904
905 setOverrideIndexIsProperty(!predecessor->isFunction());
906 setOverrideIndex(predecessor->coreIndex());
907 // propagate "virtuality"
908 m_flags.setIsVirtual(predecessor->isVirtual());
909 predecessor->m_flags.setIsOverridden(true);
910 Q_ASSERT(predecessor->isOverridden());
911 return;
912}
913
914QQmlPropertyCacheMethodArguments *QQmlPropertyCache::createArgumentsObject(
915 int argc, const QList<QByteArray> &names)
916{
917 typedef QQmlPropertyCacheMethodArguments A;
918 A *args = static_cast<A *>(malloc(sizeof(A) + argc * sizeof(QMetaType)));
919 args->names = argc ? new QList<QByteArray>(names) : nullptr;
920 args->next = argumentsCache;
921 argumentsCache = args;
922 return args;
923}
924
925QString QQmlPropertyCache::signalParameterStringForJS(
926 const QList<QByteArray> &parameterNameList, QString *errorString)
927{
928 bool unnamedParameter = false;
929 QString parameters;
930
931 const qsizetype count = parameterNameList.size();
932 if (count > std::numeric_limits<quint16>::max())
933 *errorString = QCoreApplication::translate("QQmlRewrite", "Signal has an excessive number of parameters: %1").arg(count);
934
935 for (qsizetype i = 0; i < count; ++i) {
936 if (i > 0)
937 parameters += QLatin1Char(',');
938 const QByteArray &param = parameterNameList.at(i);
939 if (param.isEmpty()) {
940 unnamedParameter = true;
941 } else if (unnamedParameter) {
942 if (errorString)
943 *errorString = QCoreApplication::translate("QQmlRewrite", "Signal uses unnamed parameter followed by named parameter.");
944 return QString();
945 } else if (QV4::Compiler::Codegen::isNameGlobal(param)) {
946 if (errorString)
947 *errorString = QCoreApplication::translate("QQmlRewrite", "Signal parameter \"%1\" hides global variable.").arg(QString::fromUtf8(param));
948 return QString();
949 }
950 parameters += QString::fromUtf8(param);
951 }
952
953 return parameters;
954}
955
956int QQmlPropertyCache::originalClone(int index) const
957{
958 while (signal(index)->isCloned())
959 --index;
960 return index;
961}
962
963int QQmlPropertyCache::originalClone(const QObject *object, int index)
964{
965 QQmlData *data = QQmlData::get(object);
966 if (data && data->propertyCache) {
967 const QQmlPropertyCache *cache = data->propertyCache.data();
968 const QQmlPropertyData *sig = cache->signal(index);
969 while (sig && sig->isCloned()) {
970 --index;
971 sig = cache->signal(index);
972 }
973 } else {
974 while (QMetaObjectPrivate::signal(object->metaObject(), index).attributes() & QMetaMethod::Cloned)
975 --index;
976 }
977 return index;
978}
979
980template<typename T>
981static QQmlPropertyData qQmlPropertyCacheCreate(const QMetaObject *metaObject, const T& propertyName)
982{
983 Q_ASSERT(metaObject);
984
985 QQmlPropertyData rv;
986
987 /* It's important to check the method list before checking for properties;
988 * otherwise, if the meta object is dynamic, a property will be created even
989 * if not found and it might obscure a method having the same name. */
990
991 //Used to block access to QObject::destroyed() and QObject::deleteLater() from QML
992 static const int destroyedIdx1 = QObject::staticMetaObject.indexOfSignal("destroyed(QObject*)");
993 static const int destroyedIdx2 = QObject::staticMetaObject.indexOfSignal("destroyed()");
994 static const int deleteLaterIdx = QObject::staticMetaObject.indexOfSlot("deleteLater()");
995 // These indices don't apply to gadgets, so don't block them.
996 const bool preventDestruction = metaObject->superClass() || metaObject == &QObject::staticMetaObject;
997
998 int methodCount = metaObject->methodCount();
999 for (int ii = methodCount - 1; ii >= 0; --ii) {
1000 if (preventDestruction && (ii == destroyedIdx1 || ii == destroyedIdx2 || ii == deleteLaterIdx))
1001 continue;
1002 QMetaMethod m = metaObject->method(ii);
1003 if (m.access() == QMetaMethod::Private)
1004 continue;
1005
1006 if (m.name() == propertyName) {
1007 rv.load(m);
1008 return rv;
1009 }
1010 }
1011
1012 {
1013 const QMetaObject *cmo = metaObject;
1014 while (cmo) {
1015 int idx = cmo->indexOfProperty(propertyName);
1016 if (idx != -1) {
1017 QMetaProperty p = cmo->property(idx);
1018 if (p.isScriptable()) {
1019 rv.load(p);
1020 return rv;
1021 } else {
1022 bool changed = false;
1023 while (cmo && cmo->propertyOffset() >= idx) {
1024 cmo = cmo->superClass();
1025 changed = true;
1026 }
1027 /* If the "cmo" variable didn't change, set it to 0 to
1028 * avoid running into an infinite loop */
1029 if (!changed) cmo = nullptr;
1030 }
1031 } else {
1032 cmo = nullptr;
1033 }
1034 }
1035 }
1036 return rv;
1037}
1038
1039static inline const char *qQmlPropertyCacheToString(QLatin1String string)
1040{
1041 return string.data();
1042}
1043
1044static inline QByteArray qQmlPropertyCacheToString(QStringView string)
1045{
1046 return string.toUtf8();
1047}
1048
1049static inline QByteArray qQmlPropertyCacheToString(const QV4::String *string)
1050{
1051 return string->toQString().toUtf8();
1052}
1053
1054template<typename T>
1055const QQmlPropertyData *
1056qQmlPropertyCacheProperty(QObject *obj, T name, const QQmlRefPointer<QQmlContextData> &context,
1057 QQmlPropertyData *local)
1058{
1059 const QQmlPropertyCache *cache = nullptr;
1060
1061 QQmlData *ddata = QQmlData::get(obj, false);
1062
1063 if (ddata && ddata->propertyCache) {
1064 cache = ddata->propertyCache.data();
1065 } else if (auto newCache = QQmlMetaType::propertyCache(obj)) {
1066 cache = newCache.data();
1067 ddata = QQmlData::get(obj, true);
1068 ddata->propertyCache = std::move(newCache);
1069 }
1070
1071 const QQmlPropertyData *rv = nullptr;
1072
1073 if (cache) {
1074 rv = cache->property(name, obj, context);
1075 } else if (local) {
1076 *local = qQmlPropertyCacheCreate(obj->metaObject(), qQmlPropertyCacheToString(name));
1077 if (local->isValid())
1078 rv = local;
1079 }
1080
1081 return rv;
1082}
1083
1084const QQmlPropertyData *QQmlPropertyCache::property(
1085 QObject *obj, const QV4::String *name, const QQmlRefPointer<QQmlContextData> &context,
1086 QQmlPropertyData *local)
1087{
1088 return qQmlPropertyCacheProperty<const QV4::String *>(obj, name, context, local);
1089}
1090
1091const QQmlPropertyData *QQmlPropertyCache::property(
1092 QObject *obj, QStringView name, const QQmlRefPointer<QQmlContextData> &context,
1093 QQmlPropertyData *local)
1094{
1095 return qQmlPropertyCacheProperty<const QStringView &>(obj, name, context, local);
1096}
1097
1098const QQmlPropertyData *QQmlPropertyCache::property(
1099 QObject *obj, const QLatin1String &name, const QQmlRefPointer<QQmlContextData> &context,
1100 QQmlPropertyData *local)
1101{
1102 return qQmlPropertyCacheProperty<const QLatin1String &>(obj, name, context, local);
1103}
1104
1105// this function is copied from qmetaobject.cpp
1106static inline const QByteArray stringData(const QMetaObject *mo, int index)
1107{
1108 uint offset = mo->d.stringdata[2*index];
1109 uint length = mo->d.stringdata[2*index + 1];
1110 const char *string = reinterpret_cast<const char *>(mo->d.stringdata) + offset;
1111 return QByteArray::fromRawData(string, length);
1112}
1113
1114const char *QQmlPropertyCache::className() const
1115{
1116 if (const QMetaObject *mo = _metaObject.metaObject())
1117 return mo->className();
1118 else
1119 return _dynamicClassName.constData();
1120}
1121
1122void QQmlPropertyCache::toMetaObjectBuilder(QMetaObjectBuilder &builder) const
1123{
1124 struct Sort { static bool lt(const std::pair<QString, const QQmlPropertyData *> &lhs,
1125 const std::pair<QString, const QQmlPropertyData *> &rhs) {
1126 return lhs.second->coreIndex() < rhs.second->coreIndex();
1127 } };
1128
1129 struct Insert { static void in(const QQmlPropertyCache *This,
1130 QList<std::pair<QString, const QQmlPropertyData *> > &properties,
1131 QList<std::pair<QString, const QQmlPropertyData *> > &methods,
1132 StringCache::ConstIterator iter, const QQmlPropertyData *data) {
1133 if (data->isSignalHandler())
1134 return;
1135
1136 if (data->isFunction()) {
1137 if (data->coreIndex() < This->methodIndexCacheStart)
1138 return;
1139
1140 std::pair<QString, const QQmlPropertyData *> entry = std::make_pair((QString)iter.key(), data);
1141 // Overrides can cause the entry to already exist
1142 if (!methods.contains(entry)) methods.append(entry);
1143
1144 data = This->overrideData(data);
1145 if (data && !data->isFunction()) Insert::in(This, properties, methods, iter, data);
1146 } else {
1147 if (data->coreIndex() < This->propertyIndexCacheStart)
1148 return;
1149
1150 std::pair<QString, const QQmlPropertyData *> entry = std::make_pair((QString)iter.key(), data);
1151 // Overrides can cause the entry to already exist
1152 if (!properties.contains(entry)) properties.append(entry);
1153
1154 data = This->overrideData(data);
1155 if (data) Insert::in(This, properties, methods, iter, data);
1156 }
1157
1158 } };
1159
1160 builder.setClassName(_dynamicClassName);
1161
1162 QList<std::pair<QString, const QQmlPropertyData *> > properties;
1163 QList<std::pair<QString, const QQmlPropertyData *> > methods;
1164
1165 for (StringCache::ConstIterator iter = stringCache.begin(), cend = stringCache.end(); iter != cend; ++iter)
1166 Insert::in(this, properties, methods, iter, iter.value().second);
1167
1168 // Any invalid overrides are not linked by name into the properties and methods hashes.
1169 // Therefore there can be more properties and methods than present in the hashes.
1170 Q_ASSERT(properties.size() <= propertyIndexCache.size());
1171 Q_ASSERT(methods.size() <= methodIndexCache.size());
1172
1173 std::sort(properties.begin(), properties.end(), Sort::lt);
1174 std::sort(methods.begin(), methods.end(), Sort::lt);
1175
1176 for (int ii = 0; ii < properties.size(); ++ii) {
1177 const QQmlPropertyData *data = properties.at(ii).second;
1178
1179 int notifierId = -1;
1180 if (data->notifyIndex() != -1)
1181 notifierId = data->notifyIndex() - signalHandlerIndexCacheStart;
1182
1183 QMetaPropertyBuilder property = builder.addProperty(properties.at(ii).first.toUtf8(),
1184 data->propType().name(),
1185 data->propType(),
1186 notifierId);
1187
1188 property.setReadable(true);
1189 property.setWritable(data->isWritable());
1190 property.setResettable(data->isResettable());
1191 property.setBindable(data->notifiesViaBindable());
1192 property.setAlias(data->isAlias());
1193 }
1194
1195 for (int ii = 0; ii < methods.size(); ++ii) {
1196 const QQmlPropertyData *data = methods.at(ii).second;
1197
1198 QByteArray returnType;
1199 if (data->propType().isValid())
1200 returnType = data->propType().name();
1201
1202 QByteArray signature;
1203 // '+=' reserves extra capacity. Follow-up appending will be probably free.
1204 signature += methods.at(ii).first.toUtf8() + '(';
1205
1206 QQmlPropertyCacheMethodArguments *arguments = nullptr;
1207 if (data->hasArguments()) {
1208 arguments = data->arguments();
1209 for (int ii = 0, end = arguments->names ? arguments->names->size() : 0;
1210 ii < end; ++ii) {
1211 if (ii != 0)
1212 signature.append(',');
1213 signature.append(arguments->types[1 + ii].name());
1214 }
1215 }
1216
1217 signature.append(')');
1218
1219 QMetaMethodBuilder method;
1220 if (data->isSignal()) {
1221 method = builder.addSignal(signature);
1222 } else {
1223 method = builder.addSlot(signature);
1224 }
1225 method.setAccess(QMetaMethod::Public);
1226
1227 if (arguments && arguments->names)
1228 method.setParameterNames(*arguments->names);
1229
1230 if (!returnType.isEmpty())
1231 method.setReturnType(returnType);
1232 }
1233
1234 for (int ii = 0; ii < enumCache.size(); ++ii) {
1235 const QQmlEnumData &enumData = enumCache.at(ii);
1236 QMetaEnumBuilder enumeration = builder.addEnumerator(enumData.name.toUtf8());
1237 enumeration.setIsScoped(true);
1238 for (int jj = 0; jj < enumData.values.size(); ++jj) {
1239 const QQmlEnumValue &value = enumData.values.at(jj);
1240 enumeration.addKey(value.namedValue.toUtf8(), value.value);
1241 }
1242 }
1243
1244 if (!_defaultPropertyName.isEmpty()) {
1245 const QQmlPropertyData *dp = property(_defaultPropertyName, nullptr, nullptr);
1246 if (dp && dp->coreIndex() >= propertyIndexCacheStart) {
1247 Q_ASSERT(!dp->isFunction());
1248 builder.addClassInfo("DefaultProperty", _defaultPropertyName.toUtf8());
1249 }
1250 }
1251
1252 if (!_listPropertyAssignBehavior.isEmpty())
1253 builder.addClassInfo("QML.ListPropertyAssignBehavior", _listPropertyAssignBehavior);
1254}
1255
1256namespace {
1257template <typename StringVisitor, typename TypeInfoVisitor>
1258int visitMethods(const QMetaObject &mo, int methodOffset, int methodCount,
1259 StringVisitor visitString, TypeInfoVisitor visitTypeInfo)
1260{
1261 int fieldsForParameterData = 0;
1262
1263 bool hasOldStyleRevisionedMethods = false;
1264
1265 for (int i = 0; i < methodCount; ++i) {
1266 const int handle = methodOffset + i * QMetaObjectPrivate::IntsPerMethod;
1267
1268 const uint flags = mo.d.data[handle + 4];
1269 if (flags & MethodRevisioned) {
1270 if (mo.d.data[0] < 13)
1271 hasOldStyleRevisionedMethods = true;
1272 else
1273 fieldsForParameterData += 1; // revision
1274 }
1275
1276 visitString(mo.d.data[handle + 0]); // name
1277 visitString(mo.d.data[handle + 3]); // tag
1278
1279 const int argc = mo.d.data[handle + 1];
1280 const int paramIndex = mo.d.data[handle + 2];
1281
1282 fieldsForParameterData += argc * 2; // type and name
1283 fieldsForParameterData += 1; // + return type
1284
1285 // return type + args
1286 for (int i = 0; i < 1 + argc; ++i) {
1287 // type name (maybe)
1288 visitTypeInfo(mo.d.data[paramIndex + i]);
1289
1290 // parameter name
1291 if (i > 0)
1292 visitString(mo.d.data[paramIndex + argc + i]);
1293 }
1294 }
1295
1296 int fieldsForRevisions = 0;
1297 if (hasOldStyleRevisionedMethods)
1298 fieldsForRevisions = methodCount;
1299
1300 return methodCount * QMetaObjectPrivate::IntsPerMethod
1301 + fieldsForRevisions + fieldsForParameterData;
1302}
1303
1304template <typename StringVisitor, typename TypeInfoVisitor>
1305int visitProperties(const QMetaObject &mo, StringVisitor visitString, TypeInfoVisitor visitTypeInfo)
1306{
1307 const QMetaObjectPrivate *const priv = reinterpret_cast<const QMetaObjectPrivate*>(mo.d.data);
1308
1309 for (int i = 0; i < priv->propertyCount; ++i) {
1310 const int handle = priv->propertyData + i * QMetaObjectPrivate::IntsPerProperty;
1311
1312 visitString(mo.d.data[handle]); // name
1313 visitTypeInfo(mo.d.data[handle + 1]);
1314 }
1315
1316 return priv->propertyCount * QMetaObjectPrivate::IntsPerProperty;
1317}
1318
1319template <typename StringVisitor>
1320int visitClassInfo(const QMetaObject &mo, StringVisitor visitString)
1321{
1322 const QMetaObjectPrivate *const priv = reinterpret_cast<const QMetaObjectPrivate*>(mo.d.data);
1323 const int intsPerClassInfo = 2;
1324
1325 for (int i = 0; i < priv->classInfoCount; ++i) {
1326 const int handle = priv->classInfoData + i * intsPerClassInfo;
1327
1328 visitString(mo.d.data[handle]); // key
1329 visitString(mo.d.data[handle + 1]); // value
1330 }
1331
1332 return priv->classInfoCount * intsPerClassInfo;
1333}
1334
1335template <typename StringVisitor>
1336int visitEnumerations(const QMetaObject &mo, StringVisitor visitString)
1337{
1338 const QMetaObjectPrivate *const priv = reinterpret_cast<const QMetaObjectPrivate*>(mo.d.data);
1339
1340 int fieldCount = priv->enumeratorCount * QMetaObjectPrivate::IntsPerEnum;
1341
1342 for (int i = 0; i < priv->enumeratorCount; ++i) {
1343 const uint *enumeratorData = mo.d.data + priv->enumeratorData + i * QMetaObjectPrivate::IntsPerEnum;
1344
1345 const uint keyCount = enumeratorData[3];
1346 fieldCount += keyCount * 2;
1347
1348 visitString(enumeratorData[0]); // name
1349 visitString(enumeratorData[1]); // enum name
1350
1351 const uint keyOffset = enumeratorData[4];
1352
1353 for (uint j = 0; j < keyCount; ++j) {
1354 visitString(mo.d.data[keyOffset + 2 * j]);
1355 }
1356 }
1357
1358 return fieldCount;
1359}
1360
1361template <typename StringVisitor>
1362int countMetaObjectFields(const QMetaObject &mo, StringVisitor stringVisitor)
1363{
1364 const QMetaObjectPrivate *const priv = reinterpret_cast<const QMetaObjectPrivate*>(mo.d.data);
1365
1366 const auto typeInfoVisitor = [&stringVisitor](uint typeInfo) {
1367 if (typeInfo & IsUnresolvedType)
1368 stringVisitor(typeInfo & TypeNameIndexMask);
1369 };
1370
1371 int fieldCount = MetaObjectPrivateFieldCount;
1372
1373 fieldCount += visitMethods(mo, priv->methodData, priv->methodCount, stringVisitor,
1374 typeInfoVisitor);
1375 fieldCount += visitMethods(mo, priv->constructorData, priv->constructorCount, stringVisitor,
1376 typeInfoVisitor);
1377
1378 fieldCount += visitProperties(mo, stringVisitor, typeInfoVisitor);
1379 fieldCount += visitClassInfo(mo, stringVisitor);
1380 fieldCount += visitEnumerations(mo, stringVisitor);
1381
1382 return fieldCount;
1383}
1384
1385} // anonymous namespace
1386
1387static_assert(QMetaObjectPrivate::OutputRevision == 13, "Check and adjust determineMetaObjectSizes");
1388
1389bool QQmlPropertyCache::determineMetaObjectSizes(const QMetaObject &mo, int *fieldCount,
1390 int *stringCount)
1391{
1392 const QMetaObjectPrivate *priv = reinterpret_cast<const QMetaObjectPrivate*>(mo.d.data);
1393 if (priv->revision != QMetaObjectPrivate::OutputRevision)
1394 return false;
1395
1396 uint highestStringIndex = 0;
1397 const auto stringIndexVisitor = [&highestStringIndex](uint index) {
1398 highestStringIndex = qMax(highestStringIndex, index);
1399 };
1400
1401 *fieldCount = countMetaObjectFields(mo, stringIndexVisitor);
1402 *stringCount = highestStringIndex + 1;
1403
1404 return true;
1405}
1406
1407bool QQmlPropertyCache::addToHash(QCryptographicHash &hash, const QMetaObject &mo)
1408{
1409 int fieldCount = 0;
1410 int stringCount = 0;
1411 if (!determineMetaObjectSizes(mo, &fieldCount, &stringCount)) {
1412 return false;
1413 }
1414
1415 hash.addData({reinterpret_cast<const char *>(mo.d.data), qsizetype(fieldCount * sizeof(uint))});
1416 for (int i = 0; i < stringCount; ++i) {
1417 hash.addData(stringData(&mo, i));
1418 }
1419
1420 return true;
1421}
1422
1423QByteArray QQmlPropertyCache::checksum(QHash<quintptr, QByteArray> *checksums, bool *ok) const
1424{
1425 auto it = checksums->constFind(quintptr(this));
1426 if (it != checksums->constEnd()) {
1427 *ok = true;
1428 return *it;
1429 }
1430
1431 // Generate a checksum on the meta-object data only on C++ types.
1432 if (_metaObject.isShared()) {
1433 *ok = false;
1434 return QByteArray();
1435 }
1436
1437 QCryptographicHash hash(QCryptographicHash::Md5);
1438
1439 if (_parent) {
1440 hash.addData(_parent->checksum(checksums, ok));
1441 if (!*ok)
1442 return QByteArray();
1443 }
1444
1445 if (!addToHash(hash, *_metaObject.metaObject())) {
1446 *ok = false;
1447 return QByteArray();
1448 }
1449
1450 const QByteArray result = hash.result();
1451 if (result.isEmpty()) {
1452 *ok = false;
1453 } else {
1454 *ok = true;
1455 checksums->insert(quintptr(this), result);
1456 }
1457 return result;
1458}
1459
1460/*! \internal
1461 \a index MUST be in the signal index range (see QObjectPrivate::signalIndex()).
1462 This is different from QMetaMethod::methodIndex().
1463*/
1464QList<QByteArray> QQmlPropertyCache::signalParameterNames(int index) const
1465{
1466 const QQmlPropertyData *signalData = signal(index);
1467 if (signalData && signalData->hasArguments()) {
1468 QQmlPropertyCacheMethodArguments *args = (QQmlPropertyCacheMethodArguments *)signalData->arguments();
1469 if (args && args->names)
1470 return *args->names;
1471 const QMetaMethod &method = QMetaObjectPrivate::signal(firstCppMetaObject(), index);
1472 return method.parameterNames();
1473 }
1474 return QList<QByteArray>();
1475}
1476
1477QT_END_NAMESPACE
static Status checkMinimal(const QQmlPropertyData *const existingProperty)
static Status check(const QQmlPropertyData &overridingProperty, const QQmlPropertyData *const existingProperty, CheckMode mode)
static bool hasInvalidModifierCombintation(const QQmlPropertyData &overridingProperty)
static Status checkFull(const QQmlPropertyData &overridingProperty, const QQmlPropertyData *const existingProperty)
Status handleOverride(QQmlPropertyData &overridingProperty, QQmlPropertyData *existingProperty, CheckMode mode)
Q_LOGGING_CATEGORY(lcEventDispatcher, "qt.eventdispatcher")
const QQmlPropertyData * qQmlPropertyCacheProperty(QObject *obj, T name, const QQmlRefPointer< QQmlContextData > &context, QQmlPropertyData *local)
static const QByteArray stringData(const QMetaObject *mo, int index)
static QQmlPropertyData qQmlPropertyCacheCreate(const QMetaObject *metaObject, const T &propertyName)
#define Q_INT16_MAX
static const char * qQmlPropertyCacheToString(QLatin1String string)
static QByteArray qQmlPropertyCacheToString(const QV4::String *string)
static std::pair< bool, int > deriveEncodingAndLength(const char *str)
static QHashedString signalNameToHandlerName(const QHashedString &methodName)
static int metaObjectSignalCount(const QMetaObject *metaObject)