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
qv4qmlcontext.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/qjsvalue_p.h>
8#include <private/qqmlcontext_p.h>
9#include <private/qqmlengine_p.h>
10#include <private/qqmlglobal_p.h>
11#include <private/qqmljavascriptexpression_p.h>
12#include <private/qqmllistwrapper_p.h>
13#include <private/qqmltypewrapper_p.h>
14#include <private/qv4compileddata_p.h>
15#include <private/qv4engine_p.h>
16#include <private/qv4function_p.h>
17#include <private/qv4identifiertable_p.h>
18#include <private/qv4lookup_p.h>
19#include <private/qv4mm_p.h>
20#include <private/qv4module_p.h>
21#include <private/qv4objectproto_p.h>
22#include <private/qv4qobjectwrapper_p.h>
23#include <private/qv4stackframe_p.h>
24#include <private/qv4value_p.h>
25
26#include <QtCore/qloggingcategory.h>
27
29
30Q_STATIC_LOGGING_CATEGORY(lcQmlContext, "qt.qml.context");
31
32using namespace QV4;
33
36
37void Heap::QQmlContextWrapper::init(QQmlRefPointer<QQmlContextData> context, QObject *scopeObject)
38{
39 Object::init();
40 this->context = context.take();
41 this->scopeObject.init(scopeObject);
42 scopePropertyCache = nullptr;
43 if (scopeObject && !QQmlData::wasDeleted(scopeObject))
44 scopePropertyCache = QQmlData::ensurePropertyCache(scopeObject).take();
45}
46
47void Heap::QQmlContextWrapper::destroy()
48{
49 context->release();
50 context = nullptr;
51 scopeObject.destroy();
52 if (scopePropertyCache)
53 scopePropertyCache->release();
54 Object::destroy();
55}
56
58 QV4::ExecutionEngine *v4, const QQmlRefPointer<QQmlContextData> &context, String *name,
59 bool *hasProperty, Value *base, QV4::Lookup *lookup, QV4::Lookup *originalLookup,
60 QQmlEnginePrivate *ep)
61{
62 const int propertyIdx = context->propertyIndex(name->d());
63
64 if (propertyIdx == -1)
65 return OptionalReturnedValue();
66
67 if (propertyIdx < context->numIdValues()) {
68 if (hasProperty)
69 *hasProperty = true;
70
71 // The same code can run in different immediate contexts, for example a script string in
72 // a context created by the user. Only cache the index if the context has the id table
73 // of the component the code belongs to. Compilation unit and component object index
74 // together identify the id table.
75 if (lookup && context->typeCompilationUnit().data()
76 == v4->currentStackFrame->v4Function->executableCompilationUnit()) {
77 lookup->qmlContextIdObjectLookup.objectId = propertyIdx;
78 lookup->qmlContextIdObjectLookup.componentObjectIndex
79 = context->componentObjectIndex();
80 lookup->call = Lookup::Call::ContextGetterIdObject;
81 return OptionalReturnedValue(lookup->contextGetter(v4, base));
82 } else if (originalLookup && !lookup) {
83 originalLookup->call = Lookup::Call::ContextGetterInParentContextHierarchy;
84 }
85
86 if (ep->propertyCapture)
87 ep->propertyCapture->captureProperty(context->idValueBindings(propertyIdx));
88 return OptionalReturnedValue(QV4::QObjectWrapper::wrap(v4, context->idValue(propertyIdx)));
89 }
90
91 QQmlContextPrivate *cp = context->asQQmlContextPrivate();
92
93 if (ep->propertyCapture)
94 ep->propertyCapture->captureProperty(context->asQQmlContext(), -1, propertyIdx + cp->notifyIndex());
95
96 const QVariant &value = cp->propertyValue(propertyIdx);
97 if (hasProperty)
98 *hasProperty = true;
99 if (value.userType() == qMetaTypeId<QList<QObject*> >()) {
100 QQmlListProperty<QObject> prop(context->asQQmlContext(), (void*) qintptr(propertyIdx),
101 QQmlContextPrivate::context_count,
102 QQmlContextPrivate::context_at);
103 return OptionalReturnedValue(QmlListWrapper::create(v4, prop, QMetaType::fromType<QQmlListProperty<QObject> >()));
104 }
105 return OptionalReturnedValue(v4->fromVariant(cp->propertyValue(propertyIdx)));
106}
107
108template<typename Lookup>
109bool performLookup(ScopedValue *result, bool *hasProperty, const Lookup &lookup) {
110 bool hasProp = false;
111 *result = lookup(&hasProp);
112 if (hasProp) {
113 if (hasProperty)
114 *hasProperty = hasProp;
115 return true;
116 }
117 return false;
118}
119
121{
122 return (l && l->forCall)
123 ? QV4::QObjectWrapper::CheckRevision
124 : (QV4::QObjectWrapper::CheckRevision | QV4::QObjectWrapper::AttachMethods);
125}
126
127/*!
128 \internal
129 Searches the module the context wrapped by \a resource belongs to, if any. This is what code
130 running outside of that context can see besides the plain JavaScript properties.
131*/
133 const QQmlContextWrapper *resource, PropertyKey id, const Value *receiver,
134 bool *hasProperty)
135{
136 if (!resource->d()->module)
137 return OptionalReturnedValue();
138
139 QV4::Scope scope(resource->engine());
140 Scoped<Module> module(scope, resource->d()->module);
141 bool hasProp = false;
142 ScopedValue value(scope, module->get(id, receiver, &hasProp));
143 if (!hasProp)
144 return OptionalReturnedValue();
145
146 if (hasProperty)
147 *hasProperty = hasProp;
148 return OptionalReturnedValue(value->asReturnedValue());
149}
150
151/*!
152 \internal
153 Prepares \a lookup to return the singleton \a type.
154*/
155static void setupSingletonLookup(QV4::ExecutionEngine *v4, Lookup *lookup, const QQmlType &type)
156{
157 bool isValueSingleton = false;
158 QQmlEnginePrivate *e = QQmlEnginePrivate::get(v4->qmlEngine());
159 if (type.isQObjectSingleton() || type.isCompositeSingleton()) {
160 e->singletonInstance<QObject*>(type);
161 lookup->qmlContextSingletonLookup.singletonObject.set(
162 v4, Value::fromReturnedValue(QQmlTypeWrapper::create(v4, nullptr, type))
163 .heapObject());
164 } else {
165 QJSValue singleton = e->singletonInstance<QJSValue>(type);
166
167 // QString values should already have been put on the engine heap at
168 // this point to manage their memory. We later assume this has already
169 // happened.
170 Q_ASSERT(!QJSValuePrivate::asQString(&singleton));
171
172 if (QV4::Value *val = QJSValuePrivate::takeManagedValue(&singleton)) {
173 lookup->qmlContextSingletonLookup.singletonObject.set(v4, val->heapObject());
174 } else {
175 lookup->qmlContextSingletonLookup.singletonValue
176 = QJSValuePrivate::asReturnedValue(&singleton);
177 isValueSingleton = true;
178 }
179 }
180 lookup->call = isValueSingleton
181 ? Lookup::Call::ContextGetterValueSingleton
182 : Lookup::Call::ContextGetterSingleton;
183}
184
185/*!
186 \internal
187 Searches the attached properties, enums, imported scripts, types and namespaces visible in
188 \a context for \a name.
189*/
191 QV4::ExecutionEngine *v4, const QQmlRefPointer<QQmlContextData> &context,
192 QObject *scopeObject, String *name, bool *hasProperty, Value *base, Lookup *lookup)
193{
194 if (!context->imports() || !(name->startsWithUpper() || context->valueTypesAreAddressable()))
195 return OptionalReturnedValue();
196
197 const QQmlTypeNameCache::Result r = context->imports()->query<QQmlImport::AllowRecursion>(
198 name, v4->typeLoader());
199 if (!r.isValid())
200 return OptionalReturnedValue();
201
202 if (hasProperty)
203 *hasProperty = true;
204
205 QV4::Scope scope(v4);
206 ScopedValue result(scope);
207
208 if (r.scriptIndex != -1) {
209 if (lookup) {
210 lookup->qmlContextScriptLookup.scriptIndex = r.scriptIndex;
211 lookup->call = Lookup::Call::ContextGetterScript;
212 return OptionalReturnedValue(lookup->contextGetter(v4, base));
213 }
214 QV4::ScopedObject scripts(scope, context->importedScripts());
215 if (scripts)
216 return OptionalReturnedValue(scripts->get(r.scriptIndex));
217 return OptionalReturnedValue(QV4::Encode::null());
218 } else if (r.type.isValid()) {
219 if (lookup && r.type.isSingleton()) {
220 setupSingletonLookup(v4, lookup, r.type);
221 return OptionalReturnedValue(lookup->contextGetter(v4, base));
222 }
223 result = QQmlTypeWrapper::create(v4, scopeObject, r.type);
224 } else if (r.importNamespace) {
225 result = QQmlTypeWrapper::create(v4, scopeObject, context->imports(), r.importNamespace);
226 }
227
228 if (lookup) {
229 lookup->qmlTypeLookup.qmlTypeWrapper.set(v4, result->heapObject());
230 lookup->call = Lookup::Call::ContextGetterType;
231 }
232 return OptionalReturnedValue(result->asReturnedValue());
233}
234
235/*!
236 \internal
237 Searches the contexts enclosing \a outer that belong to the same compilation unit as \a
238 context, advancing \a outer to the first context beyond them. Only applies if the components
239 of the compilation unit are bound.
240*/
242 QV4::ExecutionEngine *v4, const QQmlRefPointer<QQmlContextData> &context,
243 QQmlRefPointer<QQmlContextData> &outer, String *name, bool *hasProperty, Value *base,
244 Lookup *originalLookup, QQmlEnginePrivate *ep)
245{
246 const auto cu = context->typeCompilationUnit();
247 if (!cu || !cu->componentsAreBound())
248 return OptionalReturnedValue();
249
250 // If components are bound in this CU, we can search the whole context hierarchy
251 // of the file. Bound components' contexts override their local properties.
252 // You also can't instantiate bound components outside of their creation
253 // context. Therefore this is safe.
254 for (; outer && outer->typeCompilationUnit() == cu; outer = outer->parent()) {
255 if (auto property = searchContextProperties(
256 v4, outer, name, hasProperty, base, nullptr, originalLookup, ep)) {
257 return property;
258 }
259 }
260 return OptionalReturnedValue();
261}
262
263/*!
264 \internal
265 Searches the properties and methods of \a scopeObject for \a name, and prepares \a lookup if
266 it can accelerate the next access.
267*/
269 QV4::ExecutionEngine *v4, const QQmlRefPointer<QQmlContextData> &context,
270 QObject *scopeObject, String *name, bool *hasProperty, Value *base, Lookup *lookup)
271{
272 QV4::Scope scope(v4);
273 bool hasProp = false;
274 const QQmlPropertyData *propertyData = nullptr;
275
276 QV4::ScopedObject wrapper(scope, QV4::QObjectWrapper::wrap(v4, scopeObject));
277 QV4::ScopedValue result(scope, QV4::QObjectWrapper::getQmlProperty(
278 v4, context, wrapper->d(), scopeObject, name,
279 getQmlPropertyFlags(lookup), &hasProp, &propertyData));
280 if (!hasProp)
281 return OptionalReturnedValue();
282
283 if (hasProperty)
284 *hasProperty = true;
285 if (base)
286 *base = wrapper;
287
288 if (lookup) {
289 QQmlData *ddata = QQmlData::get(scopeObject, false);
290 if (ddata && ddata->propertyCache) {
291 ScopedValue val(scope, base ? *base : Value::fromReturnedValue(
292 QV4::QObjectWrapper::wrap(v4, scopeObject)));
293 if (QObjectMethod *method = result->as<QObjectMethod>()) {
294 QV4::setupQObjectMethodLookup(
295 lookup, ddata->propertyCache, propertyData, val->objectValue(),
296 method->d());
297 lookup->call = Lookup::Call::ContextGetterScopeObjectMethod;
298 } else {
299 QV4::setupQObjectLookup(lookup, ddata, propertyData, val->objectValue());
300 lookup->call = Lookup::Call::ContextGetterScopeObjectProperty;
301 }
302 }
303 }
304
305 return OptionalReturnedValue(result->asReturnedValue());
306}
307
308/*!
309 \internal
310 Searches the properties and methods of the context object of \a context for \a name, and
311 prepares \a lookup if it can accelerate the next access. \a contextGetterCall is the getter
312 to use for properties. It is the scope object getter if scope and context object are the same.
313*/
315 QV4::ExecutionEngine *v4, const QQmlRefPointer<QQmlContextData> &context, String *name,
316 bool *hasProperty, Value *base, Lookup *lookup, Lookup *originalLookup,
317 Lookup::Call contextGetterCall)
318{
319 QObject *contextObject = context->contextObject();
320 if (!contextObject)
321 return OptionalReturnedValue();
322
323 QV4::Scope scope(v4);
324 bool hasProp = false;
325 const QQmlPropertyData *propertyData = nullptr;
326 QV4::ScopedObject wrapper(scope, QV4::QObjectWrapper::wrap(v4, contextObject));
327 QV4::ScopedValue result(scope, QV4::QObjectWrapper::getQmlProperty(
328 v4, context, wrapper->d(), contextObject, name,
329 getQmlPropertyFlags(lookup), &hasProp, &propertyData));
330 if (!hasProp)
331 return OptionalReturnedValue();
332
333 if (hasProperty)
334 *hasProperty = true;
335 if (base)
336 *base = wrapper;
337
338 if (lookup) {
339 QQmlData *ddata = QQmlData::get(contextObject, false);
340 if (ddata && ddata->propertyCache && lookup->call != contextGetterCall) {
341 ScopedValue val(scope, base ? *base : Value::fromReturnedValue(
342 QV4::QObjectWrapper::wrap(v4, contextObject)));
343 if (QObjectMethod *method = result->as<QObjectMethod>()) {
344 setupQObjectMethodLookup(
345 lookup, ddata->propertyCache, propertyData, val->objectValue(),
346 method->d());
347 if (contextGetterCall == Lookup::Call::ContextGetterScopeObjectProperty)
348 lookup->call = Lookup::Call::ContextGetterScopeObjectMethod;
349 else
350 lookup->call = Lookup::Call::ContextGetterContextObjectMethod;
351 } else {
352 setupQObjectLookup(lookup, ddata, propertyData, val->objectValue());
353 lookup->call = contextGetterCall;
354 }
355 }
356 } else if (originalLookup) {
357 originalLookup->call = Lookup::Call::ContextGetterInParentContextHierarchy;
358 }
359
360 return OptionalReturnedValue(result->asReturnedValue());
361}
362
363/*!
364 \internal
365 Resolves the global object getter on \a lookup and turns it into a lookup that caches a
366 hit in the global object. The global object cannot change, and everything searched before it
367 is either stable or not covered by the lookup anyway. Returns false and leaves the generic
368 global getter in place if the hit cannot be cached.
369*/
370static bool cacheGlobalLookup(QV4::ExecutionEngine *v4, Lookup *lookup, ScopedValue *result)
371{
372 *result = lookup->resolveGlobalGetter(v4);
373 if (lookup->call == Lookup::Call::GlobalGetterGeneric)
374 return false;
375 lookup->qmlContextGlobalLookup.getterTrampoline = lookup->call;
376 lookup->call = Lookup::Call::ContextGetterInGlobalObject;
377 return true;
378}
379
381 const QQmlPropertyCache *cache, QV4::ExecutionEngine *v4, String *name)
382{
383 // QObjectWrapper provides those for any QObject.
384 if (name->equals(v4->id_destroy()) || name->equals(v4->id_toString()))
385 return true;
386
387 return cache->property(name->toQString(), nullptr, nullptr) != nullptr;
388}
389
390ReturnedValue QQmlContextWrapper::getPropertyAndBase(const QQmlContextWrapper *resource, PropertyKey id, const Value *receiver, bool *hasProperty, Value *base, Lookup *lookup)
391{
392 if (!id.isString())
393 return Object::virtualGet(resource, id, receiver, hasProperty);
394
395 QV4::ExecutionEngine *v4 = resource->engine();
396
397 if (v4->callingQmlContext().data() != resource->d()->context) {
398 if (auto property = searchModule(resource, id, receiver, hasProperty))
399 return *property;
400 return Object::virtualGet(resource, id, receiver, hasProperty);
401 }
402
403 QV4::Scope scope(v4);
404 ScopedValue result(scope);
405
406 // It's possible we could delay the calculation of the "actual" context (in the case
407 // of sub contexts) until it is definitely needed.
408 QQmlRefPointer<QQmlContextData> context = resource->getContext();
409 QQmlRefPointer<QQmlContextData> expressionContext = context;
410
411 if (!context) {
412 if (hasProperty)
413 *hasProperty = true;
414 return result->asReturnedValue();
415 }
416
417 // Search type (attached property/enum/imported scripts) names
418 // while (context) {
419 // Search context properties
420 // Search scope object
421 // Search context object
422 // context = context->parent
423 // }
424
425 QObject *scopeObject = resource->getScopeObject();
426
427 ScopedString name(scope, id.asStringOrSymbol());
428
429 const auto globalLookup = [v4, &name](bool *hasProp) {
430 return v4->globalObject->get(name, hasProp);
431 };
432
433 const auto jsLookup = [resource, &id, receiver](bool *hasProp) {
434 return Object::virtualGet(resource, id, receiver, hasProp);
435 };
436
437 // The scope object would have resolved the name, but it is gone. The search doesn't resume
438 // past it. Its type is still known.
439 const bool scopeObjectLost = !scopeObject || QQmlData::wasDeleted(scopeObject);
440 const QQmlPropertyCache *lostScopeCache = scopeObjectLost ? resource->d()->scopePropertyCache
441 : nullptr;
442
443 const bool isJSContext = context->isJSContext();
444
445 // Do the generic JS lookup early in case of a JavaScript context.
446 if (isJSContext && performLookup(&result, hasProperty, jsLookup))
447 return result->asReturnedValue();
448
449 // If the scope object is a QAbstractDynamicMetaObject, then QMetaObject::indexOfProperty
450 // will call createProperty() on the QADMO and implicitly create the property. While that
451 // is questionable behavior, there are two use-cases that we support in the light of this:
452 //
453 // (1) The implicit creation of properties is necessary because it will also result in
454 // a recorded capture, which will allow a re-evaluation of bindings when the value
455 // is populated later. See QTBUG-35233 and the test-case in tst_qqmlpropertymap.
456 //
457 // (1) Looking up "console" in order to place a console.log() call for example must
458 // find the console instead of creating a new property. Therefore we prioritize the
459 // lookup in the global object here.
460 //
461 // Note: The scope object is only a QADMO for example when somebody registers a QQmlPropertyMap
462 // sub-class as QML type and then instantiates it in .qml.
463 const QMetaObjectPrivate *metaObjectPrivate = scopeObject
464 ? reinterpret_cast<const QMetaObjectPrivate *>(scopeObject->metaObject()->d.data)
465 : nullptr;
466 const bool scopeObjectIsDynamic = metaObjectPrivate
467 && (metaObjectPrivate->flags & DynamicMetaObject);
468 if (scopeObjectIsDynamic) {
469 if (performLookup(&result, hasProperty, globalLookup))
470 return result->asReturnedValue();
471 }
472
473 QQmlEnginePrivate *ep = QQmlEnginePrivate::get(v4->qmlEngine());
474
475 if (auto imported = searchImports(v4, context, scopeObject, name, hasProperty, base, lookup))
476 return *imported;
477
478 // The types cannot change, so they can be cached. Everything else is not predictable if the
479 // scope object is dynamic, so don't try to optimize any lookups.
480 if (scopeObjectIsDynamic)
481 lookup = nullptr;
482
483 Lookup * const originalLookup = lookup;
484
485 Lookup::Call contextGetterCall = Lookup::Call::ContextGetterContextObjectProperty;
486
487 // minor optimization so we don't potentially try two property lookups on the same object
488 if (scopeObject == context->contextObject()) {
489 scopeObject = nullptr;
490 contextGetterCall = Lookup::Call::ContextGetterScopeObjectProperty;
491 }
492
493 // The global object comes after the immediate context, the scope object, the context object,
494 // and the lexically enclosing contexts of a bound component, but before any other context.
495 bool globalSearched = false;
496 bool immediateContextDone = false;
497
498 QQmlRefPointer<QQmlContextData> outer = context;
499 while (context) {
500 if (immediateContextDone && outer == context && !globalSearched
501 && !ep->preferContextPropertiesOverJavaScriptGlobals) {
502 globalSearched = true;
503 if (!isJSContext && performLookup(&result, hasProperty, jsLookup))
504 return result->asReturnedValue();
505 if (originalLookup) {
506 // Don't throw if the global object doesn't have the name.
507 if (v4->globalObject->hasProperty(id)) {
508 if (hasProperty)
509 *hasProperty = true;
510 if (!cacheGlobalLookup(v4, originalLookup, &result))
511 originalLookup->call = Lookup::Call::ContextGetterGeneric;
512 return result->asReturnedValue();
513 }
514 } else if (performLookup(&result, hasProperty, globalLookup)) {
515 return result->asReturnedValue();
516 }
517 }
518
519 if (outer == context) {
520 if (auto property = searchContextProperties(
521 v4, context, name, hasProperty, base, lookup, originalLookup, ep)) {
522 return *property;
523 }
524
525 outer = outer->parent();
526
527 if (auto property = searchBoundComponentContexts(
528 v4, context, outer, name, hasProperty, base, originalLookup, ep)) {
529 return *property;
530 }
531 }
532
533 if (lostScopeCache) {
534 if (lostScopeCacheResolves(lostScopeCache, v4, name)) {
535 if (hasProperty)
536 *hasProperty = true;
537 return v4->throwReferenceError(name->toQString());
538 }
539 lostScopeCache = nullptr;
540 }
541
542 if (scopeObject && !scopeObjectLost) {
543 if (auto property = searchScopeObject(
544 v4, context, scopeObject, name, hasProperty, base, lookup)) {
545 return *property;
546 }
547 }
548 scopeObject = nullptr;
549
550 // The context object would have resolved the name, but it is gone. The search doesn't
551 // resume past it. Its type is still known.
552 if (!immediateContextDone && !context->contextObject()) {
553 if (const QQmlPropertyCache *lostCache = context->lostContextObjectCache();
554 lostCache && lostScopeCacheResolves(lostCache, v4, name)) {
555 if (hasProperty)
556 *hasProperty = true;
557 return v4->throwReferenceError(name->toQString());
558 }
559 }
560
561 if (auto property = searchContextObject(
562 v4, context, name, hasProperty, base, lookup, originalLookup,
563 contextGetterCall)) {
564 return *property;
565 }
566
567 immediateContextDone = true;
568 context = context->parent();
569
570 // As the hierarchy of contexts is not stable, we can't do accelerated lookups beyond
571 // the immediate QML context (of the .qml file).
572 lookup = nullptr;
573 }
574
575 if (!globalSearched) {
576 // Do the generic JS lookup late in case of a non-JavaScript context.
577 // The scope, context, types etc should be able to override it.
578 if (!isJSContext && performLookup(&result, hasProperty, jsLookup))
579 return result->asReturnedValue();
580
581 // Do a lookup in the global object here to avoid expressionContext->unresolvedNames
582 // becoming true if we access properties of the global object.
583 if (originalLookup) {
584 if (cacheGlobalLookup(v4, originalLookup, &result)) {
585 if (hasProperty)
586 *hasProperty = true;
587 return result->asReturnedValue();
588 }
589 originalLookup->call = Lookup::Call::ContextGetterGeneric;
590 } else if (performLookup(&result, hasProperty, globalLookup)) {
591 return result->asReturnedValue();
592 }
593 } else if (originalLookup) {
594 // Not found anywhere. Resolving the global getter throws the ReferenceError.
595 originalLookup->resolveGlobalGetter(v4);
596 originalLookup->call = Lookup::Call::ContextGetterGeneric;
597 }
598
599 expressionContext->setUnresolvedNames(true);
600
601 return Encode::undefined();
602}
603
604ReturnedValue QQmlContextWrapper::virtualGet(const Managed *m, PropertyKey id, const Value *receiver, bool *hasProperty)
605{
606 Q_ASSERT(m->as<QQmlContextWrapper>());
607 const QQmlContextWrapper *This = static_cast<const QQmlContextWrapper *>(m);
608 return getPropertyAndBase(This, id, receiver, hasProperty, /*base*/nullptr);
609}
610
611bool QQmlContextWrapper::virtualPut(Managed *m, PropertyKey id, const Value &value, Value *receiver)
612{
613 Q_ASSERT(m->as<QQmlContextWrapper>());
614
615 if (id.isSymbol() || id.isArrayIndex())
616 return Object::virtualPut(m, id, value, receiver);
617
618 QQmlContextWrapper *resource = static_cast<QQmlContextWrapper *>(m);
619 ExecutionEngine *v4 = resource->engine();
620 QV4::Scope scope(v4);
621 if (scope.hasException())
622 return false;
623 QV4::Scoped<QQmlContextWrapper> wrapper(scope, resource);
624
625 auto member = wrapper->internalClass()->findValueOrSetter(id);
626 if (member.index < UINT_MAX)
627 return wrapper->putValue(member.index, member.attrs, value);
628
629 // It's possible we could delay the calculation of the "actual" context (in the case
630 // of sub contexts) until it is definitely needed.
631 QQmlRefPointer<QQmlContextData> context = wrapper->getContext();
632 QQmlRefPointer<QQmlContextData> expressionContext = context;
633
634 if (!context)
635 return false;
636
637 // See QQmlContextWrapper::Getter for resolution order
638
639 QObject *scopeObject = wrapper->getScopeObject();
640 ScopedString name(scope, id.asStringOrSymbol());
641
642 while (context) {
643 // Search context properties
644 if (const int propertyIndex = context->propertyIndex(name->d()); propertyIndex != -1) {
645 if (propertyIndex < context->numIdValues()) {
646 v4->throwError(QLatin1String("left-hand side of assignment operator is not an lvalue"));
647 return false;
648 }
649 return false;
650 }
651
652 // Search scope object
653 if (scopeObject &&
654 QV4::QObjectWrapper::setQmlProperty(v4, context, scopeObject, name, QV4::QObjectWrapper::CheckRevision, value))
655 return true;
656 scopeObject = nullptr;
657
658 // Search context object
659 if (context->contextObject() &&
660 QV4::QObjectWrapper::setQmlProperty(v4, context, context->contextObject(), name,
661 QV4::QObjectWrapper::CheckRevision, value))
662 return true;
663
664 context = context->parent();
665 }
666
667 expressionContext->setUnresolvedNames(true);
668
669 QString error = QLatin1String("Invalid write to global property \"") + name->toQString() +
670 QLatin1Char('"');
671 v4->throwError(error);
672 return false;
673}
674
675ReturnedValue QQmlContextWrapper::resolveQmlContextPropertyLookupGetter(Lookup *l, ExecutionEngine *engine, Value *base)
676{
677 Scope scope(engine);
678 auto *func = engine->currentStackFrame->v4Function;
679 ScopedPropertyKey name(scope, engine->identifierTable->asPropertyKey(
680 func->compilationUnit->runtimeStrings[l->nameIndex]));
681
682 // Special hack for bounded signal expressions, where the parameters of signals are injected
683 // into the handler expression through the locals of the call context. So for onClicked: { ... }
684 // the parameters of the clicked signal are injected and we must allow for them to be found here
685 // before any other property from the QML context.
686 for (Heap::ExecutionContext *ctx = engine->currentContext()->d(); ctx; ctx = ctx->outer) {
687 if (ctx->type == Heap::ExecutionContext::Type_CallContext) {
688 const uint index = ctx->internalClass->indexOfValueOrGetter(name);
689 if (index < std::numeric_limits<uint>::max()) {
690 if (!func->detectedInjectedParameters) {
691 const auto location = func->sourceLocation();
692 qCWarning(lcQmlContext).nospace().noquote()
693 << location.sourceFile << ":" << location.line << ":" << location.column
694 << " Parameter \"" << name->toQString() << "\" is not declared."
695 << " Injection of parameters into signal handlers is deprecated."
696 << " Use JavaScript functions with formal parameters instead.";
697
698 // Don't warn over and over for the same function
699 func->detectedInjectedParameters = true;
700 }
701
702 return static_cast<Heap::CallContext *>(ctx)->locals[index].asReturnedValue();
703 }
704 }
705
706 // Skip only block and call contexts.
707 // Other contexts need a regular QML property lookup. See below.
708 if (ctx->type != Heap::ExecutionContext::Type_BlockContext && ctx->type != Heap::ExecutionContext::Type_CallContext)
709 break;
710 }
711
712 bool hasProperty = false;
713 ScopedValue result(scope);
714
715 Scoped<QmlContext> callingQmlContext(scope, engine->qmlContext());
716 if (callingQmlContext) {
717 Scoped<QQmlContextWrapper> qmlContextWrapper(scope, callingQmlContext->d()->qml());
718 result = QQmlContextWrapper::getPropertyAndBase(
719 qmlContextWrapper, name, /*receiver*/nullptr, &hasProperty, base, l);
720 } else {
721 // Code path typical to worker scripts, compiled with lookups but no qml context.
722 result = l->resolveGlobalGetter(engine);
723 if (l->call != Lookup::Call::GlobalGetterGeneric) {
724 hasProperty = true;
725 l->qmlContextGlobalLookup.getterTrampoline = l->call;
726 l->call = Lookup::Call::ContextGetterInGlobalObject;
727 }
728 }
729 if (!hasProperty)
730 return engine->throwReferenceError(name->toQString());
731 return result->asReturnedValue();
732}
733
734ReturnedValue QQmlContextWrapper::lookupScript(Lookup *l, ExecutionEngine *engine, Value *base)
735{
736 Q_UNUSED(base);
737 Scope scope(engine);
738 Scoped<QmlContext> qmlContext(scope, engine->qmlContext());
739 if (!qmlContext)
740 return QV4::Encode::null();
741
742 QQmlRefPointer<QQmlContextData> context = qmlContext->qmlContext();
743 if (!context)
744 return QV4::Encode::null();
745
746 QV4::ScopedObject scripts(scope, context->importedScripts());
747 if (!scripts)
748 return QV4::Encode::null();
749 return scripts->get(l->qmlContextScriptLookup.scriptIndex);
750}
751
752ReturnedValue QQmlContextWrapper::lookupSingleton(Lookup *l, ExecutionEngine *engine, Value *base)
753{
754 Q_UNUSED(engine);
755 Q_UNUSED(base);
756
757 return l->qmlContextSingletonLookup.singletonObject->asReturnedValue();
758}
759
760ReturnedValue QQmlContextWrapper::lookupValueSingleton(Lookup *l, ExecutionEngine *engine, Value *base)
761{
762 Q_UNUSED(engine);
763 Q_UNUSED(base);
764
765 Q_ASSERT(l->qmlContextSingletonLookup.singletonObject == nullptr);
766 return l->qmlContextSingletonLookup.singletonValue;
767}
768
769ReturnedValue QQmlContextWrapper::lookupIdObject(Lookup *l, ExecutionEngine *engine, Value *base)
770{
771 Q_UNUSED(base);
772 Scope scope(engine);
773 Scoped<QmlContext> qmlContext(scope, engine->qmlContext());
774 if (!qmlContext)
775 return QV4::Encode::null();
776
777 QQmlRefPointer<QQmlContextData> context = qmlContext->qmlContext();
778 if (!context)
779 return QV4::Encode::null();
780
781 // The lookup was populated for the id table of one component. The same code can also run
782 // in a different context, for example a script string in a context created by the user.
783 // In that case, we have to invalidate.
784 if (context->typeCompilationUnit().data()
785 != engine->currentStackFrame->v4Function->executableCompilationUnit()
786 || context->componentObjectIndex() != l->qmlContextIdObjectLookup.componentObjectIndex) {
787 l->call = Lookup::Call::ContextGetterGeneric;
788 return QQmlContextWrapper::resolveQmlContextPropertyLookupGetter(l, engine, base);
789 }
790
791 const int objectId = l->qmlContextIdObjectLookup.objectId;
792 QQmlEnginePrivate *qmlEngine = QQmlEnginePrivate::get(engine->qmlEngine());
793
794 if (qmlEngine->propertyCapture)
795 qmlEngine->propertyCapture->captureProperty(context->idValueBindings(objectId));
796
797 return QV4::QObjectWrapper::wrap(engine, context->idValue(objectId));
798}
799
800ReturnedValue QQmlContextWrapper::lookupIdObjectInParentContext(
801 Lookup *l, ExecutionEngine *engine, Value *base)
802{
803 return QQmlContextWrapper::resolveQmlContextPropertyLookupGetter(l, engine, base);
804}
805
806static ReturnedValue revertObjectPropertyLookup(Lookup *l, ExecutionEngine *engine, Value *base)
807{
808 l->qobjectLookup.propertyCache->release();
809 l->qobjectLookup.propertyCache = nullptr;
810 l->call = Lookup::Call::ContextGetterGeneric;
811 return QQmlContextWrapper::resolveQmlContextPropertyLookupGetter(l, engine, base);
812}
813
814static ReturnedValue revertObjectMethodLookup(Lookup *l, ExecutionEngine *engine, Value *base)
815{
816 l->qobjectMethodLookup.propertyCache->release();
817 l->qobjectMethodLookup.propertyCache = nullptr;
818 l->call = Lookup::Call::ContextGetterGeneric;
819 return QQmlContextWrapper::resolveQmlContextPropertyLookupGetter(l, engine, base);
820}
821
822// The object may be gone once it is being destroyed. Its name is not defined then, just like
823// when resolving the name anew.
824static ReturnedValue throwLostObjectReferenceError(Lookup *l, ExecutionEngine *engine)
825{
826 return engine->throwReferenceError(
827 engine->currentStackFrame->v4Function->compilationUnit->runtimeStrings[l->nameIndex]
828 ->toQString());
829}
830
831template<typename Call>
832ReturnedValue callWithScopeObject(Lookup *l, ExecutionEngine *engine, Value *base, Call c)
833{
834 Scope scope(engine);
835 Scoped<QmlContext> qmlContext(scope, engine->qmlContext());
836 if (!qmlContext)
837 return QV4::Encode::undefined();
838
839 QObject *scopeObject = qmlContext->qmlScope();
840 if (!scopeObject || QQmlData::wasDeleted(scopeObject))
841 return throwLostObjectReferenceError(l, engine);
842
843 ScopedValue obj(scope, QV4::QObjectWrapper::wrap(engine, scopeObject));
844
845 if (base)
846 *base = obj;
847
848 return c(obj);
849}
850
851ReturnedValue QQmlContextWrapper::lookupScopeObjectProperty(Lookup *l, ExecutionEngine *engine, Value *base)
852{
853 return callWithScopeObject(l, engine, base, [l, engine, base](const Value &obj) {
854 const QObjectWrapper::Flags flags = l->forCall
855 ? QObjectWrapper::NoFlag
856 : QObjectWrapper::AttachMethods;
857 return QObjectWrapper::lookupPropertyGetterImpl(l, engine, obj, flags, [l, engine, base]() {
858 return revertObjectPropertyLookup(l, engine, base);
859 });
860 });
861}
862
863ReturnedValue QQmlContextWrapper::lookupScopeObjectMethod(Lookup *l, ExecutionEngine *engine, Value *base)
864{
865 return callWithScopeObject(l, engine, base, [l, engine, base](const Value &obj) {
866 const QObjectWrapper::Flags flags = l->forCall
867 ? QObjectWrapper::NoFlag
868 : QObjectWrapper::AttachMethods;
869 return QObjectWrapper::lookupMethodGetterImpl(l, engine, obj, flags, [l, engine, base]() {
870 return revertObjectMethodLookup(l, engine, base);
871 });
872 });
873}
874
875template<typename Call>
876ReturnedValue callWithContextObject(Lookup *l, ExecutionEngine *engine, Value *base, Call c)
877{
878 Scope scope(engine);
879 Scoped<QmlContext> qmlContext(scope, engine->qmlContext());
880 if (!qmlContext)
881 return QV4::Encode::undefined();
882
883 QQmlRefPointer<QQmlContextData> context = qmlContext->qmlContext();
884 if (!context)
885 return QV4::Encode::undefined();
886
887 QObject *contextObject = context->contextObject();
888 if (!contextObject || QQmlData::wasDeleted(contextObject))
889 return throwLostObjectReferenceError(l, engine);
890
891 ScopedValue obj(scope, QV4::QObjectWrapper::wrap(engine, contextObject));
892
893 if (base)
894 *base = obj;
895
896 return c(obj);
897}
898
899ReturnedValue QQmlContextWrapper::lookupContextObjectProperty(
900 Lookup *l, ExecutionEngine *engine, Value *base)
901{
902 return callWithContextObject(l, engine, base, [l, engine, base](const Value &obj) {
903 const QObjectWrapper::Flags flags = l->forCall
904 ? QObjectWrapper::NoFlag
905 : QObjectWrapper::AttachMethods;
906 return QObjectWrapper::lookupPropertyGetterImpl(l, engine, obj, flags, [l, engine, base]() {
907 return revertObjectPropertyLookup(l, engine, base);
908 });
909 });
910}
911
912ReturnedValue QQmlContextWrapper::lookupContextObjectMethod(
913 Lookup *l, ExecutionEngine *engine, Value *base)
914{
915 return callWithContextObject(l, engine, base, [l, engine, base](const Value &obj) {
916 const QObjectWrapper::Flags flags = l->forCall
917 ? QObjectWrapper::NoFlag
918 : QObjectWrapper::AttachMethods;
919 return QObjectWrapper::lookupMethodGetterImpl(l, engine, obj, flags, [l, engine, base]() {
920 return revertObjectMethodLookup(l, engine, base);
921 });
922 });
923}
924
925ReturnedValue QQmlContextWrapper::lookupScopeFallbackProperty(Lookup *l, ExecutionEngine *engine, Value *base)
926{
927 return resolveQmlContextPropertyLookupGetter(l, engine, base);
928}
929
930ReturnedValue QQmlContextWrapper::lookupInGlobalObject(Lookup *l, ExecutionEngine *engine, Value *base)
931{
932 Q_UNUSED(base);
933 ReturnedValue result = Lookup::doCallGlobal(
934 l->qmlContextGlobalLookup.getterTrampoline, l, engine);
935 // In the unlikely event of mutation of the global object, update the trampoline.
936 if (l->call != Lookup::Call::ContextGetterInGlobalObject) {
937 l->qmlContextGlobalLookup.getterTrampoline = l->call;
938 l->call = Lookup::Call::ContextGetterInGlobalObject;
939 }
940 return result;
941}
942
943ReturnedValue QQmlContextWrapper::lookupInParentContextHierarchy(Lookup *l, ExecutionEngine *engine, Value *base)
944{
945 Scope scope(engine);
946 Scoped<QmlContext> qmlContext(scope, engine->qmlContext());
947 if (!qmlContext)
948 return QV4::Encode::undefined();
949
950 QQmlRefPointer<QQmlContextData> context = qmlContext->qmlContext();
951 if (!context)
952 return QV4::Encode::undefined();
953
954 QQmlRefPointer<QQmlContextData> expressionContext = context;
955
956 QQmlEnginePrivate *ep = QQmlEnginePrivate::get(engine->qmlEngine());
957
958 PropertyKey id =engine->identifierTable->asPropertyKey(engine->currentStackFrame->v4Function->compilationUnit->
959 runtimeStrings[l->nameIndex]);
960 ScopedString name(scope, id.asStringOrSymbol());
961
962 ScopedValue result(scope);
963
964 for (context = context->parent(); context; context = context->parent()) {
965 if (auto property = searchContextProperties(engine, context, name, nullptr, base, nullptr, nullptr, ep))
966 return *property;
967
968 // Search context object
969 if (QObject *contextObject = context->contextObject()) {
970 bool hasProp = false;
971 QV4::ScopedObject wrapper(scope, QV4::QObjectWrapper::wrap(engine, contextObject));
972 result = QV4::QObjectWrapper::getQmlProperty(
973 engine, context, wrapper->d(), contextObject, name, getQmlPropertyFlags(l),
974 &hasProp);
975 if (hasProp) {
976 if (base)
977 *base = wrapper;
978
979 return result->asReturnedValue();
980 }
981 }
982 }
983
984 bool hasProp = false;
985 result = engine->globalObject->get(name, &hasProp);
986 if (hasProp)
987 return result->asReturnedValue();
988
989 expressionContext->setUnresolvedNames(true);
990
991 return Encode::undefined();
992}
993
994ReturnedValue QQmlContextWrapper::lookupType(Lookup *l, ExecutionEngine *engine, Value *base)
995{
996 Q_UNUSED(base)
997
998 Scope scope(engine);
999 Scoped<QmlContext> qmlContext(scope, engine->qmlContext());
1000 if (!qmlContext)
1001 return QV4::Encode::undefined();
1002
1003 QObject *currentScopeObject = qmlContext->qmlScope();
1004 if (currentScopeObject && QQmlData::wasDeleted(currentScopeObject))
1005 return QV4::Encode::undefined();
1006
1007 Heap::Base *heapObject = l->qmlTypeLookup.qmlTypeWrapper;
1008 Heap::QQmlTypeWrapper *typeWrapper = static_cast<Heap::QQmlTypeWrapper *>(heapObject);
1009 QObject *lookupScopeObject = typeWrapper->object;
1010 if (lookupScopeObject == currentScopeObject)
1011 return Value::fromHeapObject(heapObject).asReturnedValue();
1012
1013 // The type wrapper is still valid. We can simply rebase it onto the new scope.
1014 // The type cannot have changed. The only thing that may have changed is the
1015 // base object of any attachment.
1016 Scoped<QQmlTypeWrapper> newWrapper(scope);
1017 switch (typeWrapper->kind()) {
1018 case Heap::QQmlTypeWrapper::Type:
1019 newWrapper = QQmlTypeWrapper::create(engine, currentScopeObject, typeWrapper->type(),
1020 typeWrapper->typeNameMode());
1021 break;
1022 case Heap::QQmlTypeWrapper::Namespace:
1023 newWrapper = QQmlTypeWrapper::create(
1024 engine, currentScopeObject, typeWrapper->n.typeNamespace,
1025 typeWrapper->n.importNamespace, typeWrapper->typeNameMode());
1026 break;
1027 }
1028 l->qmlTypeLookup.qmlTypeWrapper.set(engine, newWrapper->d());
1029 return newWrapper.asReturnedValue();
1030}
1031
1032void Heap::QmlContext::init(QV4::ExecutionContext *outerContext, QV4::QQmlContextWrapper *qml)
1033{
1034 Heap::ExecutionContext::init(Heap::ExecutionContext::Type_QmlContext);
1035 outer.set(internalClass->engine, outerContext->d());
1036
1037 this->activation.set(internalClass->engine, qml->d());
1038}
1039
1040Heap::QmlContext *QmlContext::create(
1041 ExecutionContext *parent, QQmlRefPointer<QQmlContextData> context,
1042 QObject *scopeObject)
1043{
1044 Scope scope(parent);
1045
1046 Scoped<QQmlContextWrapper> qml(
1047 scope, scope.engine->memoryManager->allocate<QQmlContextWrapper>(
1048 std::move(context), scopeObject));
1049 Heap::QmlContext *c = scope.engine->memoryManager->alloc<QmlContext>(parent, qml);
1050 Q_ASSERT(c->vtable() == staticVTable());
1051 return c;
1052}
1053
1054QT_END_NAMESPACE
Combined button and popup list for selecting options.
Definition qjsvalue.h:24
static OptionalReturnedValue searchImports(QV4::ExecutionEngine *v4, const QQmlRefPointer< QQmlContextData > &context, QObject *scopeObject, String *name, bool *hasProperty, Value *base, Lookup *lookup)
static ReturnedValue revertObjectMethodLookup(Lookup *l, ExecutionEngine *engine, Value *base)
static void setupSingletonLookup(QV4::ExecutionEngine *v4, Lookup *lookup, const QQmlType &type)
static QV4::QObjectWrapper::Flags getQmlPropertyFlags(const Lookup *l)
DEFINE_MANAGED_VTABLE(QmlContext)
static ReturnedValue revertObjectPropertyLookup(Lookup *l, ExecutionEngine *engine, Value *base)
static OptionalReturnedValue searchContextProperties(QV4::ExecutionEngine *v4, const QQmlRefPointer< QQmlContextData > &context, String *name, bool *hasProperty, Value *base, QV4::Lookup *lookup, QV4::Lookup *originalLookup, QQmlEnginePrivate *ep)
static OptionalReturnedValue searchScopeObject(QV4::ExecutionEngine *v4, const QQmlRefPointer< QQmlContextData > &context, QObject *scopeObject, String *name, bool *hasProperty, Value *base, Lookup *lookup)
static OptionalReturnedValue searchModule(const QQmlContextWrapper *resource, PropertyKey id, const Value *receiver, bool *hasProperty)
DEFINE_OBJECT_VTABLE(QQmlContextWrapper)
ReturnedValue callWithScopeObject(Lookup *l, ExecutionEngine *engine, Value *base, Call c)
static OptionalReturnedValue searchContextObject(QV4::ExecutionEngine *v4, const QQmlRefPointer< QQmlContextData > &context, String *name, bool *hasProperty, Value *base, Lookup *lookup, Lookup *originalLookup, Lookup::Call contextGetterCall)
static OptionalReturnedValue searchBoundComponentContexts(QV4::ExecutionEngine *v4, const QQmlRefPointer< QQmlContextData > &context, QQmlRefPointer< QQmlContextData > &outer, String *name, bool *hasProperty, Value *base, Lookup *originalLookup, QQmlEnginePrivate *ep)
ReturnedValue callWithContextObject(Lookup *l, ExecutionEngine *engine, Value *base, Call c)
static bool lostScopeCacheResolves(const QQmlPropertyCache *cache, QV4::ExecutionEngine *v4, String *name)
static bool cacheGlobalLookup(QV4::ExecutionEngine *v4, Lookup *lookup, ScopedValue *result)
static ReturnedValue throwLostObjectReferenceError(Lookup *l, ExecutionEngine *engine)
bool performLookup(ScopedValue *result, bool *hasProperty, const Lookup &lookup)