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
qqmldata.cpp
Go to the documentation of this file.
1// Copyright (C) 2026 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
5#include "qqmldata_p.h"
6
7#include <private/qmetaobject_p.h>
8#include <private/qqmlabstractbinding_p.h>
9#include <private/qqmlboundsignal_p.h>
10#include <private/qqmlcontextdata_p.h>
11#include <private/qqmlnotifier_p.h>
12
13#include <QtCore/qtyperevision.h>
14#include <private/qthread_p.h>
15
17
18QQmlData::QQmlData(Ownership ownership)
19 : ownMemory(ownership == OwnsMemory)
20 , indestructible(true)
21 , explicitIndestructibleSet(false)
22 , hasTaintedV4Object(false)
23 , isQueuedForDeletion(false)
24 , rootObjectInCreation(false)
25 , hasInterceptorMetaObject(false)
26 , hasVMEMetaObject(false)
27 , hasConstWrapper(false)
28 , dummy(0)
29 , bindingBitsArraySize(InlineBindingArraySize)
30{
31 memset(bindingBitsValue, 0, sizeof(bindingBitsValue));
32 init();
33}
34
35QQmlData::~QQmlData() = default;
36
37void QQmlData::destroyed(QAbstractDeclarativeData *d, QObject *o)
38{
39 QQmlData *ddata = static_cast<QQmlData *>(d);
40 ddata->destroyed(o);
41}
42
44{
45public:
47
48 int qt_metacall(QMetaObject::Call, int methodIndex, void **a) override {
49 if (!target)
50 return -1;
51
52 QMetaMethod method = target->metaObject()->method(methodIndex);
53 Q_ASSERT(method.methodType() == QMetaMethod::Signal);
54 int signalIndex = QMetaObjectPrivate::signalIndex(method);
55 QQmlData *ddata = QQmlData::get(target, false);
56 QQmlNotifierEndpoint *ep = ddata->notify(signalIndex);
57 if (ep) QQmlNotifier::emitNotify(ep, a);
58
59 delete this;
60
61 return -1;
62 }
63};
64
65void QQmlData::signalEmitted(QAbstractDeclarativeData *, QObject *object, int index, void **a)
66{
67 QQmlData *ddata = QQmlData::get(object, false);
68 if (!ddata) return; // Probably being deleted
69
70 // In general, QML only supports QObject's that live on the same thread as the QQmlEngine
71 // that they're exposed to. However, to make writing "worker objects" that calculate data
72 // in a separate thread easier, QML allows a QObject that lives in the same thread as the
73 // QQmlEngine to emit signals from a different thread. These signals are then automatically
74 // marshalled back onto the QObject's thread and handled by QML from there. This is tested
75 // by the qqmlecmascript::threadSignal() autotest.
76
77 // Relaxed semantics here. If we're on a different thread we might schedule a useless event,
78 // but that should be rare.
79 if (!ddata->notifyList.loadRelaxed())
80 return;
81
82 auto objectThreadData = QObjectPrivate::get(object)->threadData.loadRelaxed();
83 if (QThread::currentThreadId() != objectThreadData->threadId.loadRelaxed()) {
84 if (!objectThreadData->thread.loadAcquire())
85 return;
86
87 QMetaMethod m = QMetaObjectPrivate::signal(object->metaObject(), index);
88 const QList<QByteArray> parameterTypes = m.parameterTypes();
89
90 QVarLengthArray<const QtPrivate::QMetaTypeInterface *, 16> argTypes;
91 argTypes.reserve(1 + parameterTypes.size());
92 argTypes.emplace_back(nullptr); // return type
93 for (const QByteArray &typeName: parameterTypes) {
94 QMetaType type;
95 if (typeName.endsWith('*'))
96 type = QMetaType(QMetaType::VoidStar);
97 else
98 type = QMetaType::fromName(typeName);
99
100 if (!type.isValid()) {
101 qWarning("QObject::connect: Cannot queue arguments of type '%s'\n"
102 "(Make sure '%s' is registered using qRegisterMetaType().)",
103 typeName.constData(), typeName.constData());
104 return;
105 }
106
107 argTypes.emplace_back(type.iface());
108 }
109
110 auto ev = std::make_unique<QQueuedMetaCallEvent>(m.methodIndex(), 0, nullptr, object, index,
111 argTypes.size(), argTypes.data(), a);
112
113 QQmlThreadNotifierProxyObject *mpo = new QQmlThreadNotifierProxyObject;
114 mpo->target = object;
115 mpo->moveToThread(objectThreadData->thread.loadAcquire());
116 QCoreApplication::postEvent(mpo, ev.release());
117
118 } else {
119 QQmlNotifierEndpoint *ep = ddata->notify(index);
120 if (ep) QQmlNotifier::emitNotify(ep, a);
121 }
122}
123
124int QQmlData::receivers(QAbstractDeclarativeData *d, const QObject *, int index)
125{
126 QQmlData *ddata = static_cast<QQmlData *>(d);
127 return ddata->endpointCount(index);
128}
129
130bool QQmlData::isSignalConnected(QAbstractDeclarativeData *d, const QObject *, int index)
131{
132 QQmlData *ddata = static_cast<QQmlData *>(d);
133 return ddata->signalHasEndpoint(index);
134}
135
136int QQmlData::endpointCount(int index)
137{
138 int count = 0;
139 QQmlNotifierEndpoint *ep = notify(index);
140 if (!ep)
141 return count;
142 ++count;
143 while (ep->next) {
144 ++count;
145 ep = ep->next;
146 }
147 return count;
148}
149
150void QQmlData::markAsDeleted(QObject *o)
151{
152 QVarLengthArray<QObject *> workStack;
153 workStack.push_back(o);
154 while (!workStack.isEmpty()) {
155 auto currentObject = workStack.last();
156 workStack.pop_back();
157 QQmlData::setQueuedForDeletion(currentObject);
158 auto currentObjectPriv = QObjectPrivate::get(currentObject);
159 for (QObject *child: std::as_const(currentObjectPriv->children))
160 workStack.push_back(child);
161 }
162}
163
164void QQmlData::setQueuedForDeletion(QObject *object)
165{
166 if (object) {
167 if (QQmlData *ddata = QQmlData::get(object)) {
168 if (ddata->ownContext) {
169 Q_ASSERT(ddata->ownContext.data() == ddata->context);
170 ddata->ownContext->deepClearContextObject(object);
171 ddata->ownContext.reset();
172 ddata->context = nullptr;
173 }
174 ddata->isQueuedForDeletion = true;
175
176 // Disconnect the notifiers now - during object destruction this would be too late,
177 // since the disconnect call wouldn't be able to call disconnectNotify(), as it isn't
178 // possible to get the metaobject anymore.
179 // Also, there is no point in evaluating bindings in order to set properties on
180 // half-deleted objects.
181 ddata->disconnectNotifiers(DeleteNotifyList::No);
182 }
183 }
184}
185
186void QQmlData::flushPendingBinding(int coreIndex)
187{
188 clearPendingBindingBit(coreIndex);
189
190 // Find the binding
191 QQmlAbstractBinding *b = bindings;
192 while (b && (b->targetPropertyIndex().coreIndex() != coreIndex ||
193 b->targetPropertyIndex().hasValueTypeIndex()))
194 b = b->nextBinding();
195
196 if (b && b->targetPropertyIndex().coreIndex() == coreIndex &&
197 !b->targetPropertyIndex().hasValueTypeIndex())
198 b->setEnabled(true, QQmlPropertyData::BypassInterceptor |
199 QQmlPropertyData::DontRemoveBinding);
200}
201
202QQmlData::DeferredData::DeferredData() = default;
203QQmlData::DeferredData::~DeferredData() = default;
204
214
215void QQmlData::deferData(
216 int objectIndex, const QQmlRefPointer<QV4::ExecutableCompilationUnit> &compilationUnit,
217 const QQmlRefPointer<QQmlContextData> &context, const QString &inlineComponentName)
218{
219 QQmlData::DeferredData *deferData = new QQmlData::DeferredData;
220 deferData->deferredIdx = objectIndex;
221 deferData->compilationUnit = compilationUnit;
222 deferData->context = context;
223 deferData->inlineComponentName = inlineComponentName;
224
225 const QV4::CompiledData::Object *compiledObject = compilationUnit->objectAt(objectIndex);
226 const QV4::CompiledData::BindingPropertyData *propertyData
227 = compilationUnit->bindingPropertyDataPerObjectAt(objectIndex);
228
229 const QV4::CompiledData::Binding *binding = compiledObject->bindingTable();
230 for (quint32 i = 0; i < compiledObject->nBindings; ++i, ++binding) {
231 const QQmlPropertyData *property = propertyData->at(i);
232 if (binding->hasFlag(QV4::CompiledData::Binding::IsDeferredBinding))
233 deferData->bindings.insert(property ? property->coreIndex() : -1, binding);
234 }
235
236 deferredData.append(deferData);
237}
238
239void QQmlData::releaseDeferredData()
240{
241 auto it = deferredData.begin();
242 while (it != deferredData.end()) {
243 DeferredData *deferData = *it;
244 if (deferData->bindings.isEmpty()) {
245 delete deferData;
246 it = deferredData.erase(it);
247 } else {
248 ++it;
249 }
250 }
251}
252
253void QQmlData::addNotify(int index, QQmlNotifierEndpoint *endpoint)
254{
255 // Can only happen on "home" thread. We apply relaxed semantics when loading the atomics.
256
257 QQmlNotifyList *list = notifyList.loadRelaxed();
258
259 if (!list) {
260 list = new QQmlNotifyList;
261 // We don't really care when this change takes effect on other threads. The notifyList can
262 // only become non-null once in the life time of a QQmlData. It becomes null again when the
263 // underlying QObject is deleted. At that point any interaction with the QQmlData is UB
264 // anyway. So, for all intents and purposese, the list becomes non-null once and then stays
265 // non-null "forever". We can apply relaxed semantics.
266 notifyList.storeRelaxed(list);
267 }
268
269 Q_ASSERT(!endpoint->isConnected());
270
271 index = qMin(index, 0xFFFF - 1);
272
273 // Likewise, we don't really care _when_ the change in the connectionMask is propagated to other
274 // threads. Cross-thread event ordering is inherently nondeterministic. Therefore, when querying
275 // the conenctionMask in the presence of concurrent modification, any result is correct.
276 list->connectionMask.storeRelaxed(
277 list->connectionMask.loadRelaxed() | (1ULL << quint64(index % 64)));
278
279 if (index < list->notifiesSize) {
280 endpoint->next = list->notifies[index];
281 if (endpoint->next) endpoint->next->prev = &endpoint->next;
282 endpoint->prev = &list->notifies[index];
283 list->notifies[index] = endpoint;
284 } else {
285 list->maximumTodoIndex = qMax(int(list->maximumTodoIndex), index);
286
287 endpoint->next = list->todo;
288 if (endpoint->next) endpoint->next->prev = &endpoint->next;
289 endpoint->prev = &list->todo;
290 list->todo = endpoint;
291 }
292}
293
294void QQmlData::disconnectNotifiers(QQmlData::DeleteNotifyList doDelete)
295{
296 // Can only happen on "home" thread. We apply relaxed semantics when loading the atomics.
297 if (QQmlNotifyList *list = notifyList.loadRelaxed()) {
298 while (QQmlNotifierEndpoint *todo = list->todo)
299 todo->disconnect();
300 for (int ii = 0; ii < list->notifiesSize; ++ii) {
301 while (QQmlNotifierEndpoint *ep = list->notifies[ii])
302 ep->disconnect();
303 }
304 free(list->notifies);
305
306 if (doDelete == DeleteNotifyList::Yes) {
307 // We can only get here from QQmlData::destroyed(), and that can only come from the
308 // the QObject dtor. If you're still sending signals at that point you have UB already
309 // without any threads. Therefore, it's enough to apply relaxed semantics.
310 notifyList.storeRelaxed(nullptr);
311 delete list;
312 } else {
313 // We can use relaxed semantics here. The worst thing that can happen is that some
314 // signal is falsely reported as connected. Signal connectedness across threads
315 // is not quite deterministic anyway.
316 list->connectionMask.storeRelaxed(0);
317 list->maximumTodoIndex = 0;
318 list->notifiesSize = 0;
319 list->notifies = nullptr;
320
321 }
322 }
323}
324
325QHash<QQmlAttachedPropertiesFunc, QObject *> *QQmlData::attachedProperties() const
326{
327 if (!extendedData) extendedData = new QQmlDataExtended;
328 return &extendedData->attachedProperties;
329}
330
331void QQmlData::removeFromContext()
332{
333 if (nextContextObject)
334 nextContextObject->prevContextObject = prevContextObject;
335 if (prevContextObject)
336 *prevContextObject = nextContextObject;
337 else if (outerContext && outerContext->ownedObjects() == this)
338 outerContext->setOwnedObjects(nextContextObject);
339
340 nextContextObject = nullptr;
341 prevContextObject = nullptr;
342 outerContext = nullptr;
343 context = nullptr;
344}
345
346void QQmlData::clearBindings()
347{
348 if (QQmlAbstractBinding *binding = std::exchange(bindings, nullptr)) {
349 for (QQmlAbstractBinding *next = binding; next; next = next->nextBinding())
350 next->setAddedToObject(false);
351 if (!binding->ref.deref())
352 delete binding;
353 }
354}
355
356bool QQmlData::clearSignalHandlers()
357{
358 for (QQmlBoundSignal *signalHandler = std::exchange(signalHandlers, nullptr); signalHandler;) {
359 if (signalHandler->isNotifying()) {
360 signalHandlers = signalHandler;
361 return false;
362 }
363
364 QQmlBoundSignal *next = signalHandler->m_nextSignal;
365 signalHandler->m_prevSignal = nullptr;
366 signalHandler->m_nextSignal = nullptr;
367 delete signalHandler;
368 signalHandler = next;
369 }
370
371 return true;
372}
373
374void QQmlData::clear()
375{
376 removeFromContext();
377 clearBindings();
378
379 compilationUnit.reset();
380 qDeleteAll(std::exchange(deferredData, {}));
381
382 if (!clearSignalHandlers())
383 qFatal("Can't clear QQmlData from signal handler");
384
385 BindingBitsType *bits = (bindingBitsArraySize == InlineBindingArraySize)
386 ? bindingBitsValue
387 : bindingBits;
388 memset(bits, 0, bindingBitsArraySize * sizeof(BindingBitsType));
389
390 propertyCache.reset();
391 ownContext.reset();
392
393 disconnectNotifiers(DeleteNotifyList::No);
394
395 delete std::exchange(extendedData, nullptr);
396 propertyObservers.clear();
397
398 lineNumber = 0;
399 columnNumber = 0;
400 rootObjectInCreation = false;
401 hasInterceptorMetaObject = false;
402 hasVMEMetaObject = false;
403 cuObjectIndex = -1;
404}
405
406void QQmlData::destroyed(QObject *object)
407{
408 removeFromContext();
409 clearBindings();
410
411 compilationUnit.reset();
412 qDeleteAll(deferredData);
413 deferredData.clear();
414
415 if (!clearSignalHandlers()) {
416 // The object is being deleted during signal handler evaluation.
417 // This will cause a crash due to invalid memory access when the
418 // evaluation has completed.
419 // Abort with a friendly message instead.
420 QString locationString;
421 QQmlBoundSignalExpression *expr = signalHandlers->expression();
422 if (expr) {
423 QQmlSourceLocation location = expr->sourceLocation();
424 if (location.sourceFile.isEmpty())
425 location.sourceFile = QStringLiteral("<Unknown File>");
426 locationString.append(location.sourceFile);
427 locationString.append(QStringLiteral(":%0: ").arg(location.line));
428 QString source = expr->expression();
429 if (source.size() > 100) {
430 source.truncate(96);
431 source.append(QLatin1String(" ..."));
432 }
433 locationString.append(source);
434 } else {
435 locationString = QStringLiteral("<Unknown Location>");
436 }
437 qFatal("Object %p destroyed while one of its QML signal handlers is in progress.\n"
438 "Most likely the object was deleted synchronously (use QObject::deleteLater() "
439 "instead), or the application is running a nested event loop.\n"
440 "This behavior is NOT supported!\n"
441 "%s", object, qPrintable(locationString));
442 }
443
444 if (bindingBitsArraySize > InlineBindingArraySize)
445 free(bindingBits);
446
447 if (propertyCache)
448 propertyCache.reset();
449
450 ownContext.reset();
451
452 while (guards) {
453 auto *guard = guards;
454 guard->setObject(nullptr);
455 if (guard->objectDestroyed)
456 guard->objectDestroyed(guard);
457 }
458
459 disconnectNotifiers(DeleteNotifyList::Yes);
460
461 if (extendedData)
462 delete extendedData;
463
464 // Dispose the handle.
465 jsWrapper.clear();
466
467 if (ownMemory)
468 delete this;
469 else
470 this->~QQmlData();
471}
472
473QQmlData::BindingBitsType *QQmlData::growBits(QObject *obj, int bit)
474{
475 BindingBitsType *bits = (bindingBitsArraySize == InlineBindingArraySize) ? bindingBitsValue : bindingBits;
476 int props = QQmlMetaObject(obj).propertyCount();
477 Q_ASSERT(bit < 2 * props);
478 Q_UNUSED(bit); // .. for Q_NO_DEBUG mode when the assert above expands to empty
479
480 uint arraySize = (2 * static_cast<uint>(props) + BitsPerType - 1) / BitsPerType;
481 Q_ASSERT(arraySize > 1);
482 Q_ASSERT(arraySize <= 0xffff); // max for bindingBitsArraySize
483
484 BindingBitsType *newBits = static_cast<BindingBitsType *>(malloc(arraySize*sizeof(BindingBitsType)));
485 memcpy(newBits, bits, bindingBitsArraySize * sizeof(BindingBitsType));
486 memset(newBits + bindingBitsArraySize, 0, sizeof(BindingBitsType) * (arraySize - bindingBitsArraySize));
487
488 if (bindingBitsArraySize > InlineBindingArraySize)
489 free(bits);
490 bindingBits = newBits;
491 bits = newBits;
492 bindingBitsArraySize = arraySize;
493 return bits;
494}
495
496QQmlData *QQmlData::createQQmlData(QObjectPrivate *priv)
497{
498 Q_ASSERT(priv);
499 Q_ASSERT(!priv->isDeletingChildren);
500 priv->declarativeData = new QQmlData(OwnsMemory);
501 return static_cast<QQmlData *>(priv->declarativeData);
502}
503
504QQmlPropertyCache::ConstPtr QQmlData::createPropertyCache(QObject *object)
505{
506 QQmlData *ddata = QQmlData::get(object, /*create*/true);
507 ddata->propertyCache = QQmlMetaType::propertyCache(object, QTypeRevision {});
508 return ddata->propertyCache;
509}
510
511QT_END_NAMESPACE
QHash< QQmlAttachedPropertiesFunc, QObject * > attachedProperties
Definition qqmldata.cpp:212
~QQmlDataExtended()=default
QPointer< QObject > target
Definition qqmldata.cpp:46
int qt_metacall(QMetaObject::Call, int methodIndex, void **a) override
Definition qqmldata.cpp:48
Combined button and popup list for selecting options.