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
qv4engine.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 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 "qv4engine_p.h"
6
7#include <wtf/BumpPointerAllocator.h>
8#include <wtf/OSAllocator.h>
9#include <wtf/PageAllocation.h>
10
11#include <private/qjsvalue_p.h>
12#include <private/qqmlbuiltinfunctions_p.h>
13#include <private/qqmlengine_p.h>
14#include <private/qqmljsdiagnosticmessage_p.h>
15#include <private/qqmllist_p.h>
16#include <private/qqmllistwrapper_p.h>
17#include <private/qqmlscriptblob_p.h>
18#include <private/qqmlscriptdata_p.h>
19#include <private/qqmltypeloader_p.h>
20#include <private/qqmltypewrapper_p.h>
21#include <private/qqmlvaluetype_p.h>
22#include <private/qqmlvaluetypewrapper_p.h>
23#include <private/qv4argumentsobject_p.h>
24#include <private/qv4arraybuffer_p.h>
25#include <private/qv4arrayiterator_p.h>
26#include <private/qv4arrayobject_p.h>
27#include <private/qv4atomics_p.h>
28#include <private/qv4booleanobject_p.h>
29#include <private/qv4codegen_p.h>
30#include <private/qv4compileddata_p.h>
31#include <private/qv4dataview_p.h>
32#include <private/qv4dateobject_p.h>
33#include <private/qv4debugging_p.h>
34#include <private/qv4errorobject_p.h>
35#include <private/qv4executableallocator_p.h>
36#include <private/qv4function_p.h>
37#include <private/qv4functionobject_p.h>
38#include <private/qv4generatorobject_p.h>
39#include <private/qv4globalobject_p.h>
40#include <private/qv4identifiertable_p.h>
41#include <private/qv4iterator_p.h>
42#include <private/qv4jsonobject_p.h>
43#include <private/qv4mapiterator_p.h>
44#include <private/qv4mapobject_p.h>
45#include <private/qv4mathobject_p.h>
46#include <private/qv4memberdata_p.h>
47#include <private/qv4mm_p.h>
48#include <private/qv4module_p.h>
49#include <private/qv4numberobject_p.h>
50#include <private/qv4object_p.h>
51#include <private/qv4objectiterator_p.h>
52#include <private/qv4objectproto_p.h>
53#include <private/qv4profiling_p.h>
54#include <private/qv4promiseobject_p.h>
55#include <private/qv4proxy_p.h>
56#include <private/qv4qmetaobjectwrapper_p.h>
57#include <private/qv4qmlcontext_p.h>
58#include <private/qv4qobjectwrapper_p.h>
59#include <private/qv4reflect_p.h>
60#include <private/qv4regexp_p.h>
61#include <private/qv4regexpobject_p.h>
62#include <private/qv4runtime_p.h>
63#include <private/qv4sequenceobject_p.h>
64#include <private/qv4setiterator_p.h>
65#include <private/qv4setobject_p.h>
66#include <private/qv4sqlerrors_p.h>
67#include <private/qv4stackframe_p.h>
68#include <private/qv4stacklimits_p.h>
69#include <private/qv4stringiterator_p.h>
70#include <private/qv4stringobject_p.h>
71#include <private/qv4symbol_p.h>
72#include <private/qv4typedarray_p.h>
73#include <private/qv4urlobject_p.h>
74#include <private/qv4value_p.h>
75#include <private/qv4variantassociationobject_p.h>
76#include <private/qv4variantobject_p.h>
77
78#include <QtQml/qqmlfile.h>
79
80#include <QtCore/qdatetime.h>
81#include <QtCore/qdir.h>
82#include <QtCore/qfileinfo.h>
83#include <QtCore/qiterable.h>
84#include <QtCore/qloggingcategory.h>
85#include <QtCore/qmetatype.h>
86#include <QtCore/qmetasequence.h>
87#include <QtCore/qtextstream.h>
88#include <QtCore/qtimezone.h>
89
90#if QT_CONFIG(regularexpression)
91#include <QtCore/qregularexpression.h>
92#endif
93#if QT_CONFIG(qml_locale)
94#include <private/qqmllocale_p.h>
95#endif
96#if QT_CONFIG(qml_xml_http_request)
97#include <private/qv4domerrors_p.h>
98#include <private/qqmlxmlhttprequest_p.h>
99#endif
100#ifdef V4_USE_VALGRIND
101#include <valgrind/memcheck.h>
102#endif
103
105
106DEFINE_BOOL_CONFIG_OPTION(disableDiskCache, QML_DISABLE_DISK_CACHE);
108
109using namespace QV4;
110
111// While engineSerial is odd the statics haven't been initialized. The engine that receives ID 1
112// initializes the statics and sets engineSerial to 2 afterwards.
113// Each engine does engineSerial.fetchAndAddOrdered(2) on creation. Therefore engineSerial stays
114// odd while the statics are being initialized, and stays even afterwards.
115// Any further engines created while the statics are being initialized busy-wait until engineSerial
116// is even.
117Q_CONSTINIT static QBasicAtomicInt engineSerial = Q_BASIC_ATOMIC_INITIALIZER(1);
118Q_CONSTINIT static QBasicAtomicInt hasPreview = Q_BASIC_ATOMIC_INITIALIZER(0);
119int ExecutionEngine::s_maxCallDepth = -1;
120int ExecutionEngine::s_jitCallCountThreshold = 3;
121int ExecutionEngine::s_maxJSStackSize = 4 * 1024 * 1024;
122int ExecutionEngine::s_maxGCStackSize = 2 * 1024 * 1024;
123int ExecutionEngine::s_stackSizeSoftLimit = -1;
124
125ReturnedValue throwTypeError(const FunctionObject *b, const QV4::Value *, const QV4::Value *, int)
126{
127 return b->engine()->throwTypeError();
128}
129
130
131template <typename ReturnType>
132ReturnType convertJSValueToVariantType(const QJSValue &value)
133{
134 const QVariant variant = value.toVariant();
135 return variant.metaType() == QMetaType::fromType<QJSValue>()
136 ? ReturnType()
137 : variant.value<ReturnType>();
138}
139
144
145namespace {
146void createNewIteratorIfNonExisting(void **iterator) {
147 if (*iterator == nullptr)
148 *iterator = new JSArrayIterator;
149}
150}
151
153{
154 // set up some functions so that non-array QMetaSequence::Iterables do not crash
155 // but instead appear as an empty sequence
156
157 using namespace QtMetaContainerPrivate;
158 QMetaSequenceInterface iface;
159 iface.sizeFn = [](const void *) { return qsizetype(0); };
160 iface.valueAtIndexFn = [](const void *, qsizetype, void *) {};
161 iface.createIteratorFn = [](void *, QMetaSequenceInterface::Position) -> void * {
162 return nullptr;
163 };
164 iface.advanceIteratorFn = [](void *, qsizetype) {};
165 iface.compareIteratorFn = [](const void *, const void *) {
166 return true; /*all iterators are nullptr*/
167 };
168 iface.destroyIteratorFn = [](const void *) {};
169 iface.copyIteratorFn = [](void *, const void *) {};
170 iface.diffIteratorFn = [](const void *, const void *) { return qsizetype(0); };
171
172 iface.createConstIteratorFn = [](const void *, QMetaSequenceInterface::Position) -> void * {
173 return nullptr;
174 };
175 iface.advanceConstIteratorFn = [](void *, qsizetype) {};
176 iface.compareConstIteratorFn = [](const void *, const void *) {
177 return true; /*all iterators are nullptr*/
178 };
179 iface.destroyConstIteratorFn = [](const void *) {};
180 iface.copyConstIteratorFn = [](void *, const void *) {};
181 iface.diffConstIteratorFn = [](const void *, const void *) { return qsizetype(0); };
182 return iface;
183}
184
186{
187 using namespace QtMetaContainerPrivate;
188 QMetaSequenceInterface iface;
189 iface.valueMetaType = QtPrivate::qMetaTypeInterfaceForType<QVariant>();
190 iface.iteratorCapabilities = RandomAccessCapability | BiDirectionalCapability | ForwardCapability;
191 iface.addRemoveCapabilities = CanAddAtEnd;
192 iface.sizeFn = [](const void *p) -> qsizetype {
193 return static_cast<QJSValue const *>(p)->property(QString::fromLatin1("length")).toInt();
194 };
195
196 /* Lifetime management notes:
197 * valueAtIndexFn and valueAtIteratorFn return a pointer to a JSValue allocated via
198 * QMetaType::create Because we set QVariantConstructionFlags::ShouldDeleteVariantData,
199 * QMetaSequence::Iterable::at and QMetaSequence::Iterable::operator*() will free that memory
200 */
201
202 iface.valueAtIndexFn = [](const void *iterable, qsizetype index, void *dataPtr) -> void {
203 auto *data = static_cast<QVariant *>(dataPtr);
204 *data = static_cast<QJSValue const *>(iterable)->property(quint32(index)).toVariant();
205 };
206 iface.createIteratorFn = [](void *iterable, QMetaSequenceInterface::Position pos) {
207 void *iterator = nullptr;
208 createNewIteratorIfNonExisting(&iterator);
209 auto jsArrayIterator = static_cast<JSArrayIterator *>(iterator);
210 jsArrayIterator->index = 0;
211 jsArrayIterator->data = reinterpret_cast<QJSValue const*>(iterable);
212 if (pos == QMetaSequenceInterface::AtEnd) {
213 auto length = static_cast<QJSValue const *>(iterable)->property(
214 QString::fromLatin1("length")).toInt();
215 jsArrayIterator->index = quint32(length);
216 }
217 return iterator;
218 };
219 iface.createConstIteratorFn = [](const void *iterable, QMetaSequenceInterface::Position pos) {
220 void *iterator = nullptr;
221 createNewIteratorIfNonExisting(&iterator);
222 auto jsArrayIterator = static_cast<JSArrayIterator *>(iterator);
223 jsArrayIterator->index = 0;
224 jsArrayIterator->data = reinterpret_cast<QJSValue const*>(iterable);
225 if (pos == QMetaSequenceInterface::AtEnd) {
226 auto length = static_cast<QJSValue const *>(iterable)->property(
227 QString::fromLatin1("length")).toInt();
228 jsArrayIterator->index = quint32(length);
229 }
230 return iterator;
231 };
232 iface.advanceIteratorFn = [](void *iterator, qsizetype advanceBy) {
233 static_cast<JSArrayIterator *>(iterator)->index += quint32(advanceBy);
234 };
235 iface.advanceConstIteratorFn = [](void *iterator, qsizetype advanceBy) {
236 static_cast<JSArrayIterator *>(iterator)->index += quint32(advanceBy);
237 };
238 iface.valueAtIteratorFn = [](const void *iterator, void *dataPtr) -> void {
239 const auto *arrayIterator = static_cast<const JSArrayIterator *>(iterator);
240 const QJSValue *jsArray = arrayIterator->data;
241 auto *data = static_cast<QVariant *>(dataPtr);
242 *data = jsArray->property(arrayIterator->index).toVariant();
243 };
244 iface.valueAtConstIteratorFn = [](const void *iterator, void *dataPtr) -> void {
245 const auto *arrayIterator = static_cast<const JSArrayIterator *>(iterator);
246 const QJSValue *jsArray = arrayIterator->data;
247 auto *data = static_cast<QVariant *>(dataPtr);
248 *data = jsArray->property(arrayIterator->index).toVariant();
249 };
250 iface.destroyIteratorFn = [](const void *iterator) {
251 delete static_cast<const JSArrayIterator *>(iterator);
252 };
253 iface.destroyConstIteratorFn = [](const void *iterator) {
254 delete static_cast<const JSArrayIterator *>(iterator);
255 };
256 iface.compareIteratorFn = [](const void *p, const void *other) {
257 auto this_ = static_cast<const JSArrayIterator *>(p);
258 auto that_ = static_cast<const JSArrayIterator *>(other);
259 return this_->index == that_->index && this_->data == that_->data;
260 };
261 iface.compareConstIteratorFn = [](const void *p, const void *other) {
262 auto this_ = static_cast<const JSArrayIterator *>(p);
263 auto that_ = static_cast<const JSArrayIterator *>(other);
264 return this_->index == that_->index && this_->data == that_->data;
265 };
266 iface.copyIteratorFn = [](void *iterator, const void *otherIterator) {
267 auto *otherIter = (static_cast<JSArrayIterator const *>(otherIterator));
268 static_cast<JSArrayIterator *>(iterator)->index = otherIter->index;
269 static_cast<JSArrayIterator *>(iterator)->data = otherIter->data;
270 };
271 iface.copyConstIteratorFn = [](void *iterator, const void *otherIterator) {
272 auto *otherIter = (static_cast<JSArrayIterator const *>(otherIterator));
273 static_cast<JSArrayIterator *>(iterator)->index = otherIter->index;
274 static_cast<JSArrayIterator *>(iterator)->data = otherIter->data;
275 };
276 iface.diffIteratorFn = [](const void *iterator, const void *otherIterator) -> qsizetype {
277 const auto *self = static_cast<const JSArrayIterator *>(iterator);
278 const auto *other = static_cast<const JSArrayIterator *>(otherIterator);
279 return self->index - other->index;
280 };
281 iface.diffConstIteratorFn = [](const void *iterator, const void *otherIterator) -> qsizetype {
282 const auto *self = static_cast<const JSArrayIterator *>(iterator);
283 const auto *other = static_cast<const JSArrayIterator *>(otherIterator);
284 return self->index - other->index;
285 };
286 iface.addValueFn = [](void *iterable, const void *data, QMetaSequenceInterface::Position) {
287 auto *jsvalue = static_cast<QJSValue *>(iterable);
288 QV4::Scope scope(QJSValuePrivate::engine(jsvalue));
289 QV4::ScopedArrayObject a(scope, QJSValuePrivate::asManagedType<QV4::ArrayObject>(jsvalue));
290 QV4::ScopedValue v(scope, scope.engine->fromVariant(*static_cast<const QVariant *>(data)));
291 if (!a)
292 return;
293 int len = a->getLength();
294 a->setIndexed(len, v, QV4::Object::DoNotThrow);
295 };
296 return iface;
297}
298
299static QMetaSequence::Iterable jsvalueToSequence (const QJSValue& value) {
300 using namespace QtMetaTypePrivate;
301 using namespace QtMetaContainerPrivate;
302
303
304 if (!value.isArray()) {
305 static QMetaSequenceInterface emptySequence = emptySequenceInterface();
306 return QMetaSequence::Iterable(QMetaSequence(&emptySequence), nullptr);
307 }
308
309 static QMetaSequenceInterface sequence = sequenceInterface();
310 return QMetaSequence::Iterable(QMetaSequence(&sequence), &value);
311}
312
313void ExecutionEngine::initializeStaticMembers()
314{
315 bool ok = false;
316
317 const int envMaxJSStackSize = qEnvironmentVariableIntValue("QV4_JS_MAX_STACK_SIZE", &ok);
318 if (ok && envMaxJSStackSize > 0)
319 s_maxJSStackSize = envMaxJSStackSize;
320
321 const int envMaxGCStackSize = qEnvironmentVariableIntValue("QV4_GC_MAX_STACK_SIZE", &ok);
322 if (ok && envMaxGCStackSize > 0)
323 s_maxGCStackSize = envMaxGCStackSize;
324
325 const int envStackSizeSoftLimit = qEnvironmentVariableIntValue("QV4_STACK_SOFT_LIMIT", &ok);
326 if (ok && envStackSizeSoftLimit > -1)
327 s_stackSizeSoftLimit = envStackSizeSoftLimit;
328 else
329 s_stackSizeSoftLimit = -1;
330
331 if (qEnvironmentVariableIsSet("QV4_CRASH_ON_STACKOVERFLOW")) {
332 s_maxCallDepth = std::numeric_limits<qint32>::max();
333 } else {
334 ok = false;
335 s_maxCallDepth = qEnvironmentVariableIntValue("QV4_MAX_CALL_DEPTH", &ok);
336 if (!ok || s_maxCallDepth <= 0)
337 s_maxCallDepth = -1;
338 }
339
340 ok = false;
341 s_jitCallCountThreshold = qEnvironmentVariableIntValue("QV4_JIT_CALL_THRESHOLD", &ok);
342 if (!ok)
343 s_jitCallCountThreshold = 3;
344 if (qEnvironmentVariableIsSet("QV4_FORCE_INTERPRETER"))
345 s_jitCallCountThreshold = std::numeric_limits<int>::max();
346
347 qMetaTypeId<QJSValue>();
348 qMetaTypeId<QList<int> >();
349
350 if (!QMetaType::hasRegisteredConverterFunction<QJSValue, QVariantMap>())
351 QMetaType::registerConverter<QJSValue, QVariantMap>(convertJSValueToVariantType<QVariantMap>);
352 if (!QMetaType::hasRegisteredConverterFunction<QJSValue, QVariantHash>())
353 QMetaType::registerConverter<QJSValue, QVariantHash>(convertJSValueToVariantType<QVariantHash>);
354 if (!QMetaType::hasRegisteredConverterFunction<QJSValue, QVariantList>())
355 QMetaType::registerConverter<QJSValue, QVariantList>(convertJSValueToVariantType<QVariantList>);
356 if (!QMetaType::hasRegisteredConverterFunction<QJSValue, QStringList>())
357 QMetaType::registerConverter<QJSValue, QStringList>(convertJSValueToVariantType<QStringList>);
358 if (!QMetaType::hasRegisteredConverterFunction<QJSValue, QMetaSequence::Iterable>())
359 QMetaType::registerConverter<QJSValue, QMetaSequence::Iterable>(jsvalueToSequence);
360}
361
362/*!
363 \class QV4::ExecutionEngine
364 \inmodule QtQml
365 \internal
366*/
367ExecutionEngine::ExecutionEngine(QJSEngine *jsEngine)
368 : executableAllocator(new QV4::ExecutableAllocator)
369 , regExpAllocator(new QV4::ExecutableAllocator)
370 , bumperPointerAllocator(new WTF::BumpPointerAllocator)
371 , jsStack(new WTF::PageAllocation)
372 , gcStack(new WTF::PageAllocation)
373 , publicEngine(jsEngine)
374 , m_engineId(engineSerial.fetchAndAddOrdered(2))
375#if QT_CONFIG(qml_jit)
376 , m_canAllocateExecutableMemory(OSAllocator::canAllocateExecutableMemory())
377#endif
378{
379 if (m_engineId == 1) {
380 initializeStaticMembers();
381 engineSerial.storeRelease(2); // make it even
382 } else if (Q_UNLIKELY(m_engineId & 1)) {
383 // This should be rare. You usually don't create lots of engines at the same time.
384 while (engineSerial.loadAcquire() & 1) {
385 QThread::yieldCurrentThread();
386 }
387 }
388
389 if (s_maxCallDepth < 0)
390 setCppStackProperties();
391 else
392 callDepth = 0;
393
394 // We allocate guard pages around our stacks.
395 const size_t guardPages = 2 * WTF::pageSize();
396
397 memoryManager = new QV4::MemoryManager(this);
398 // we don't want to run the gc while the initial setup is not done; not even in aggressive mode
399 GCCriticalSection gcCriticalSection(this);
400 // reserve space for the JS stack
401 // we allow it to grow to a bit more than m_maxJSStackSize, as we can overshoot due to ScopedValues
402 // allocated outside of JIT'ed methods.
403 *jsStack = WTF::PageAllocation::allocate(
404 s_maxJSStackSize + 256*1024 + guardPages, WTF::OSAllocator::JSVMStackPages,
405 /* writable */ true, /* executable */ false, /* includesGuardPages */ true);
406 jsStackBase = (Value *)jsStack->base();
407#ifdef V4_USE_VALGRIND
408 VALGRIND_MAKE_MEM_UNDEFINED(jsStackBase, s_maxJSStackSize + 256*1024);
409#endif
410
411 jsStackTop = jsStackBase;
412
413 *gcStack = WTF::PageAllocation::allocate(
414 s_maxGCStackSize + guardPages, WTF::OSAllocator::JSVMStackPages,
415 /* writable */ true, /* executable */ false, /* includesGuardPages */ true);
416
417 exceptionValue = jsAlloca(1);
418 *exceptionValue = Encode::undefined();
419 globalObject = static_cast<Object *>(jsAlloca(1));
420 jsObjects = jsAlloca(NJSObjects);
421 typedArrayPrototype = static_cast<Object *>(jsAlloca(NTypedArrayTypes));
422 typedArrayCtors = static_cast<FunctionObject *>(jsAlloca(NTypedArrayTypes));
423 jsStrings = jsAlloca(NJSStrings);
424 jsSymbols = jsAlloca(NJSSymbols);
425
426 // set up stack limits
427 jsStackLimit = jsStackBase + s_maxJSStackSize/sizeof(Value);
428
429 identifierTable = new IdentifierTable(this);
430
431 memset(classes, 0, sizeof(classes));
432 classes[Class_Empty] = memoryManager->allocIC<InternalClass>();
433 classes[Class_Empty]->init(this);
434
435 classes[Class_MemberData] = classes[Class_Empty]->changeVTable(QV4::MemberData::staticVTable());
436 classes[Class_SimpleArrayData] = classes[Class_Empty]->changeVTable(QV4::SimpleArrayData::staticVTable());
437 classes[Class_SparseArrayData] = classes[Class_Empty]->changeVTable(QV4::SparseArrayData::staticVTable());
438 classes[Class_ExecutionContext] = classes[Class_Empty]->changeVTable(QV4::ExecutionContext::staticVTable());
439 classes[Class_CallContext] = classes[Class_Empty]->changeVTable(QV4::CallContext::staticVTable());
440 classes[Class_QmlContext] = classes[Class_Empty]->changeVTable(QV4::QmlContext::staticVTable());
441
442 Scope scope(this);
443 Scoped<InternalClass> ic(scope);
444 ic = classes[Class_Empty]->changeVTable(QV4::Object::staticVTable());
445 jsObjects[ObjectProto] = memoryManager->allocObject<ObjectPrototype>(ic->d());
446 classes[Class_Object] = ic->changePrototype(objectPrototype()->d());
447 classes[Class_QmlContextWrapper] = classes[Class_Object]->changeVTable(QV4::QQmlContextWrapper::staticVTable());
448
449 ic = newInternalClass(QV4::StringObject::staticVTable(), objectPrototype());
450 jsObjects[StringProto] = memoryManager->allocObject<StringPrototype>(ic->d(), /*init =*/ false);
451 classes[Class_String] = classes[Class_Empty]->changeVTable(QV4::String::staticVTable())->changePrototype(stringPrototype()->d());
452 Q_ASSERT(stringPrototype()->d() && classes[Class_String]->prototype);
453
454 jsObjects[SymbolProto] = memoryManager->allocate<SymbolPrototype>();
455 classes[Class_Symbol] = classes[EngineBase::Class_Empty]->changeVTable(QV4::Symbol::staticVTable())->changePrototype(symbolPrototype()->d());
456
457 jsStrings[String_Empty] = newIdentifier(QString());
458 jsStrings[String_undefined] = newIdentifier(QStringLiteral("undefined"));
459 jsStrings[String_null] = newIdentifier(QStringLiteral("null"));
460 jsStrings[String_true] = newIdentifier(QStringLiteral("true"));
461 jsStrings[String_false] = newIdentifier(QStringLiteral("false"));
462 jsStrings[String_boolean] = newIdentifier(QStringLiteral("boolean"));
463 jsStrings[String_number] = newIdentifier(QStringLiteral("number"));
464 jsStrings[String_string] = newIdentifier(QStringLiteral("string"));
465 jsStrings[String_default] = newIdentifier(QStringLiteral("default"));
466 jsStrings[String_symbol] = newIdentifier(QStringLiteral("symbol"));
467 jsStrings[String_object] = newIdentifier(QStringLiteral("object"));
468 jsStrings[String_function] = newIdentifier(QStringLiteral("function"));
469 jsStrings[String_length] = newIdentifier(QStringLiteral("length"));
470 jsStrings[String_prototype] = newIdentifier(QStringLiteral("prototype"));
471 jsStrings[String_constructor] = newIdentifier(QStringLiteral("constructor"));
472 jsStrings[String_arguments] = newIdentifier(QStringLiteral("arguments"));
473 jsStrings[String_caller] = newIdentifier(QStringLiteral("caller"));
474 jsStrings[String_callee] = newIdentifier(QStringLiteral("callee"));
475 jsStrings[String_this] = newIdentifier(QStringLiteral("this"));
476 jsStrings[String___proto__] = newIdentifier(QStringLiteral("__proto__"));
477 jsStrings[String_enumerable] = newIdentifier(QStringLiteral("enumerable"));
478 jsStrings[String_configurable] = newIdentifier(QStringLiteral("configurable"));
479 jsStrings[String_writable] = newIdentifier(QStringLiteral("writable"));
480 jsStrings[String_value] = newIdentifier(QStringLiteral("value"));
481 jsStrings[String_get] = newIdentifier(QStringLiteral("get"));
482 jsStrings[String_set] = newIdentifier(QStringLiteral("set"));
483 jsStrings[String_eval] = newIdentifier(QStringLiteral("eval"));
484 jsStrings[String_uintMax] = newIdentifier(QStringLiteral("4294967295"));
485 jsStrings[String_name] = newIdentifier(QStringLiteral("name"));
486 jsStrings[String_index] = newIdentifier(QStringLiteral("index"));
487 jsStrings[String_input] = newIdentifier(QStringLiteral("input"));
488 jsStrings[String_toString] = newIdentifier(QStringLiteral("toString"));
489 jsStrings[String_toLocaleString] = newIdentifier(QStringLiteral("toLocaleString"));
490 jsStrings[String_destroy] = newIdentifier(QStringLiteral("destroy"));
491 jsStrings[String_valueOf] = newIdentifier(QStringLiteral("valueOf"));
492 jsStrings[String_byteLength] = newIdentifier(QStringLiteral("byteLength"));
493 jsStrings[String_byteOffset] = newIdentifier(QStringLiteral("byteOffset"));
494 jsStrings[String_buffer] = newIdentifier(QStringLiteral("buffer"));
495 jsStrings[String_lastIndex] = newIdentifier(QStringLiteral("lastIndex"));
496 jsStrings[String_next] = newIdentifier(QStringLiteral("next"));
497 jsStrings[String_done] = newIdentifier(QStringLiteral("done"));
498 jsStrings[String_return] = newIdentifier(QStringLiteral("return"));
499 jsStrings[String_throw] = newIdentifier(QStringLiteral("throw"));
500 jsStrings[String_global] = newIdentifier(QStringLiteral("global"));
501 jsStrings[String_ignoreCase] = newIdentifier(QStringLiteral("ignoreCase"));
502 jsStrings[String_multiline] = newIdentifier(QStringLiteral("multiline"));
503 jsStrings[String_unicode] = newIdentifier(QStringLiteral("unicode"));
504 jsStrings[String_sticky] = newIdentifier(QStringLiteral("sticky"));
505 jsStrings[String_source] = newIdentifier(QStringLiteral("source"));
506 jsStrings[String_flags] = newIdentifier(QStringLiteral("flags"));
507
508 jsSymbols[Symbol_hasInstance] = Symbol::create(this, QStringLiteral("@Symbol.hasInstance"));
509 jsSymbols[Symbol_isConcatSpreadable] = Symbol::create(this, QStringLiteral("@Symbol.isConcatSpreadable"));
510 jsSymbols[Symbol_iterator] = Symbol::create(this, QStringLiteral("@Symbol.iterator"));
511 jsSymbols[Symbol_match] = Symbol::create(this, QStringLiteral("@Symbol.match"));
512 jsSymbols[Symbol_replace] = Symbol::create(this, QStringLiteral("@Symbol.replace"));
513 jsSymbols[Symbol_search] = Symbol::create(this, QStringLiteral("@Symbol.search"));
514 jsSymbols[Symbol_species] = Symbol::create(this, QStringLiteral("@Symbol.species"));
515 jsSymbols[Symbol_split] = Symbol::create(this, QStringLiteral("@Symbol.split"));
516 jsSymbols[Symbol_toPrimitive] = Symbol::create(this, QStringLiteral("@Symbol.toPrimitive"));
517 jsSymbols[Symbol_toStringTag] = Symbol::create(this, QStringLiteral("@Symbol.toStringTag"));
518 jsSymbols[Symbol_unscopables] = Symbol::create(this, QStringLiteral("@Symbol.unscopables"));
519 jsSymbols[Symbol_revokableProxy] = Symbol::create(this, QStringLiteral("@Proxy.revokableProxy"));
520
521 ic = newInternalClass(ArrayPrototype::staticVTable(), objectPrototype());
522 Q_ASSERT(ic->d()->prototype);
523 ic = ic->addMember(id_length()->propertyKey(), Attr_NotConfigurable|Attr_NotEnumerable);
524 Q_ASSERT(ic->d()->prototype);
525 jsObjects[ArrayProto] = memoryManager->allocObject<ArrayPrototype>(ic->d());
526 classes[Class_ArrayObject] = ic->changePrototype(arrayPrototype()->d());
527 jsObjects[PropertyListProto] = memoryManager->allocate<PropertyListPrototype>();
528
529 Scoped<InternalClass> argsClass(scope);
530 argsClass = newInternalClass(ArgumentsObject::staticVTable(), objectPrototype());
531 argsClass = argsClass->addMember(id_length()->propertyKey(), Attr_NotEnumerable);
532 argsClass = argsClass->addMember(symbol_iterator()->propertyKey(), Attr_Data|Attr_NotEnumerable);
533 classes[Class_ArgumentsObject] = argsClass->addMember(id_callee()->propertyKey(), Attr_Data|Attr_NotEnumerable);
534 argsClass = newInternalClass(StrictArgumentsObject::staticVTable(), objectPrototype());
535 argsClass = argsClass->addMember(id_length()->propertyKey(), Attr_NotEnumerable);
536 argsClass = argsClass->addMember(symbol_iterator()->propertyKey(), Attr_Data|Attr_NotEnumerable);
537 classes[Class_StrictArgumentsObject] = argsClass->addMember(id_callee()->propertyKey(), Attr_Accessor|Attr_NotConfigurable|Attr_NotEnumerable);
538
539 *static_cast<Value *>(globalObject) = newObject();
540 Q_ASSERT(globalObject->d()->vtable());
541 initRootContext();
542
543 ic = newInternalClass(QV4::StringObject::staticVTable(), objectPrototype());
544 ic = ic->addMember(id_length()->propertyKey(), Attr_ReadOnly);
545 classes[Class_StringObject] = ic->changePrototype(stringPrototype()->d());
546 Q_ASSERT(classes[Class_StringObject]->verifyIndex(id_length()->propertyKey(), Heap::StringObject::LengthPropertyIndex));
547
548 classes[Class_SymbolObject] = newInternalClass(QV4::SymbolObject::staticVTable(), symbolPrototype());
549
550 jsObjects[NumberProto] = memoryManager->allocate<NumberPrototype>();
551 jsObjects[BooleanProto] = memoryManager->allocate<BooleanPrototype>();
552 jsObjects[DateProto] = memoryManager->allocate<DatePrototype>();
553
554#if defined(QT_NO_DEBUG) && !defined(QT_FORCE_ASSERTS)
555 InternalClassEntry *index = nullptr;
556#else
557 InternalClassEntry _index;
558 auto *index = &_index;
559#endif
560 ic = newInternalClass(QV4::FunctionPrototype::staticVTable(), objectPrototype());
561 auto addProtoHasInstance = [&] {
562 // Add an invalid prototype slot, so that all function objects have the same layout
563 // This helps speed up instanceof operations and other things where we need to query
564 // prototype property (as we always know it's location)
565 ic = ic->addMember(id_prototype()->propertyKey(), Attr_Invalid, index);
566 Q_ASSERT(index->index == Heap::FunctionObject::Index_Prototype);
567 // add an invalid @hasInstance slot, so that we can quickly track whether the
568 // hasInstance method has been reimplemented. This is required for a fast
569 // instanceof implementation
570 ic = ic->addMember(symbol_hasInstance()->propertyKey(), Attr_Invalid, index);
571 Q_ASSERT(index->index == Heap::FunctionObject::Index_HasInstance);
572 };
573 addProtoHasInstance();
574 jsObjects[FunctionProto] = memoryManager->allocObject<FunctionPrototype>(ic->d());
575 ic = newInternalClass(FunctionObject::staticVTable(), functionPrototype());
576 addProtoHasInstance();
577 classes[Class_FunctionObject] = ic->d();
578 ic = ic->addMember(id_name()->propertyKey(), Attr_ReadOnly, index);
579 Q_ASSERT(index->index == Heap::ArrowFunction::Index_Name);
580 ic = ic->addMember(id_length()->propertyKey(), Attr_ReadOnly_ButConfigurable, index);
581 Q_ASSERT(index->index == Heap::ArrowFunction::Index_Length);
582 classes[Class_ArrowFunction] = ic->changeVTable(ArrowFunction::staticVTable());
583 ic = ic->changeVTable(MemberFunction::staticVTable());
584 classes[Class_MemberFunction] = ic->d();
585 ic = ic->changeVTable(GeneratorFunction::staticVTable());
586 classes[Class_GeneratorFunction] = ic->d();
587 ic = ic->changeVTable(MemberGeneratorFunction::staticVTable());
588 classes[Class_MemberGeneratorFunction] = ic->d();
589
590 ic = ic->changeMember(id_prototype()->propertyKey(), Attr_NotConfigurable|Attr_NotEnumerable);
591 ic = ic->changeVTable(ScriptFunction::staticVTable());
592 classes[Class_ScriptFunction] = ic->d();
593 ic = ic->changeVTable(ConstructorFunction::staticVTable());
594 classes[Class_ConstructorFunction] = ic->d();
595
596 classes[Class_ObjectProto] = classes[Class_Object]->addMember(id_constructor()->propertyKey(), Attr_NotEnumerable, index);
597 Q_ASSERT(index->index == Heap::FunctionObject::Index_ProtoConstructor);
598
599 jsObjects[GeneratorProto] = memoryManager->allocObject<GeneratorPrototype>(classes[Class_Object]);
600 classes[Class_GeneratorObject] = newInternalClass(QV4::GeneratorObject::staticVTable(), generatorPrototype());
601
602 ScopedString str(scope);
603 classes[Class_RegExp] = classes[Class_Empty]->changeVTable(QV4::RegExp::staticVTable());
604 ic = newInternalClass(QV4::RegExpObject::staticVTable(), objectPrototype());
605 ic = ic->addMember(id_lastIndex()->propertyKey(), Attr_NotEnumerable|Attr_NotConfigurable, index);
606 Q_ASSERT(index->index == RegExpObject::Index_LastIndex);
607 jsObjects[RegExpProto] = memoryManager->allocObject<RegExpPrototype>(classes[Class_Object]);
608 classes[Class_RegExpObject] = ic->changePrototype(regExpPrototype()->d());
609
610 ic = classes[Class_ArrayObject]->addMember(id_index()->propertyKey(), Attr_Data, index);
611 Q_ASSERT(index->index == RegExpObject::Index_ArrayIndex);
612 classes[Class_RegExpExecArray] = ic->addMember(id_input()->propertyKey(), Attr_Data, index);
613 Q_ASSERT(index->index == RegExpObject::Index_ArrayInput);
614
615 ic = newInternalClass(ErrorObject::staticVTable(), nullptr);
616 ic = ic->addMember((str = newIdentifier(QStringLiteral("stack")))->propertyKey(), Attr_Accessor|Attr_NotConfigurable|Attr_NotEnumerable, index);
617 Q_ASSERT(index->index == ErrorObject::Index_Stack);
618 Q_ASSERT(index->setterIndex == ErrorObject::Index_StackSetter);
619 ic = ic->addMember((str = newIdentifier(QStringLiteral("fileName")))->propertyKey(), Attr_Data|Attr_NotEnumerable, index);
620 Q_ASSERT(index->index == ErrorObject::Index_FileName);
621 ic = ic->addMember((str = newIdentifier(QStringLiteral("lineNumber")))->propertyKey(), Attr_Data|Attr_NotEnumerable, index);
622 classes[Class_ErrorObject] = ic->d();
623 Q_ASSERT(index->index == ErrorObject::Index_LineNumber);
624 classes[Class_ErrorObjectWithMessage] = ic->addMember((str = newIdentifier(QStringLiteral("message")))->propertyKey(), Attr_Data|Attr_NotEnumerable, index);
625 Q_ASSERT(index->index == ErrorObject::Index_Message);
626 ic = newInternalClass(Object::staticVTable(), objectPrototype());
627 ic = ic->addMember(id_constructor()->propertyKey(), Attr_Data|Attr_NotEnumerable, index);
628 Q_ASSERT(index->index == ErrorPrototype::Index_Constructor);
629 ic = ic->addMember((str = newIdentifier(QStringLiteral("message")))->propertyKey(), Attr_Data|Attr_NotEnumerable, index);
630 Q_ASSERT(index->index == ErrorPrototype::Index_Message);
631 classes[Class_ErrorProto] = ic->addMember(id_name()->propertyKey(), Attr_Data|Attr_NotEnumerable, index);
632 Q_ASSERT(index->index == ErrorPrototype::Index_Name);
633
634 classes[Class_ProxyObject] = classes[Class_Empty]->changeVTable(ProxyObject::staticVTable());
635 classes[Class_ProxyFunctionObject] = classes[Class_Empty]->changeVTable(ProxyFunctionObject::staticVTable());
636
637 jsObjects[GetStack_Function] = FunctionObject::createBuiltinFunction(this, str = newIdentifier(QStringLiteral("stack")), ErrorObject::method_get_stack, 0);
638
639 jsObjects[ErrorProto] = memoryManager->allocObject<ErrorPrototype>(classes[Class_ErrorProto]);
640 ic = classes[Class_ErrorProto]->changePrototype(errorPrototype()->d());
641 jsObjects[EvalErrorProto] = memoryManager->allocObject<EvalErrorPrototype>(ic->d());
642 jsObjects[RangeErrorProto] = memoryManager->allocObject<RangeErrorPrototype>(ic->d());
643 jsObjects[ReferenceErrorProto] = memoryManager->allocObject<ReferenceErrorPrototype>(ic->d());
644 jsObjects[SyntaxErrorProto] = memoryManager->allocObject<SyntaxErrorPrototype>(ic->d());
645 jsObjects[TypeErrorProto] = memoryManager->allocObject<TypeErrorPrototype>(ic->d());
646 jsObjects[URIErrorProto] = memoryManager->allocObject<URIErrorPrototype>(ic->d());
647
648 jsObjects[VariantProto] = memoryManager->allocate<VariantPrototype>();
649 Q_ASSERT(variantPrototype()->getPrototypeOf() == objectPrototype()->d());
650
651 jsObjects[VariantAssociationProto] = memoryManager->allocate<VariantAssociationPrototype>();
652 Q_ASSERT(variantAssociationPrototype()->getPrototypeOf() == objectPrototype()->d());
653
654 ic = newInternalClass(SequencePrototype::staticVTable(), SequencePrototype::defaultPrototype(this));
655 jsObjects[SequenceProto] = ScopedValue(scope, memoryManager->allocObject<SequencePrototype>(ic->d()));
656
657 jsObjects[Object_Ctor] = memoryManager->allocate<ObjectCtor>(this);
658 jsObjects[String_Ctor] = memoryManager->allocate<StringCtor>(this);
659 jsObjects[Symbol_Ctor] = memoryManager->allocate<SymbolCtor>(this);
660 jsObjects[Number_Ctor] = memoryManager->allocate<NumberCtor>(this);
661 jsObjects[Boolean_Ctor] = memoryManager->allocate<BooleanCtor>(this);
662 jsObjects[Array_Ctor] = memoryManager->allocate<ArrayCtor>(this);
663 jsObjects[Function_Ctor] = memoryManager->allocate<FunctionCtor>(this);
664 jsObjects[GeneratorFunction_Ctor] = memoryManager->allocate<GeneratorFunctionCtor>(this);
665 jsObjects[Date_Ctor] = memoryManager->allocate<DateCtor>(this);
666 jsObjects[RegExp_Ctor] = memoryManager->allocate<RegExpCtor>(this);
667 jsObjects[Error_Ctor] = memoryManager->allocate<ErrorCtor>(this);
668 jsObjects[EvalError_Ctor] = memoryManager->allocate<EvalErrorCtor>(this);
669 jsObjects[RangeError_Ctor] = memoryManager->allocate<RangeErrorCtor>(this);
670 jsObjects[ReferenceError_Ctor] = memoryManager->allocate<ReferenceErrorCtor>(this);
671 jsObjects[SyntaxError_Ctor] = memoryManager->allocate<SyntaxErrorCtor>(this);
672 jsObjects[TypeError_Ctor] = memoryManager->allocate<TypeErrorCtor>(this);
673 jsObjects[URIError_Ctor] = memoryManager->allocate<URIErrorCtor>(this);
674 jsObjects[IteratorProto] = memoryManager->allocate<IteratorPrototype>();
675
676 ic = newInternalClass(ForInIteratorPrototype::staticVTable(), iteratorPrototype());
677 jsObjects[ForInIteratorProto] = memoryManager->allocObject<ForInIteratorPrototype>(ic);
678 ic = newInternalClass(SetIteratorPrototype::staticVTable(), iteratorPrototype());
679 jsObjects[MapIteratorProto] = memoryManager->allocObject<MapIteratorPrototype>(ic);
680 ic = newInternalClass(SetIteratorPrototype::staticVTable(), iteratorPrototype());
681 jsObjects[SetIteratorProto] = memoryManager->allocObject<SetIteratorPrototype>(ic);
682 ic = newInternalClass(ArrayIteratorPrototype::staticVTable(), iteratorPrototype());
683 jsObjects[ArrayIteratorProto] = memoryManager->allocObject<ArrayIteratorPrototype>(ic);
684 ic = newInternalClass(StringIteratorPrototype::staticVTable(), iteratorPrototype());
685 jsObjects[StringIteratorProto] = memoryManager->allocObject<StringIteratorPrototype>(ic);
686
687 //
688 // url
689 //
690
691 jsObjects[Url_Ctor] = memoryManager->allocate<UrlCtor>(this);
692 jsObjects[UrlProto] = memoryManager->allocate<UrlPrototype>();
693 jsObjects[UrlSearchParams_Ctor] = memoryManager->allocate<UrlSearchParamsCtor>(this);
694 jsObjects[UrlSearchParamsProto] = memoryManager->allocate<UrlSearchParamsPrototype>();
695
696 str = newString(QStringLiteral("get [Symbol.species]"));
697 jsObjects[GetSymbolSpecies] = FunctionObject::createBuiltinFunction(this, str, ArrayPrototype::method_get_species, 0);
698
699 static_cast<ObjectPrototype *>(objectPrototype())->init(this, objectCtor());
700 static_cast<StringPrototype *>(stringPrototype())->init(this, stringCtor());
701 static_cast<SymbolPrototype *>(symbolPrototype())->init(this, symbolCtor());
702 static_cast<NumberPrototype *>(numberPrototype())->init(this, numberCtor());
703 static_cast<BooleanPrototype *>(booleanPrototype())->init(this, booleanCtor());
704 static_cast<ArrayPrototype *>(arrayPrototype())->init(this, arrayCtor());
705 static_cast<PropertyListPrototype *>(propertyListPrototype())->init();
706 static_cast<DatePrototype *>(datePrototype())->init(this, dateCtor());
707 static_cast<FunctionPrototype *>(functionPrototype())->init(this, functionCtor());
708 static_cast<GeneratorPrototype *>(generatorPrototype())->init(this, generatorFunctionCtor());
709 static_cast<RegExpPrototype *>(regExpPrototype())->init(this, regExpCtor());
710 static_cast<ErrorPrototype *>(errorPrototype())->init(this, errorCtor());
711 static_cast<EvalErrorPrototype *>(evalErrorPrototype())->init(this, evalErrorCtor());
712 static_cast<RangeErrorPrototype *>(rangeErrorPrototype())->init(this, rangeErrorCtor());
713 static_cast<ReferenceErrorPrototype *>(referenceErrorPrototype())->init(this, referenceErrorCtor());
714 static_cast<SyntaxErrorPrototype *>(syntaxErrorPrototype())->init(this, syntaxErrorCtor());
715 static_cast<TypeErrorPrototype *>(typeErrorPrototype())->init(this, typeErrorCtor());
716 static_cast<URIErrorPrototype *>(uRIErrorPrototype())->init(this, uRIErrorCtor());
717 static_cast<UrlPrototype *>(urlPrototype())->init(this, urlCtor());
718 static_cast<UrlSearchParamsPrototype *>(urlSearchParamsPrototype())->init(this, urlSearchParamsCtor());
719
720 static_cast<IteratorPrototype *>(iteratorPrototype())->init(this);
721 static_cast<ForInIteratorPrototype *>(forInIteratorPrototype())->init(this);
722 static_cast<MapIteratorPrototype *>(mapIteratorPrototype())->init(this);
723 static_cast<SetIteratorPrototype *>(setIteratorPrototype())->init(this);
724 static_cast<ArrayIteratorPrototype *>(arrayIteratorPrototype())->init(this);
725 static_cast<StringIteratorPrototype *>(stringIteratorPrototype())->init(this);
726
727 static_cast<VariantPrototype *>(variantPrototype())->init();
728
729 sequencePrototype()->cast<SequencePrototype>()->init();
730
731 jsObjects[WeakMap_Ctor] = memoryManager->allocate<WeakMapCtor>(this);
732 jsObjects[WeakMapProto] = memoryManager->allocate<WeakMapPrototype>();
733 static_cast<WeakMapPrototype *>(weakMapPrototype())->init(this, weakMapCtor());
734
735 jsObjects[Map_Ctor] = memoryManager->allocate<MapCtor>(this);
736 jsObjects[MapProto] = memoryManager->allocate<MapPrototype>();
737 static_cast<MapPrototype *>(mapPrototype())->init(this, mapCtor());
738
739 jsObjects[WeakSet_Ctor] = memoryManager->allocate<WeakSetCtor>(this);
740 jsObjects[WeakSetProto] = memoryManager->allocate<WeakSetPrototype>();
741 static_cast<WeakSetPrototype *>(weakSetPrototype())->init(this, weakSetCtor());
742
743 jsObjects[Set_Ctor] = memoryManager->allocate<SetCtor>(this);
744 jsObjects[SetProto] = memoryManager->allocate<SetPrototype>();
745 static_cast<SetPrototype *>(setPrototype())->init(this, setCtor());
746
747 //
748 // promises
749 //
750
751 jsObjects[Promise_Ctor] = memoryManager->allocate<PromiseCtor>(this);
752 jsObjects[PromiseProto] = memoryManager->allocate<PromisePrototype>();
753 static_cast<PromisePrototype *>(promisePrototype())->init(this, promiseCtor());
754
755 // typed arrays
756
757 jsObjects[SharedArrayBuffer_Ctor] = memoryManager->allocate<SharedArrayBufferCtor>(this);
758 jsObjects[SharedArrayBufferProto] = memoryManager->allocate<SharedArrayBufferPrototype>();
759 static_cast<SharedArrayBufferPrototype *>(sharedArrayBufferPrototype())->init(this, sharedArrayBufferCtor());
760
761 jsObjects[ArrayBuffer_Ctor] = memoryManager->allocate<ArrayBufferCtor>(this);
762 jsObjects[ArrayBufferProto] = memoryManager->allocate<ArrayBufferPrototype>();
763 static_cast<ArrayBufferPrototype *>(arrayBufferPrototype())->init(this, arrayBufferCtor());
764
765 jsObjects[DataView_Ctor] = memoryManager->allocate<DataViewCtor>(this);
766 jsObjects[DataViewProto] = memoryManager->allocate<DataViewPrototype>();
767 static_cast<DataViewPrototype *>(dataViewPrototype())->init(this, dataViewCtor());
768 jsObjects[ValueTypeProto] = (Heap::Base *) nullptr;
769 jsObjects[SignalHandlerProto] = (Heap::Base *) nullptr;
770 jsObjects[TypeWrapperProto] = (Heap::Base *) nullptr;
771
772 jsObjects[IntrinsicTypedArray_Ctor] = memoryManager->allocate<IntrinsicTypedArrayCtor>(this);
773 jsObjects[IntrinsicTypedArrayProto] = memoryManager->allocate<IntrinsicTypedArrayPrototype>();
774 static_cast<IntrinsicTypedArrayPrototype *>(intrinsicTypedArrayPrototype())
775 ->init(this, static_cast<IntrinsicTypedArrayCtor *>(intrinsicTypedArrayCtor()));
776
777 for (int i = 0; i < NTypedArrayTypes; ++i) {
778 static_cast<Value &>(typedArrayCtors[i]) = memoryManager->allocate<TypedArrayCtor>(this, Heap::TypedArray::Type(i));
779 static_cast<Value &>(typedArrayPrototype[i]) = memoryManager->allocate<TypedArrayPrototype>(Heap::TypedArray::Type(i));
780 typedArrayPrototype[i].as<TypedArrayPrototype>()->init(this, static_cast<TypedArrayCtor *>(typedArrayCtors[i].as<Object>()));
781 }
782
783 //
784 // set up the global object
785 //
786 rootContext()->d()->activation.set(scope.engine, globalObject->d());
787 Q_ASSERT(globalObject->d()->vtable());
788
789 globalObject->defineDefaultProperty(QStringLiteral("Object"), *objectCtor());
790 globalObject->defineDefaultProperty(QStringLiteral("String"), *stringCtor());
791 globalObject->defineDefaultProperty(QStringLiteral("Symbol"), *symbolCtor());
792 FunctionObject *numberObject = numberCtor();
793 globalObject->defineDefaultProperty(QStringLiteral("Number"), *numberObject);
794 globalObject->defineDefaultProperty(QStringLiteral("Boolean"), *booleanCtor());
795 globalObject->defineDefaultProperty(QStringLiteral("Array"), *arrayCtor());
796 globalObject->defineDefaultProperty(QStringLiteral("Function"), *functionCtor());
797 globalObject->defineDefaultProperty(QStringLiteral("Date"), *dateCtor());
798 globalObject->defineDefaultProperty(QStringLiteral("RegExp"), *regExpCtor());
799 globalObject->defineDefaultProperty(QStringLiteral("Error"), *errorCtor());
800 globalObject->defineDefaultProperty(QStringLiteral("EvalError"), *evalErrorCtor());
801 globalObject->defineDefaultProperty(QStringLiteral("RangeError"), *rangeErrorCtor());
802 globalObject->defineDefaultProperty(QStringLiteral("ReferenceError"), *referenceErrorCtor());
803 globalObject->defineDefaultProperty(QStringLiteral("SyntaxError"), *syntaxErrorCtor());
804 globalObject->defineDefaultProperty(QStringLiteral("TypeError"), *typeErrorCtor());
805 globalObject->defineDefaultProperty(QStringLiteral("URIError"), *uRIErrorCtor());
806 globalObject->defineDefaultProperty(QStringLiteral("Promise"), *promiseCtor());
807 globalObject->defineDefaultProperty(QStringLiteral("URL"), *urlCtor());
808 globalObject->defineDefaultProperty(QStringLiteral("URLSearchParams"), *urlSearchParamsCtor());
809
810 globalObject->defineDefaultProperty(QStringLiteral("SharedArrayBuffer"), *sharedArrayBufferCtor());
811 globalObject->defineDefaultProperty(QStringLiteral("ArrayBuffer"), *arrayBufferCtor());
812 globalObject->defineDefaultProperty(QStringLiteral("DataView"), *dataViewCtor());
813 globalObject->defineDefaultProperty(QStringLiteral("WeakSet"), *weakSetCtor());
814 globalObject->defineDefaultProperty(QStringLiteral("Set"), *setCtor());
815 globalObject->defineDefaultProperty(QStringLiteral("WeakMap"), *weakMapCtor());
816 globalObject->defineDefaultProperty(QStringLiteral("Map"), *mapCtor());
817
818 for (int i = 0; i < NTypedArrayTypes; ++i)
819 globalObject->defineDefaultProperty((str = typedArrayCtors[i].as<FunctionObject>()->name()), typedArrayCtors[i]);
820 ScopedObject o(scope);
821 globalObject->defineDefaultProperty(QStringLiteral("Atomics"), (o = memoryManager->allocate<Atomics>()));
822 globalObject->defineDefaultProperty(QStringLiteral("Math"), (o = memoryManager->allocate<MathObject>()));
823 globalObject->defineDefaultProperty(QStringLiteral("JSON"), (o = memoryManager->allocate<JsonObject>()));
824 globalObject->defineDefaultProperty(QStringLiteral("Reflect"), (o = memoryManager->allocate<Reflect>()));
825 globalObject->defineDefaultProperty(QStringLiteral("Proxy"), (o = memoryManager->allocate<Proxy>(this)));
826
827 globalObject->defineReadonlyProperty(QStringLiteral("undefined"), Value::undefinedValue());
828 globalObject->defineReadonlyProperty(QStringLiteral("NaN"), Value::fromDouble(std::numeric_limits<double>::quiet_NaN()));
829 globalObject->defineReadonlyProperty(QStringLiteral("Infinity"), Value::fromDouble(Q_INFINITY));
830
831
832 jsObjects[Eval_Function] = memoryManager->allocate<EvalFunction>(this);
833 globalObject->defineDefaultProperty(QStringLiteral("eval"), *evalFunction());
834
835 // ES6: 20.1.2.12 & 20.1.2.13:
836 // parseInt and parseFloat must be the same FunctionObject on the global &
837 // Number object.
838 {
839 QString piString(QStringLiteral("parseInt"));
840 QString pfString(QStringLiteral("parseFloat"));
841 Scope scope(this);
842 ScopedString pi(scope, newIdentifier(piString));
843 ScopedString pf(scope, newIdentifier(pfString));
844 ScopedFunctionObject parseIntFn(scope, FunctionObject::createBuiltinFunction(this, pi, GlobalFunctions::method_parseInt, 2));
845 ScopedFunctionObject parseFloatFn(scope, FunctionObject::createBuiltinFunction(this, pf, GlobalFunctions::method_parseFloat, 1));
846 globalObject->defineDefaultProperty(piString, parseIntFn);
847 globalObject->defineDefaultProperty(pfString, parseFloatFn);
848 numberObject->defineDefaultProperty(piString, parseIntFn);
849 numberObject->defineDefaultProperty(pfString, parseFloatFn);
850 }
851
852 globalObject->defineDefaultProperty(QStringLiteral("isNaN"), GlobalFunctions::method_isNaN, 1);
853 globalObject->defineDefaultProperty(QStringLiteral("isFinite"), GlobalFunctions::method_isFinite, 1);
854 globalObject->defineDefaultProperty(QStringLiteral("decodeURI"), GlobalFunctions::method_decodeURI, 1);
855 globalObject->defineDefaultProperty(QStringLiteral("decodeURIComponent"), GlobalFunctions::method_decodeURIComponent, 1);
856 globalObject->defineDefaultProperty(QStringLiteral("encodeURI"), GlobalFunctions::method_encodeURI, 1);
857 globalObject->defineDefaultProperty(QStringLiteral("encodeURIComponent"), GlobalFunctions::method_encodeURIComponent, 1);
858 globalObject->defineDefaultProperty(QStringLiteral("escape"), GlobalFunctions::method_escape, 1);
859 globalObject->defineDefaultProperty(QStringLiteral("unescape"), GlobalFunctions::method_unescape, 1);
860
861 ScopedFunctionObject t(
862 scope,
863 memoryManager->allocate<DynamicFunctionObject>(this, nullptr, ::throwTypeError));
864 t->defineReadonlyProperty(id_length(), Value::fromInt32(0));
865 t->setInternalClass(t->internalClass()->cryopreserved());
866 jsObjects[ThrowerObject] = t;
867
868 ScopedProperty pd(scope);
869 pd->value = thrower();
870 pd->set = thrower();
871 functionPrototype()->insertMember(id_caller(), pd, Attr_Accessor|Attr_ReadOnly_ButConfigurable);
872 functionPrototype()->insertMember(id_arguments(), pd, Attr_Accessor|Attr_ReadOnly_ButConfigurable);
873
874 QV4::QObjectWrapper::initializeBindings(this);
875
876 m_delayedCallQueue.init(this);
877 isInitialized = true;
878}
879
880ExecutionEngine::~ExecutionEngine()
881{
882 // The public engine destructors set this before they get here, but an
883 // ExecutionEngine can also be used on its own. Everything below - the final sweep
884 // in ~MemoryManager in particular - runs destruction handlers against an engine
885 // that is already losing its parts, and those must not start a gc.
886 inShutdown = true;
887
888#if QT_CONFIG(qml_network)
889 delete networkAccessManager;
890#endif
891 m_typeLoader.reset();
892 qDeleteAll(m_extensionData);
893 delete m_multiplyWrappedQObjects;
894 m_multiplyWrappedQObjects = nullptr;
895 delete identifierTable;
896 delete memoryManager;
897
898 for (const auto &cu : std::as_const(m_compilationUnits)) {
899 Q_ASSERT(cu->engine == this);
900 cu->clear();
901 cu->engine = nullptr;
902 }
903 m_compilationUnits.clear();
904
905 delete bumperPointerAllocator;
906 delete regExpCache;
907 delete regExpAllocator;
908 delete executableAllocator;
909 jsStack->deallocate();
910 delete jsStack;
911 gcStack->deallocate();
912 delete gcStack;
913
914#if QT_CONFIG(qml_xml_http_request)
915 qt_rem_qmlxmlhttprequest(this, m_xmlHttpRequestData);
916 m_xmlHttpRequestData = nullptr;
917#endif
918
919 QQmlMetaType::freeUnusedTypesAndCaches();
920}
921
922#if QT_CONFIG(qml_network)
923QNetworkAccessManager *ExecutionEngine::getNetworkAccessManager()
924{
925 if (!networkAccessManager)
926 networkAccessManager = typeLoader()->createNetworkAccessManager(nullptr);
927 return networkAccessManager;
928}
929#endif
930
931#if QT_CONFIG(qml_debug)
932void ExecutionEngine::setDebugger(Debugging::Debugger *debugger)
933{
934 Q_ASSERT(!m_debugger);
935 m_debugger.reset(debugger);
936}
937
938Moth::DebugInstructionPass ExecutionEngine::debugInstructionPass() const
939{
940 return m_debugger ? m_debugger->debugInstructionPass() : nullptr;
941}
942
943void ExecutionEngine::setProfiler(Profiling::Profiler *profiler)
944{
945 Q_ASSERT(!m_profiler);
946 m_profiler.reset(profiler);
947}
948
949void ExecutionEngine::setPreviewing(bool enabled)
950{
951 hasPreview.storeRelease(enabled);
952}
953
954bool ExecutionEngine::isPreviewing()
955{
956 return hasPreview.loadAcquire();
957}
958
959#endif // QT_CONFIG(qml_debug)
960
961void ExecutionEngine::initRootContext()
962{
963 Scope scope(this);
964 Scoped<ExecutionContext> r(scope, memoryManager->allocManaged<ExecutionContext>());
965 r->d()->init(Heap::ExecutionContext::Type_GlobalContext);
966 r->d()->activation.set(this, globalObject->d());
967 jsObjects[RootContext] = r;
968 jsObjects[ScriptContext] = r;
969 jsObjects[IntegerNull] = Encode((int)0);
970}
971
972Heap::InternalClass *ExecutionEngine::newClass(Heap::InternalClass *other)
973{
974 Heap::InternalClass *ic = memoryManager->allocIC<InternalClass>();
975 ic->init(other);
976 return ic;
977}
978
979Heap::InternalClass *ExecutionEngine::newInternalClass(const VTable *vtable, Object *prototype)
980{
981 Scope scope(this);
982 Scoped<InternalClass> ic(scope, internalClasses(Class_Empty)->changeVTable(vtable));
983 return ic->changePrototype(prototype ? prototype->d() : nullptr);
984}
985
986Heap::Object *ExecutionEngine::newObject()
987{
988 return memoryManager->allocate<Object>();
989}
990
991Heap::Object *ExecutionEngine::newObject(Heap::InternalClass *internalClass)
992{
993 return memoryManager->allocObject<Object>(internalClass);
994}
995
996Heap::String *ExecutionEngine::newString(const QString &s)
997{
998 return memoryManager->allocWithStringData<String>(s.size() * sizeof(QChar), s);
999}
1000
1001Heap::String *ExecutionEngine::newIdentifier(const QString &text)
1002{
1003 Scope scope(this);
1004 ScopedString s(scope, memoryManager->allocWithStringData<String>(text.size() * sizeof(QChar), text));
1005 s->toPropertyKey();
1006 return s->d();
1007}
1008
1009Heap::Object *ExecutionEngine::newStringObject(const String *string)
1010{
1011 return memoryManager->allocate<StringObject>(string);
1012}
1013
1014Heap::Object *ExecutionEngine::newSymbolObject(const Symbol *symbol)
1015{
1016 return memoryManager->allocObject<SymbolObject>(classes[Class_SymbolObject], symbol);
1017}
1018
1019Heap::Object *ExecutionEngine::newNumberObject(double value)
1020{
1021 return memoryManager->allocate<NumberObject>(value);
1022}
1023
1024Heap::Object *ExecutionEngine::newBooleanObject(bool b)
1025{
1026 return memoryManager->allocate<BooleanObject>(b);
1027}
1028
1029Heap::ArrayObject *ExecutionEngine::newArrayObject(int count)
1030{
1031 Scope scope(this);
1032 ScopedArrayObject object(scope, memoryManager->allocate<ArrayObject>());
1033
1034 if (count) {
1035 if (count < 0x1000)
1036 object->arrayReserve(count);
1037 object->setArrayLengthUnchecked(count);
1038 }
1039 return object->d();
1040}
1041
1042Heap::ArrayObject *ExecutionEngine::newArrayObject(const Value *values, int length)
1043{
1044 Scope scope(this);
1045 ScopedArrayObject a(scope, memoryManager->allocate<ArrayObject>());
1046
1047 if (length) {
1048 size_t size = sizeof(Heap::ArrayData) + (length-1)*sizeof(Value);
1049 Heap::SimpleArrayData *d = scope.engine->memoryManager->allocManaged<SimpleArrayData>(size);
1050 d->init();
1051 d->type = Heap::ArrayData::Simple;
1052 d->offset = 0;
1053 d->values.alloc = length;
1054 d->values.size = length;
1055 // this doesn't require a write barrier, things will be ok, when the new array data gets inserted into
1056 // the parent object
1057 memcpy(&d->values.values, values, length*sizeof(Value));
1058 a->d()->arrayData.set(this, d);
1059 a->setArrayLengthUnchecked(length);
1060 }
1061 return a->d();
1062}
1063
1064Heap::ArrayObject *ExecutionEngine::newArrayObject(const QStringList &list)
1065{
1066 return memoryManager->allocate<ArrayObject>(list);
1067}
1068
1069Heap::ArrayObject *ExecutionEngine::newArrayObject(Heap::InternalClass *internalClass)
1070{
1071 return memoryManager->allocObject<ArrayObject>(internalClass);
1072}
1073
1074Heap::ArrayBuffer *ExecutionEngine::newArrayBuffer(const QByteArray &array)
1075{
1076 return memoryManager->allocate<ArrayBuffer>(array);
1077}
1078
1079Heap::ArrayBuffer *ExecutionEngine::newArrayBuffer(size_t length)
1080{
1081 return memoryManager->allocate<ArrayBuffer>(length);
1082}
1083
1084Heap::DateObject *ExecutionEngine::newDateObject(double dateTime)
1085{
1086 return memoryManager->allocate<DateObject>(dateTime);
1087}
1088
1089Heap::DateObject *ExecutionEngine::newDateObject(const QDateTime &dateTime)
1090{
1091 return memoryManager->allocate<DateObject>(dateTime);
1092}
1093
1094Heap::DateObject *ExecutionEngine::newDateObject(
1095 QDate date, Heap::Object *parent, int index, uint flags)
1096{
1097 return memoryManager->allocate<DateObject>(
1098 date, parent, index, Heap::ReferenceObject::Flags(flags));
1099}
1100
1101Heap::DateObject *ExecutionEngine::newDateObject(
1102 QTime time, Heap::Object *parent, int index, uint flags)
1103{
1104 return memoryManager->allocate<DateObject>(
1105 time, parent, index, Heap::ReferenceObject::Flags(flags));
1106}
1107
1108Heap::DateObject *ExecutionEngine::newDateObject(
1109 QDateTime dateTime, Heap::Object *parent, int index, uint flags)
1110{
1111 return memoryManager->allocate<DateObject>(
1112 dateTime, parent, index, Heap::ReferenceObject::Flags(flags));
1113}
1114
1115Heap::RegExpObject *ExecutionEngine::newRegExpObject(const QString &pattern, int flags)
1116{
1117 Scope scope(this);
1118 Scoped<RegExp> re(scope, RegExp::create(this, pattern, static_cast<CompiledData::RegExp::Flags>(flags)));
1119 return newRegExpObject(re);
1120}
1121
1122Heap::RegExpObject *ExecutionEngine::newRegExpObject(RegExp *re)
1123{
1124 return memoryManager->allocate<RegExpObject>(re);
1125}
1126
1127#if QT_CONFIG(regularexpression)
1128Heap::RegExpObject *ExecutionEngine::newRegExpObject(const QRegularExpression &re)
1129{
1130 return memoryManager->allocate<RegExpObject>(re);
1131}
1132#endif
1133
1134Heap::UrlObject *ExecutionEngine::newUrlObject()
1135{
1136 return memoryManager->allocate<UrlObject>();
1137}
1138
1139Heap::UrlObject *ExecutionEngine::newUrlObject(const QUrl &url)
1140{
1141 Scope scope(this);
1142 Scoped<UrlObject> urlObject(scope, newUrlObject());
1143 urlObject->setUrl(url);
1144 return urlObject->d();
1145}
1146
1147Heap::UrlSearchParamsObject *ExecutionEngine::newUrlSearchParamsObject()
1148{
1149 return memoryManager->allocate<UrlSearchParamsObject>();
1150}
1151
1152Heap::Object *ExecutionEngine::newErrorObject(const Value &value)
1153{
1154 return ErrorObject::create<ErrorObject>(this, value, errorCtor());
1155}
1156
1157Heap::Object *ExecutionEngine::newErrorObject(const QString &message)
1158{
1159 return ErrorObject::create<ErrorObject>(this, message);
1160}
1161
1162Heap::Object *ExecutionEngine::newSyntaxErrorObject(const QString &message)
1163{
1164 return ErrorObject::create<SyntaxErrorObject>(this, message);
1165}
1166
1167Heap::Object *ExecutionEngine::newSyntaxErrorObject(const QString &message, const QString &fileName, int line, int column)
1168{
1169 return ErrorObject::create<SyntaxErrorObject>(this, message, fileName, line, column);
1170}
1171
1172
1173Heap::Object *ExecutionEngine::newReferenceErrorObject(const QString &message)
1174{
1175 return ErrorObject::create<ReferenceErrorObject>(this, message);
1176}
1177
1178Heap::Object *ExecutionEngine::newReferenceErrorObject(const QString &message, const QString &fileName, int line, int column)
1179{
1180 return ErrorObject::create<ReferenceErrorObject>(this, message, fileName, line, column);
1181}
1182
1183
1184Heap::Object *ExecutionEngine::newTypeErrorObject(const QString &message)
1185{
1186 return ErrorObject::create<TypeErrorObject>(this, message);
1187}
1188
1189Heap::Object *ExecutionEngine::newRangeErrorObject(const QString &message)
1190{
1191 return ErrorObject::create<RangeErrorObject>(this, message);
1192}
1193
1194Heap::Object *ExecutionEngine::newURIErrorObject(const Value &message)
1195{
1196 return ErrorObject::create<URIErrorObject>(this, message, uRIErrorCtor());
1197}
1198
1199Heap::PromiseObject *ExecutionEngine::newPromiseObject()
1200{
1201 if (!m_reactionHandler) {
1202 m_reactionHandler.reset(new Promise::ReactionHandler);
1203 }
1204
1205 Scope scope(this);
1206 Scoped<PromiseObject> object(scope, memoryManager->allocate<PromiseObject>(this));
1207 return object->d();
1208}
1209
1210Heap::Object *ExecutionEngine::newPromiseObject(const QV4::FunctionObject *thisObject, const QV4::PromiseCapability *capability)
1211{
1212 if (!m_reactionHandler) {
1213 m_reactionHandler.reset(new Promise::ReactionHandler);
1214 }
1215
1216 Scope scope(this);
1217 Scoped<CapabilitiesExecutorWrapper> executor(scope, memoryManager->allocate<CapabilitiesExecutorWrapper>());
1218 executor->d()->capabilities.set(this, capability->d());
1219 executor->insertMember(id_length(), Primitive::fromInt32(2), Attr_NotWritable|Attr_NotEnumerable);
1220
1221 ScopedObject object(scope, thisObject->callAsConstructor(executor, 1));
1222 return object->d();
1223}
1224
1225Promise::ReactionHandler *ExecutionEngine::getPromiseReactionHandler()
1226{
1227 Q_ASSERT(m_reactionHandler);
1228 return m_reactionHandler.data();
1229}
1230
1231Heap::Object *ExecutionEngine::newURIErrorObject(const QString &message)
1232{
1233 return ErrorObject::create<URIErrorObject>(this, message);
1234}
1235
1236Heap::Object *ExecutionEngine::newEvalErrorObject(const QString &message)
1237{
1238 return ErrorObject::create<EvalErrorObject>(this, message);
1239}
1240
1241Heap::Object *ExecutionEngine::newVariantObject(const QMetaType type, const void *data)
1242{
1243 return memoryManager->allocate<VariantObject>(type, data);
1244}
1245
1246Heap::Object *ExecutionEngine::newForInIteratorObject(Object *o)
1247{
1248 Scope scope(this);
1249 ScopedObject obj(scope, memoryManager->allocate<ForInIteratorObject>(o));
1250 return obj->d();
1251}
1252
1253Heap::Object *ExecutionEngine::newMapIteratorObject(Object *o)
1254{
1255 return memoryManager->allocate<MapIteratorObject>(o->d(), this);
1256}
1257
1258Heap::Object *ExecutionEngine::newSetIteratorObject(Object *o)
1259{
1260 return memoryManager->allocate<SetIteratorObject>(o->d(), this);
1261}
1262
1263Heap::Object *ExecutionEngine::newArrayIteratorObject(Object *o)
1264{
1265 return memoryManager->allocate<ArrayIteratorObject>(o->d(), this);
1266}
1267
1268Heap::QmlContext *ExecutionEngine::qmlContext() const
1269{
1270 return currentStackFrame
1271 ? static_cast<Heap::QmlContext *>(qmlContext(currentContext()->d()))
1272 : nullptr;
1273}
1274
1275QObject *ExecutionEngine::qmlScopeObject() const
1276{
1277 Heap::QmlContext *ctx = qmlContext();
1278 if (!ctx)
1279 return nullptr;
1280
1281 return ctx->qml()->scopeObject;
1282}
1283
1284QQmlRefPointer<QQmlContextData> ExecutionEngine::callingQmlContext() const
1285{
1286 Heap::QmlContext *ctx = qmlContext();
1287 if (!ctx)
1288 return nullptr;
1289
1290 return ctx->qml()->context;
1291}
1292
1293StackTrace ExecutionEngine::stackTrace(int frameLimit) const
1294{
1295 StackTrace stack;
1296
1297 CppStackFrame *f = currentStackFrame;
1298 while (f && frameLimit) {
1299 QV4::StackFrame frame;
1300 frame.source = f->source();
1301 frame.function = f->function();
1302 frame.line = f->lineNumber();
1303
1304 stack.append(frame);
1305 if (f->isJSTypesFrame()) {
1306 if (static_cast<JSTypesStackFrame *>(f)->isTailCalling()) {
1307 QV4::StackFrame frame;
1308 frame.function = QStringLiteral("[elided tail calls]");
1309 stack.append(frame);
1310 }
1311 }
1312 --frameLimit;
1313 f = f->parentFrame();
1314 }
1315
1316 return stack;
1317}
1318
1319/* Helper and "C" linkage exported function to format a GDBMI stacktrace for
1320 * invocation by a debugger.
1321 * Sample GDB invocation: print qt_v4StackTrace((void*)0x7fffffffb290)
1322 * Sample CDB invocation: .call Qt5Qmld!qt_v4StackTrace(0x7fffffffb290) ; gh
1323 * Note: The helper is there to suppress MSVC warning 4190 about anything
1324 * with UDT return types in a "C" linkage function. */
1325
1326static inline char *v4StackTrace(const ExecutionContext *context)
1327{
1328 QString result;
1329 QTextStream str(&result);
1330 str << "stack=[";
1331 if (context && context->engine()) {
1332 const QList<StackFrame> stackTrace = context->engine()->stackTrace(20);
1333 for (int i = 0; i < stackTrace.size(); ++i) {
1334 if (i)
1335 str << ',';
1336 const QUrl url(stackTrace.at(i).source);
1337 const QString fileName = url.isLocalFile() ? url.toLocalFile() : url.toString();
1338 str << "frame={level=\"" << i << "\",func=\"" << stackTrace.at(i).function
1339 << "\",file=\"" << fileName << "\",fullname=\"" << fileName
1340 << "\",line=\"" << qAbs(stackTrace.at(i).line) << "\",language=\"js\"}";
1341 }
1342 }
1343 str << ']';
1344 return qstrdup(result.toLocal8Bit().constData());
1345}
1346
1347extern "C" Q_QML_EXPORT char *qt_v4StackTrace(void *executionContext)
1348{
1349 return v4StackTrace(reinterpret_cast<const ExecutionContext *>(executionContext));
1350}
1351
1352extern "C" Q_QML_EXPORT char *qt_v4StackTraceForEngine(void *executionEngine)
1353{
1354 auto engine = (reinterpret_cast<const ExecutionEngine *>(executionEngine));
1355 return v4StackTrace(engine->currentContext());
1356}
1357
1358QUrl ExecutionEngine::resolvedUrl(const QString &file)
1359{
1360 QUrl src(file);
1361 if (!src.isRelative())
1362 return src;
1363
1364 QUrl base;
1365 CppStackFrame *f = currentStackFrame;
1366 while (f) {
1367 if (f->v4Function) {
1368 base = f->v4Function->finalUrl();
1369 break;
1370 }
1371 f = f->parentFrame();
1372 }
1373
1374 if (base.isEmpty() && globalCode)
1375 base = globalCode->finalUrl();
1376
1377 if (base.isEmpty())
1378 return src;
1379
1380 return base.resolved(src);
1381}
1382
1383void ExecutionEngine::markObjects(MarkStack *markStack)
1384{
1385 for (int i = 0; i < NClasses; ++i) {
1386 if (Heap::InternalClass *c = classes[i])
1387 c->mark(markStack);
1388 }
1389
1390 identifierTable->markObjects(markStack);
1391
1392 for (const auto &compilationUnit : std::as_const(m_compilationUnits))
1393 compilationUnit->markObjects(markStack);
1394}
1395
1396ReturnedValue ExecutionEngine::throwError(const Value &value)
1397{
1398 // we can get in here with an exception already set, as the runtime
1399 // doesn't check after every operation that can throw.
1400 // in this case preserve the first exception to give correct error
1401 // information
1402 if (hasException)
1403 return Encode::undefined();
1404
1405 hasException = true;
1406 *exceptionValue = value;
1407 QV4::Scope scope(this);
1408 QV4::Scoped<ErrorObject> error(scope, value);
1409 if (!!error)
1410 exceptionStackTrace = *error->d()->stackTrace;
1411 else
1412 exceptionStackTrace = stackTrace();
1413
1414 if (QV4::Debugging::Debugger *debug = debugger())
1415 debug->aboutToThrow();
1416
1417 return Encode::undefined();
1418}
1419
1420ReturnedValue ExecutionEngine::catchException(StackTrace *trace)
1421{
1422 Q_ASSERT(hasException);
1423 if (trace)
1424 *trace = exceptionStackTrace;
1425 exceptionStackTrace.clear();
1426 hasException = false;
1427 ReturnedValue res = exceptionValue->asReturnedValue();
1428 *exceptionValue = Value::emptyValue();
1429 return res;
1430}
1431
1432ReturnedValue ExecutionEngine::throwError(const QString &message)
1433{
1434 Scope scope(this);
1435 ScopedValue v(scope, newString(message));
1436 v = newErrorObject(v);
1437 return throwError(v);
1438}
1439
1440ReturnedValue ExecutionEngine::throwSyntaxError(const QString &message, const QString &fileName, int line, int column)
1441{
1442 Scope scope(this);
1443 ScopedObject error(scope, newSyntaxErrorObject(message, fileName, line, column));
1444 return throwError(error);
1445}
1446
1447ReturnedValue ExecutionEngine::throwSyntaxError(const QString &message)
1448{
1449 Scope scope(this);
1450 ScopedObject error(scope, newSyntaxErrorObject(message));
1451 return throwError(error);
1452}
1453
1454
1455ReturnedValue ExecutionEngine::throwTypeError()
1456{
1457 Scope scope(this);
1458 ScopedObject error(scope, newTypeErrorObject(QStringLiteral("Type error")));
1459 return throwError(error);
1460}
1461
1462ReturnedValue ExecutionEngine::throwTypeError(const QString &message)
1463{
1464 Scope scope(this);
1465 ScopedObject error(scope, newTypeErrorObject(message));
1466 return throwError(error);
1467}
1468
1469ReturnedValue ExecutionEngine::throwReferenceError(const QString &name)
1470{
1471 Scope scope(this);
1472 QString msg = name + QLatin1String(" is not defined");
1473 ScopedObject error(scope, newReferenceErrorObject(msg));
1474 return throwError(error);
1475}
1476
1477ReturnedValue ExecutionEngine::throwReferenceError(const Value &value)
1478{
1479 Scope scope(this);
1480 ScopedString s(scope, value.toString(this));
1481 QString msg = s->toQString() + QLatin1String(" is not defined");
1482 ScopedObject error(scope, newReferenceErrorObject(msg));
1483 return throwError(error);
1484}
1485
1486ReturnedValue ExecutionEngine::throwReferenceError(const QString &message, const QString &fileName, int line, int column)
1487{
1488 Scope scope(this);
1489 QString msg = message;
1490 ScopedObject error(scope, newReferenceErrorObject(msg, fileName, line, column));
1491 return throwError(error);
1492}
1493
1494ReturnedValue ExecutionEngine::throwRangeError(const QString &message)
1495{
1496 Scope scope(this);
1497 ScopedObject error(scope, newRangeErrorObject(message));
1498 return throwError(error);
1499}
1500
1501ReturnedValue ExecutionEngine::throwRangeError(const Value &value)
1502{
1503 Scope scope(this);
1504 ScopedString s(scope, value.toString(this));
1505 QString msg = s->toQString() + QLatin1String(" out of range");
1506 ScopedObject error(scope, newRangeErrorObject(msg));
1507 return throwError(error);
1508}
1509
1510ReturnedValue ExecutionEngine::throwURIError(const Value &msg)
1511{
1512 Scope scope(this);
1513 ScopedObject error(scope, newURIErrorObject(msg));
1514 return throwError(error);
1515}
1516
1517ReturnedValue ExecutionEngine::throwUnimplemented(const QString &message)
1518{
1519 Scope scope(this);
1520 ScopedValue v(scope, newString(QLatin1String("Unimplemented ") + message));
1521 v = newErrorObject(v);
1522 return throwError(v);
1523}
1524
1525
1526QQmlError ExecutionEngine::catchExceptionAsQmlError()
1527{
1528 QV4::StackTrace trace;
1529 QV4::Scope scope(this);
1530 QV4::ScopedValue exception(scope, catchException(&trace));
1531 QQmlError error;
1532 if (!trace.isEmpty()) {
1533 QV4::StackFrame frame = trace.constFirst();
1534 error.setUrl(QUrl(frame.source));
1535 error.setLine(qAbs(frame.line));
1536 error.setColumn(frame.column);
1537 }
1538 QV4::Scoped<QV4::ErrorObject> errorObj(scope, exception);
1539 error.setDescription(exception->toQStringNoThrow());
1540 return error;
1541}
1542
1543void ExecutionEngine::amendException()
1544{
1545 const int missingLineNumber = currentStackFrame->missingLineNumber();
1546 const int lineNumber = currentStackFrame->lineNumber();
1547 Q_ASSERT(missingLineNumber != lineNumber);
1548
1549 auto amendStackTrace = [&](QV4::StackTrace *stackTrace) {
1550 for (auto it = stackTrace->begin(), end = stackTrace->end(); it != end; ++it) {
1551 if (it->line == missingLineNumber) {
1552 it->line = lineNumber;
1553 break;
1554 }
1555 }
1556 };
1557
1558 amendStackTrace(&exceptionStackTrace);
1559
1560 QV4::Scope scope(this);
1561 QV4::Scoped<QV4::ErrorObject> error(scope, *exceptionValue);
1562 if (error) // else some other value was thrown
1563 amendStackTrace(error->d()->stackTrace);
1564}
1565
1566// Variant conversion code
1567
1570static QVariant toVariant(
1571 const QV4::Value &value, QMetaType typeHint, JSToQVariantConversionBehavior conversionBehavior,
1572 V4ObjectSet *visitedObjects);
1573static QObject *qtObjectFromJS(const QV4::Value &value);
1574static QVariant objectToVariant(const QV4::Object *o, V4ObjectSet *visitedObjects = nullptr,
1576static bool convertToNativeQObject(const QV4::Value &value, QMetaType targetType, void **result);
1577
1578static QVariant toVariant(const QV4::Value &value, QMetaType metaType, JSToQVariantConversionBehavior conversionBehavior,
1579 V4ObjectSet *visitedObjects)
1580{
1581 Q_ASSERT (!value.isEmpty());
1582
1583 if (const QV4::VariantObject *v = value.as<QV4::VariantObject>())
1584 return v->d()->data();
1585
1586 if (metaType == QMetaType::fromType<bool>())
1587 return QVariant(value.toBoolean());
1588
1589 if (metaType == QMetaType::fromType<double>())
1590 return QVariant(value.toNumber());
1591
1592 if (metaType == QMetaType::fromType<float>())
1593 return QVariant(float(value.toNumber()));
1594
1595 if (metaType == QMetaType::fromType<QJsonValue>())
1596 return QVariant::fromValue(QV4::JsonObject::toJsonValue(value));
1597
1598 if (metaType == QMetaType::fromType<QJSValue>())
1599 return QVariant::fromValue(QJSValuePrivate::fromReturnedValue(value.asReturnedValue()));
1600
1601 if (const QV4::Object *o = value.as<QV4::Object>()) {
1602 QV4::Scope scope(o->engine());
1603 QV4::ScopedObject object(scope, o);
1604 if (metaType == QMetaType::fromType<QJsonObject>()
1605 && !value.as<ArrayObject>() && !value.as<FunctionObject>()) {
1606 return QVariant::fromValue(QV4::JsonObject::toJsonObject(object));
1607 } else if (QV4::QObjectWrapper *wrapper = object->as<QV4::QObjectWrapper>()) {
1608 return QVariant::fromValue<QObject *>(wrapper->object());
1609 } else if (object->as<QV4::QQmlContextWrapper>()) {
1610 return QVariant();
1611 } else if (QV4::QQmlTypeWrapper *w = object->as<QV4::QQmlTypeWrapper>()) {
1612 return w->toVariant();
1613 } else if (QV4::QQmlValueTypeWrapper *v = object->as<QV4::QQmlValueTypeWrapper>()) {
1614 return v->toVariant();
1615 } else if (QV4::QmlListWrapper *l = object->as<QV4::QmlListWrapper>()) {
1616 return l->toVariant();
1617 } else if (QV4::Sequence *s = object->as<QV4::Sequence>()) {
1618 if (metaType.isValid()
1619 && metaType != QMetaType::fromType<QVariant>()
1620 && metaType != s->d()->listType()) {
1621 // If we can, produce an accurate result.
1622 const QVariant result = QV4::SequencePrototype::toVariant(value, metaType);
1623 if (result.isValid())
1624 return result;
1625 }
1626
1627 // Otherwise produce the "natural" type of the sequence.
1628 return QV4::SequencePrototype::toVariant(s);
1629 } else if (auto association = object->as<QV4::VariantAssociationObject>()) {
1630 return association->d()->toVariant();
1631 }
1632 }
1633
1634 if (const QV4::ArrayObject *o = value.as<ArrayObject>()) {
1635 QV4::Scope scope(o->engine());
1636 QV4::ScopedArrayObject a(scope, o);
1637 if (metaType == QMetaType::fromType<QList<QObject *>>()) {
1638 QList<QObject *> list;
1639 uint length = a->getLength();
1640 QV4::Scoped<QV4::Object> qobjectLike(scope);
1641 for (uint ii = 0; ii < length; ++ii) {
1642 qobjectLike = a->get(ii);
1643 list << qtObjectFromJS(qobjectLike);
1644 }
1645
1646 return QVariant::fromValue<QList<QObject*> >(list);
1647 } else if (metaType == QMetaType::fromType<QJsonArray>()) {
1648 return QVariant::fromValue(QV4::JsonObject::toJsonArray(a));
1649 }
1650
1651 QVariant retn = QV4::SequencePrototype::toVariant(value, metaType);
1652 if (retn.isValid())
1653 return retn;
1654 }
1655
1656 if (value.isUndefined())
1657 return QVariant();
1658 if (value.isNull())
1659 return QVariant::fromValue(nullptr);
1660 if (value.isBoolean())
1661 return value.booleanValue();
1662 if (value.isInteger())
1663 return value.integerValue();
1664 if (value.isNumber())
1665 return value.asDouble();
1666 if (String *s = value.stringValue()) {
1667 const QString &str = s->toQString();
1668 // QChars are stored as a strings
1669 if (metaType == QMetaType::fromType<QChar>() && str.size() == 1)
1670 return str.at(0);
1671 return str;
1672 }
1673 if (const QV4::DateObject *d = value.as<DateObject>()) {
1674 // NOTE: since we convert QTime to JS Date,
1675 // round trip will change the variant type (to QDateTime)!
1676
1677 if (metaType == QMetaType::fromType<QDate>())
1678 return DateObject::dateTimeToDate(d->toQDateTime());
1679
1680 if (metaType == QMetaType::fromType<QTime>())
1681 return d->toQDateTime().time();
1682
1683 if (metaType == QMetaType::fromType<QString>())
1684 return d->toString();
1685
1686 return d->toQDateTime();
1687 }
1688 if (const QV4::UrlObject *d = value.as<UrlObject>())
1689 return d->toQUrl();
1690 if (const ArrayBuffer *d = value.as<ArrayBuffer>())
1691 return d->asByteArray();
1692 if (const Symbol *symbol = value.as<Symbol>()) {
1693 return conversionBehavior == JSToQVariantConversionBehavior::Never
1694 ? QVariant::fromValue(QJSValuePrivate::fromReturnedValue(symbol->asReturnedValue()))
1695 : symbol->descriptiveString();
1696 }
1697
1698 const QV4::Object *object = value.as<QV4::Object>();
1699 Q_ASSERT(object);
1700 QV4::Scope scope(object->engine());
1701 QV4::ScopedObject o(scope, object);
1702
1703#if QT_CONFIG(regularexpression)
1704 if (QV4::RegExpObject *re = o->as<QV4::RegExpObject>())
1705 return re->toQRegularExpression();
1706#endif
1707
1708 if (metaType.isValid() && !(metaType.flags() & QMetaType::PointerToQObject)) {
1709 const QVariant result
1710 = QQmlValueTypeProvider::createValueType(value, metaType, scope.engine);
1711 if (result.isValid())
1712 return result;
1713 }
1714
1715 if (conversionBehavior == JSToQVariantConversionBehavior::Never)
1716 return QVariant::fromValue(QJSValuePrivate::fromReturnedValue(o->asReturnedValue()));
1717
1718 return objectToVariant(o, visitedObjects, conversionBehavior);
1719}
1720
1721QVariant ExecutionEngine::toVariantLossy(const Value &value)
1722{
1723 return ::toVariant(value, QMetaType(), JSToQVariantConversionBehavior::Aggressive, nullptr);
1724}
1725
1726QVariant ExecutionEngine::toVariant(
1727 const Value &value, QMetaType typeHint, bool createJSValueForObjectsAndSymbols)
1728{
1729 auto behavior = createJSValueForObjectsAndSymbols ? JSToQVariantConversionBehavior::Never
1730 : JSToQVariantConversionBehavior::Safish;
1731 return ::toVariant(value, typeHint, behavior, nullptr);
1732}
1733
1734template<typename Association>
1736 const QV4::Object *o, V4ObjectSet *visitedObjects,
1737 JSToQVariantConversionBehavior conversionBehvior)
1738{
1739 Association association;
1740 QV4::Scope scope(o->engine());
1741 QV4::ObjectIterator it(scope, o, QV4::ObjectIterator::EnumerableOnly);
1742 QV4::ScopedValue name(scope);
1743 QV4::ScopedValue val(scope);
1744 while (1) {
1745 name = it.nextPropertyNameAsString(val);
1746 if (name->isNull())
1747 break;
1748
1749 QString key = name->toQStringNoThrow();
1750 association.insert(key, ::toVariant(
1751 val, /*type hint*/ QMetaType {},
1752 conversionBehvior, visitedObjects));
1753 }
1754 return association;
1755}
1756
1757static QVariant objectToVariant(const QV4::Object *o, V4ObjectSet *visitedObjects,
1758 JSToQVariantConversionBehavior conversionBehvior)
1759{
1760 Q_ASSERT(o);
1761
1762 QV4::ExecutionEngine *engine = o->engine();
1763 if (Q_UNLIKELY(engine->checkStackLimits())) {
1764 if (o->as<ArrayObject>())
1765 return QVariantList();
1766 return QVariantMap();
1767 }
1768
1769 V4ObjectSet recursionGuardSet;
1770 if (!visitedObjects) {
1771 visitedObjects = &recursionGuardSet;
1772 } else if (visitedObjects->contains(o->d())) {
1773 // Avoid recursion.
1774 // For compatibility with QVariant{List,Map} conversion, we return an
1775 // empty object (and no error is thrown).
1776 if (o->as<ArrayObject>())
1777 return QVariantList();
1778 return QVariantMap();
1779 }
1780 visitedObjects->insert(o->d());
1781
1782 QVariant result;
1783
1784 if (o->as<ArrayObject>()) {
1785 QV4::Scope scope(engine);
1786 QV4::ScopedArrayObject a(scope, o->asReturnedValue());
1787 QV4::ScopedValue v(scope);
1788 QVariantList list;
1789
1790 int length = a->getLength();
1791 for (int ii = 0; ii < length; ++ii) {
1792 v = a->get(ii);
1793 list << ::toVariant(v, QMetaType {}, conversionBehvior,
1794 visitedObjects);
1795 }
1796
1797 result = list;
1798 } else if (o->getPrototypeOf() == engine->objectPrototype()->d()
1799 || (conversionBehvior == JSToQVariantConversionBehavior::Aggressive &&
1800 !o->as<QV4::FunctionObject>())) {
1801 /* FunctionObject is excluded for historical reasons, even though
1802 objects with a custom prototype risk losing information
1803 But the Aggressive path is used only in QJSValue::toVariant
1804 which is documented to be lossy
1805 */
1806 result = objectToVariantAssociation<QVariantMap>(o, visitedObjects, conversionBehvior);
1807 } else {
1808 // If it's not a plain object, we can only save it as QJSValue.
1809 result = QVariant::fromValue(QJSValuePrivate::fromReturnedValue(o->asReturnedValue()));
1810 }
1811
1812 visitedObjects->remove(o->d());
1813 return result;
1814}
1815
1816/*!
1817 \internal
1818
1819 Transform the given \a metaType and \a ptr into a JavaScript representation.
1820 */
1821QV4::ReturnedValue ExecutionEngine::fromData(
1822 QMetaType metaType, const void *ptr,
1823 QV4::Heap::Object *container, int property, uint flags)
1824{
1825 const auto createSequence = [&](const QMetaSequence metaSequence) {
1826 QV4::Scope scope(this);
1827 QV4::Scoped<Sequence> sequence(scope);
1828 if (container) {
1829 return QV4::SequencePrototype::newSequence(
1830 this, metaType, metaSequence, ptr,
1831 container, property, Heap::ReferenceObject::Flags(flags));
1832 } else {
1833 return QV4::SequencePrototype::fromData(this, metaType, metaSequence, ptr);
1834 }
1835 };
1836
1837 const int type = metaType.id();
1838 if (type < QMetaType::User) {
1839 switch (QMetaType::Type(type)) {
1840 case QMetaType::UnknownType:
1841 case QMetaType::Void:
1842 return QV4::Encode::undefined();
1843 case QMetaType::Nullptr:
1844 case QMetaType::VoidStar:
1845 return QV4::Encode::null();
1846 case QMetaType::Bool:
1847 return QV4::Encode(*reinterpret_cast<const bool*>(ptr));
1848 case QMetaType::Int:
1849 return QV4::Encode(*reinterpret_cast<const int*>(ptr));
1850 case QMetaType::UInt:
1851 return QV4::Encode(*reinterpret_cast<const uint*>(ptr));
1852 case QMetaType::Long:
1853 return QV4::Encode((double)*reinterpret_cast<const long *>(ptr));
1854 case QMetaType::ULong:
1855 return QV4::Encode((double)*reinterpret_cast<const ulong *>(ptr));
1856 case QMetaType::LongLong:
1857 return QV4::Encode((double)*reinterpret_cast<const qlonglong*>(ptr));
1858 case QMetaType::ULongLong:
1859 return QV4::Encode((double)*reinterpret_cast<const qulonglong*>(ptr));
1860 case QMetaType::Double:
1861 return QV4::Encode(*reinterpret_cast<const double*>(ptr));
1862 case QMetaType::QString:
1863 return newString(*reinterpret_cast<const QString*>(ptr))->asReturnedValue();
1864 case QMetaType::QByteArray:
1865 return newArrayBuffer(*reinterpret_cast<const QByteArray*>(ptr))->asReturnedValue();
1866 case QMetaType::Float:
1867 return QV4::Encode(*reinterpret_cast<const float*>(ptr));
1868 case QMetaType::Short:
1869 return QV4::Encode((int)*reinterpret_cast<const short*>(ptr));
1870 case QMetaType::UShort:
1871 return QV4::Encode((int)*reinterpret_cast<const unsigned short*>(ptr));
1872 case QMetaType::Char:
1873 return QV4::Encode((int)*reinterpret_cast<const char*>(ptr));
1874 case QMetaType::UChar:
1875 return QV4::Encode((int)*reinterpret_cast<const unsigned char*>(ptr));
1876 case QMetaType::SChar:
1877 return QV4::Encode((int)*reinterpret_cast<const signed char*>(ptr));
1878 case QMetaType::QChar:
1879 return newString(*reinterpret_cast<const QChar *>(ptr))->asReturnedValue();
1880 case QMetaType::Char16:
1881 return newString(QChar(*reinterpret_cast<const char16_t *>(ptr)))->asReturnedValue();
1882 case QMetaType::QDateTime:
1883 return QV4::Encode(newDateObject(
1884 *reinterpret_cast<const QDateTime *>(ptr),
1885 container, property, flags));
1886 case QMetaType::QDate:
1887 return QV4::Encode(newDateObject(
1888 *reinterpret_cast<const QDate *>(ptr),
1889 container, property, flags));
1890 case QMetaType::QTime:
1891 return QV4::Encode(newDateObject(
1892 *reinterpret_cast<const QTime *>(ptr),
1893 container, property, flags));
1894#if QT_CONFIG(regularexpression)
1895 case QMetaType::QRegularExpression:
1896 return QV4::Encode(newRegExpObject(*reinterpret_cast<const QRegularExpression *>(ptr)));
1897#endif
1898 case QMetaType::QObjectStar:
1899 return QV4::QObjectWrapper::wrap(this, *reinterpret_cast<QObject* const *>(ptr));
1900 case QMetaType::QStringList:
1901 return createSequence(QMetaSequence::fromContainer<QStringList>());
1902 case QMetaType::QVariantList:
1903 return createSequence(QMetaSequence::fromContainer<QVariantList>());
1904 case QMetaType::QVariantMap:
1905 return VariantAssociationPrototype::fromQVariantMap(
1906 this,
1907 *reinterpret_cast<const QVariantMap *>(ptr),
1908 container, property, Heap::ReferenceObject::Flags(flags));
1909 case QMetaType::QVariantHash:
1910 return VariantAssociationPrototype::fromQVariantHash(
1911 this,
1912 *reinterpret_cast<const QVariantHash *>(ptr),
1913 container, property, Heap::ReferenceObject::Flags(flags));
1914 case QMetaType::QJsonValue:
1915 return QV4::JsonObject::fromJsonValue(this, *reinterpret_cast<const QJsonValue *>(ptr));
1916 case QMetaType::QJsonObject:
1917 return QV4::JsonObject::fromJsonObject(this, *reinterpret_cast<const QJsonObject *>(ptr));
1918 case QMetaType::QJsonArray:
1919 return QV4::JsonObject::fromJsonArray(this, *reinterpret_cast<const QJsonArray *>(ptr));
1920 case QMetaType::QPixmap:
1921 case QMetaType::QImage:
1922 // Scarce value types
1923 return QV4::Encode(newVariantObject(metaType, ptr));
1924 default:
1925 break;
1926 }
1927 }
1928
1929 if (metaType.flags() & QMetaType::IsEnumeration)
1930 return fromData(metaType.underlyingType(), ptr, container, property, flags);
1931
1932 QV4::Scope scope(this);
1933 if (metaType == QMetaType::fromType<QQmlListReference>()) {
1934 typedef QQmlListReferencePrivate QDLRP;
1935 QDLRP *p = QDLRP::get((QQmlListReference*)const_cast<void *>(ptr));
1936 if (p->object)
1937 return QV4::QmlListWrapper::create(scope.engine, p->property, p->propertyType);
1938 else
1939 return QV4::Encode::null();
1940 } else if (auto flags = metaType.flags(); flags & QMetaType::IsQmlList) {
1941 // casting to QQmlListProperty<QObject> is slightly nasty, but it's the
1942 // same QQmlListReference does.
1943 const auto *p = static_cast<const QQmlListProperty<QObject> *>(ptr);
1944 if (p->object)
1945 return QV4::QmlListWrapper::create(scope.engine, *p, metaType);
1946 else
1947 return QV4::Encode::null();
1948 } else if (metaType == QMetaType::fromType<QJSValue>()) {
1949 return QJSValuePrivate::convertToReturnedValue(
1950 this, *reinterpret_cast<const QJSValue *>(ptr));
1951 } else if (metaType == QMetaType::fromType<QList<QObject *> >()) {
1952 // XXX Can this be made more by using Array as a prototype and implementing
1953 // directly against QList<QObject*>?
1954 const QList<QObject *> &list = *(const QList<QObject *>*)ptr;
1955 QV4::ScopedArrayObject a(scope, newArrayObject());
1956 a->arrayReserve(list.size());
1957 QV4::ScopedValue v(scope);
1958 for (int ii = 0; ii < list.size(); ++ii)
1959 a->arrayPut(ii, (v = QV4::QObjectWrapper::wrap(this, list.at(ii))));
1960 a->setArrayLengthUnchecked(list.size());
1961 return a.asReturnedValue();
1962 } else if (auto flags = metaType.flags(); flags & QMetaType::PointerToQObject) {
1963 if (flags.testFlag(QMetaType::IsConst))
1964 return QV4::QObjectWrapper::wrapConst(this, *reinterpret_cast<QObject* const *>(ptr));
1965 else
1966 return QV4::QObjectWrapper::wrap(this, *reinterpret_cast<QObject* const *>(ptr));
1967 } else if (metaType == QMetaType::fromType<QJSPrimitiveValue>()) {
1968 const QJSPrimitiveValue *primitive = static_cast<const QJSPrimitiveValue *>(ptr);
1969 switch (primitive->type()) {
1970 case QJSPrimitiveValue::Boolean:
1971 return Encode(primitive->asBoolean());
1972 case QJSPrimitiveValue::Integer:
1973 return Encode(primitive->asInteger());
1974 case QJSPrimitiveValue::String:
1975 return newString(primitive->asString())->asReturnedValue();
1976 case QJSPrimitiveValue::Undefined:
1977 return Encode::undefined();
1978 case QJSPrimitiveValue::Null:
1979 return Encode::null();
1980 case QJSPrimitiveValue::Double:
1981 return Encode(primitive->asDouble());
1982 }
1983 }
1984
1985 if (const QMetaObject *vtmo = QQmlMetaType::metaObjectForValueType(metaType)) {
1986 if (container) {
1987 return QV4::QQmlValueTypeWrapper::create(
1988 this, ptr, vtmo, metaType,
1989 container, property, Heap::ReferenceObject::Flags(flags));
1990 } else {
1991 return QV4::QQmlValueTypeWrapper::create(this, ptr, vtmo, metaType);
1992 }
1993 }
1994
1995 const QQmlType listType = QQmlMetaType::qmlListType(metaType);
1996 if (listType.isSequentialContainer())
1997 return createSequence(listType.listMetaSequence());
1998
1999 QMetaSequence::Iterable iterable;
2000 if (QMetaType::convert(metaType, ptr, QMetaType::fromType<QMetaSequence::Iterable>(), &iterable)) {
2001
2002 // If the resulting iterable is useful for anything, turn it into a QV4::Sequence.
2003 const QMetaSequence sequence = iterable.metaContainer();
2004 if (sequence.hasSize() && sequence.canGetValueAtIndex())
2005 return createSequence(sequence);
2006
2007 // As a last resort, try to read the contents of the container via an iterator
2008 // and build a JS array from them.
2009 if (sequence.hasConstIterator() && sequence.canGetValueAtConstIterator()) {
2010 QV4::ScopedArrayObject a(scope, newArrayObject());
2011 QV4::ScopedValue v(scope);
2012 for (auto it = iterable.constBegin(), end = iterable.constEnd(); it != end; ++it) {
2013 v = fromVariant(*it);
2014 a->push_back(v);
2015 }
2016 return a.asReturnedValue();
2017 }
2018 }
2019
2020 return QV4::Encode(newVariantObject(metaType, ptr));
2021}
2022
2023QV4::ReturnedValue QV4::ExecutionEngine::fromVariant(const QVariant &variant)
2024{
2025 return fromData(variant.metaType(), variant.constData());
2026}
2027
2028ReturnedValue ExecutionEngine::fromVariant(
2029 const QVariant &variant, Heap::Object *parent, int property, uint flags)
2030{
2031 return fromData(variant.metaType(), variant.constData(), parent, property, flags);
2032}
2033
2034// Returns true if fromVariant() would produce undefined for the given variant.
2035bool ExecutionEngine::isUndefinedVariant(const QVariant &variant)
2036{
2037 const QMetaType metaType = variant.metaType();
2038 return isEquivalentToUndefinedData(metaType, variant.constData());
2039}
2040
2041// Assumes that data points to data of type metaType
2042// Returns true if it would convert to undefined in QML
2043bool ExecutionEngine::isEquivalentToUndefinedData(QMetaType metaType, const void *data)
2044{
2045 switch (metaType.id()) {
2046 case QMetaType::UnknownType:
2047 case QMetaType::Void:
2048 return true;
2049 case QMetaType::QJsonValue:
2050 return static_cast<const QJsonValue *>(data)->isUndefined();
2051 default:
2052 break;
2053 }
2054
2055 if (metaType == QMetaType::fromType<QJSValue>())
2056 return static_cast<const QJSValue *>(data)->isUndefined();
2057 if (metaType == QMetaType::fromType<QJSPrimitiveValue>()) {
2058 return static_cast<const QJSPrimitiveValue *>(data)->type()
2059 == QJSPrimitiveValue::Undefined;
2060 }
2061 if (metaType == QMetaType::fromType<QJSManagedValue>())
2062 return static_cast<const QJSManagedValue *>(data)->isUndefined();
2063 return false;
2064}
2065
2066QVariantMap ExecutionEngine::variantMapFromJS(const Object *o)
2067{
2068 Q_ASSERT(o);
2069 V4ObjectSet visitedObjects;
2070 visitedObjects.insert(o->d());
2071 return objectToVariantAssociation<QVariantMap>(
2072 o, &visitedObjects, JSToQVariantConversionBehavior::Safish);
2073}
2074
2075QVariantHash ExecutionEngine::variantHashFromJS(const Object *o)
2076{
2077 Q_ASSERT(o);
2078 V4ObjectSet visitedObjects;
2079 visitedObjects.insert(o->d());
2080 return objectToVariantAssociation<QVariantHash>(
2081 o, &visitedObjects, JSToQVariantConversionBehavior::Safish);
2082}
2083
2084// Converts the meta-type defined by the given type and data to JS.
2085// Returns the value if conversion succeeded, an empty handle otherwise.
2086QV4::ReturnedValue ExecutionEngine::metaTypeToJS(QMetaType type, const void *data)
2087{
2088 Q_ASSERT(data != nullptr);
2089
2090 if (type == QMetaType::fromType<QVariant>()) {
2091 // unwrap it: this is tested in QJSEngine, and makes the most sense for
2092 // end-user code too.
2093 return fromVariant(*reinterpret_cast<const QVariant*>(data));
2094 } else if (type == QMetaType::fromType<QUrl>()) {
2095 // Create a proper URL object here, rather than a variant.
2096 return newUrlObject(*reinterpret_cast<const QUrl *>(data))->asReturnedValue();
2097 }
2098
2099 return fromData(type, data);
2100}
2101
2102int ExecutionEngine::maxJSStackSize() const
2103{
2104 return s_maxJSStackSize;
2105}
2106
2107int ExecutionEngine::maxGCStackSize() const
2108{
2109 return s_maxGCStackSize;
2110}
2111
2112/*!
2113 \internal
2114 Returns \a length converted to int if its safe to
2115 pass to \c Scope::alloc.
2116 Otherwise it throws a RangeError, and returns 0.
2117 */
2118int ExecutionEngine::safeForAllocLength(qint64 len64)
2119{
2120 if (len64 < 0ll || len64 > qint64(std::numeric_limits<int>::max())) {
2121 throwRangeError(QStringLiteral("Invalid array length."));
2122 return 0;
2123 }
2124 if (len64 > qint64(this->jsStackLimit - this->jsStackTop)) {
2125 throwRangeError(QStringLiteral("Array too large for apply()."));
2126 return 0;
2127 }
2128 return len64;
2129}
2130
2131ReturnedValue ExecutionEngine::global()
2132{
2133 return globalObject->asReturnedValue();
2134}
2135
2136QQmlRefPointer<ExecutableCompilationUnit> ExecutionEngine::compilationUnitForUrl(const QUrl &url) const
2137{
2138 // Gives the _most recently inserted_ CU of that URL. That's what we want.
2139 return m_compilationUnits.value(url);
2140}
2141
2142QQmlRefPointer<ExecutableCompilationUnit> ExecutionEngine::executableCompilationUnit(
2143 QQmlRefPointer<CompiledData::CompilationUnit> &&unit)
2144{
2145 const QUrl url = unit->finalUrl();
2146 auto [begin, end] = std::as_const(m_compilationUnits).equal_range(url);
2147
2148 for (auto it = begin; it != end; ++it) {
2149 if ((*it)->baseCompilationUnit() == unit)
2150 return *it;
2151 }
2152
2153 auto executableUnit = m_compilationUnits.insert(
2154 url, ExecutableCompilationUnit::create(std::move(unit), this));
2155 // runtime data should not be initialized yet, so we don't need to mark the CU
2156 Q_ASSERT(!(*executableUnit)->runtimeStrings);
2157 return *executableUnit;
2158}
2159
2160QQmlRefPointer<ExecutableCompilationUnit> ExecutionEngine::insertCompilationUnit(QQmlRefPointer<CompiledData::CompilationUnit> &&unit) {
2161 QUrl url = unit->finalUrl();
2162 auto executableUnit = ExecutableCompilationUnit::create(std::move(unit), this);
2163 /* Compilation Units stored in the engine are part of the gc roots,
2164 so we don't trigger any write-barrier when they are added. Use
2165 markCustom to make sure they are still marked when we insert them */
2166 QV4::WriteBarrier::markCustom(this, [&executableUnit](QV4::MarkStack *ms) {
2167 executableUnit->markObjects(ms);
2168 });
2169 return *m_compilationUnits.insert(std::move(url), std::move(executableUnit));
2170}
2171
2172void ExecutionEngine::trimCompilationUnits()
2173{
2174 for (auto it = m_compilationUnits.begin(); it != m_compilationUnits.end();) {
2175 if ((*it)->count() == 1)
2176 it = m_compilationUnits.erase(it);
2177 else
2178 ++it;
2179 }
2180}
2181
2182void ExecutionEngine::trimCompilationUnitsForUrl(const QUrl &url)
2183{
2184 auto it = m_compilationUnits.find(url);
2185 while (it != m_compilationUnits.end() && it.key() == url) {
2186 if ((*it)->count() == 1)
2187 it = m_compilationUnits.erase(it);
2188 else
2189 ++it;
2190 }
2191}
2192
2193/*!
2194 * Returns any _existing_ module for the given \a url and \a referrer. This
2195 * does not actually load anything. You must guarantee the existence of the
2196 * module by keeping a (direct or indirect) reference to it somewhere, or you
2197 * must live with a possible nullptr being returned.
2198 */
2199ExecutionEngine::Module ExecutionEngine::moduleForUrl(
2200 const QUrl &url, const ExecutableCompilationUnit *referrer)
2201{
2202 QUrl resolved = referrer
2203 ? referrer->finalUrl().resolved(QQmlMetaType::normalizedUrl(url))
2204 : QQmlMetaType::normalizedUrl(url);
2205 if (!resolved.path().endsWith(QLatin1String(".mjs")))
2206 resolved.setFragment(QLatin1String("module"));
2207
2208 // Executable compilation unit already present in engine
2209 auto existingModule = m_compilationUnits.constFind(resolved);
2210 if (existingModule != m_compilationUnits.constEnd())
2211 return *existingModule;
2212
2213 // Also try with the relative url, to support native modules.
2214 if (resolved != url) {
2215 existingModule = m_compilationUnits.constFind(url);
2216 if (existingModule != m_compilationUnits.constEnd())
2217 return *existingModule;
2218 }
2219
2220 if (const auto blob = m_typeLoader->getScript(resolved, QQmlTypeLoader::Synchronous))
2221 return executableCompilationUnit(blob->scriptData()->compilationUnit());
2222
2223 // Unavailable
2224 return Module();
2225}
2226
2227ExecutionEngine::Module ExecutionEngine::registerNativeModule(
2228 const QUrl &url, const QV4::Value &value)
2229{
2230 Q_ASSERT(!m_compilationUnits.contains(url));
2231
2232 const QV4::CompiledData::Unit *unit = Compiler::Codegen::generateNativeModuleUnitData(
2233 debugInstructionPass(), url.toString(), value);
2234 if (!unit)
2235 return Module();
2236
2237 QQmlRefPointer<CompiledData::CompilationUnit> cu;
2238
2239 // Make sure the type loader doesn't try to resolve the module anymore.
2240 // If some other code requests that same module, we need to produce the same CU.
2241 cu = typeLoader()->injectModule(url, unit);
2242
2243 QQmlRefPointer<ExecutableCompilationUnit> newModule = insertCompilationUnit(std::move(cu));
2244
2245 Q_ASSERT(m_compilationUnits.contains(url, newModule));
2246
2247 Scope scope(this);
2248 Scoped<QV4::Module> instance(scope, newModule->instantiate());
2249 Scoped<CallContext> context(scope, instance->d()->scope);
2250
2251 const CompiledData::Unit *unitData = newModule->baseCompilationUnit()->data;
2252 const CompiledData::ExportEntry *exportEntries = unitData->localExportEntryTable();
2253
2254 ScopedObject object(scope, value);
2255 for (uint i = 0, end = unitData->localExportEntryTableSize; i < end; ++i) {
2256 const CompiledData::ExportEntry *localExport = exportEntries + i;
2257 ScopedString localName(scope, newModule->runtimeStrings[localExport->localName]);
2258 const uint index
2259 = context->internalClass()->indexOfValueOrGetter(localName->toPropertyKey());
2260 QV4::Heap::CallContext *cc = context->d();
2261 Q_ASSERT(index < cc->locals.size);
2262 if (localName->toQString() == QLatin1String("default")) {
2263 cc->locals.set(this, index, value);
2264 continue;
2265 }
2266
2267 Q_ASSERT(object);
2268
2269 ScopedValue localValue(scope, object->get(localName));
2270 cc->locals.set(this, index, localValue);
2271 }
2272
2273 instance->d()->evaluated = true;
2274 return newModule;
2275}
2276
2278{
2279 using DiskCache = ExecutionEngine::DiskCache;
2280
2281 if (v == nullptr)
2282 return DiskCache::Enabled;
2283
2284 ExecutionEngine::DiskCacheOptions result = DiskCache::Disabled;
2285 const QList<QByteArray> options = QByteArray(v).split(',');
2286 for (const QByteArray &option : options) {
2287 if (option == "aot-bytecode")
2288 result |= DiskCache::AotByteCode;
2289 else if (option == "aot-native")
2290 result |= DiskCache::AotNative;
2291 else if (option == "aot")
2292 result |= DiskCache::Aot;
2293 else if (option == "qmlc-read")
2294 result |= DiskCache::QmlcRead;
2295 else if (option == "qmlc-write")
2296 result |= DiskCache::QmlcWrite;
2297 else if (option == "qmlc")
2298 result |= DiskCache::Qmlc;
2299 else
2300 qWarning() << "Ignoring unknown option to QML_DISK_CACHE:" << option;
2301 }
2302
2303 return result;
2304}
2305
2306ExecutionEngine::DiskCacheOptions ExecutionEngine::diskCacheOptions() const
2307{
2308 if (forceDiskCache())
2309 return DiskCache::Enabled;
2310 if (disableDiskCache() || debugger())
2311 return DiskCache::Disabled;
2312 static const DiskCacheOptions options = qmlGetConfigOption<
2313 DiskCacheOptions, transFormDiskCache>("QML_DISK_CACHE");
2314 return hasPreview.loadAcquire()
2315 ? (options & ~DiskCacheOptions(DiskCache::Aot)) // Disable AOT if preview enabled
2316 : options;
2317}
2318
2319void ExecutionEngine::callInContext(QV4::Function *function, QObject *self,
2320 QV4::ExecutionContext *context, int argc, void **args,
2321 QMetaType *types)
2322{
2323 if (!args) {
2324 Q_ASSERT(argc == 0);
2325 void *dummyArgs[] = { nullptr };
2326 QMetaType dummyTypes[] = { QMetaType::fromType<void>() };
2327 function->call(self, dummyArgs, dummyTypes, argc, context);
2328 return;
2329 }
2330 Q_ASSERT(types); // both args and types must be present
2331 // implicitly sets the return value, which is args[0]
2332 function->call(self, args, types, argc, context);
2333}
2334
2335QV4::ReturnedValue ExecutionEngine::callInContext(QV4::Function *function, QObject *self,
2336 QV4::ExecutionContext *context, int argc,
2337 const QV4::Value *argv)
2338{
2339 QV4::Scope scope(this);
2340 QV4::ScopedObject jsSelf(scope, QV4::QObjectWrapper::wrap(this, self));
2341 Q_ASSERT(jsSelf);
2342 return function->call(jsSelf, argv, argc, context);
2343}
2344
2345void ExecutionEngine::initQmlGlobalObject()
2346{
2347 initializeGlobal();
2348 lockObject(*globalObject);
2349}
2350
2351static bool globalNamesAreStaticallyKnown(QV4::Object *globalObject)
2352{
2353 const Heap::InternalClass *ic = globalObject->internalClass();
2354 const SharedInternalClassData<PropertyKey> &nameMap = ic->nameMap;
2355 bool clean = true;
2356 for (uint i = 0, end = ic->size; i < end; ++i) {
2357 const QV4::PropertyKey id = nameMap.at(i);
2358 if (id.isString()) {
2359 if (!Compiler::Codegen::isNameGlobal(id.toQString())) {
2360 qCritical() << id.toQString()
2361 << "is part of the JavaScript global object "
2362 "but not statically known to be global";
2363 clean = false;
2364 }
2365 }
2366 }
2367 return clean;
2368}
2369
2370#if QT_CONFIG(qml_xml_http_request)
2371void ExecutionEngine::setupXmlHttpRequestExtension()
2372{
2373 qt_add_domexceptions(this);
2374 m_xmlHttpRequestData = qt_add_qmlxmlhttprequest(this);
2375}
2376#endif
2377
2378void ExecutionEngine::initializeGlobal()
2379{
2380 createQtObject();
2381
2382 QV4::GlobalExtensions::init(globalObject, QJSEngine::AllExtensions);
2383
2384#if QT_CONFIG(qml_locale)
2385 QQmlLocale::registerStringLocaleCompare(this);
2386 QQmlDateExtension::registerExtension(this);
2387 QQmlNumberExtension::registerExtension(this);
2388#endif
2389
2390#if QT_CONFIG(qml_xml_http_request)
2391 setupXmlHttpRequestExtension();
2392#endif
2393
2394 qt_add_sqlexceptions(this);
2395
2396 Q_ASSERT(globalNamesAreStaticallyKnown(globalObject));
2397}
2398
2399void ExecutionEngine::createQtObject()
2400{
2401 QV4::Scope scope(this);
2402 QtObject *qtObject = new QtObject(this);
2403
2404 if (publicEngine) {
2405 // If we have a public engine, parent to that one so that we don't delete
2406 // the instance on QQmlEngine::clearSingletons() we still need it as property
2407 // of the global object after all.
2408 QJSEngine::setObjectOwnership(qtObject, QJSEngine::CppOwnership);
2409 qtObject->setParent(publicEngine);
2410 } else {
2411 // If we don't have a public engine, the object isn't exposed as a singleton.
2412 // We can use JavaScript ownership to have it deleted by the last GC run.
2413 QJSEngine::setObjectOwnership(qtObject, QJSEngine::JavaScriptOwnership);
2414 }
2415
2416 QV4::ScopedObject qtObjectWrapper(
2417 scope, QV4::QObjectWrapper::wrap(this, qtObject));
2418 QV4::ScopedObject qtNamespaceWrapper(
2419 scope, QV4::QMetaObjectWrapper::create(this, &Qt::staticMetaObject));
2420 QV4::ScopedObject qtObjectProtoWrapper(
2421 scope, qtObjectWrapper->getPrototypeOf());
2422
2423 qtNamespaceWrapper->setPrototypeOf(qtObjectProtoWrapper);
2424 qtObjectWrapper->setPrototypeOf(qtNamespaceWrapper);
2425
2426 globalObject->defineDefaultProperty(QStringLiteral("Qt"), qtObjectWrapper);
2427}
2428
2429void ExecutionEngine::setQmlEngine(QQmlEngine *engine)
2430{
2431 // Second stage of initialization. We're updating some more prototypes here.
2432 isInitialized = false;
2433 m_qmlEngine = engine;
2434 initQmlGlobalObject();
2435 isInitialized = true;
2436}
2437
2438static void freeze_recursive(QV4::ExecutionEngine *v4, QV4::Object *object)
2439{
2440 if (object->as<QV4::QObjectWrapper>() || object->internalClass()->isFrozen())
2441 return;
2442
2443 QV4::Scope scope(v4);
2444
2445 bool instanceOfObject = false;
2446 QV4::ScopedObject p(scope, object->getPrototypeOf());
2447 while (p) {
2448 if (p->d() == v4->objectPrototype()->d()) {
2449 instanceOfObject = true;
2450 break;
2451 }
2452 p = p->getPrototypeOf();
2453 }
2454 if (!instanceOfObject)
2455 return;
2456
2457 Heap::InternalClass *frozen = object->internalClass()->frozen();
2458 object->setInternalClass(frozen); // Immediately assign frozen to prevent it from getting GC'd
2459
2460 QV4::ScopedObject o(scope);
2461 for (uint i = 0; i < frozen->size; ++i) {
2462 if (!frozen->nameMap.at(i).isStringOrSymbol())
2463 continue;
2464 o = *object->propertyData(i);
2465 if (o)
2466 freeze_recursive(v4, o);
2467 }
2468}
2469
2470void ExecutionEngine::freezeObject(const QV4::Value &value)
2471{
2472 QV4::Scope scope(this);
2473 QV4::ScopedObject o(scope, value);
2474 freeze_recursive(this, o);
2475}
2476
2477void ExecutionEngine::lockObject(const QV4::Value &value)
2478{
2479 QV4::Scope scope(this);
2480 ScopedObject object(scope, value);
2481 if (!object)
2482 return;
2483
2484 std::vector<Heap::Object *> stack { object->d() };
2485
2486 // Methods meant to be overridden
2487 const PropertyKey writableMembers[] = {
2488 id_toString()->propertyKey(),
2489 id_toLocaleString()->propertyKey(),
2490 id_valueOf()->propertyKey(),
2491 id_constructor()->propertyKey()
2492 };
2493 const auto writableBegin = std::begin(writableMembers);
2494 const auto writableEnd = std::end(writableMembers);
2495
2496 while (!stack.empty()) {
2497 object = stack.back();
2498 stack.pop_back();
2499
2500 if (object->as<QV4::QObjectWrapper>() || object->internalClass()->isLocked())
2501 continue;
2502
2503 Scoped<InternalClass> locked(scope, object->internalClass()->locked());
2504 QV4::ScopedObject member(scope);
2505
2506 // Taking this copy is cheap. It's refcounted. This avoids keeping a reference
2507 // to the original IC.
2508 const SharedInternalClassData<PropertyKey> nameMap = locked->d()->nameMap;
2509
2510 for (uint i = 0, end = locked->d()->size; i < end; ++i) {
2511 const PropertyKey key = nameMap.at(i);
2512 if (!key.isStringOrSymbol())
2513 continue;
2514 if ((member = *object->propertyData(i))) {
2515 stack.push_back(member->d());
2516 if (std::find(writableBegin, writableEnd, key) == writableEnd) {
2517 PropertyAttributes attributes = locked->d()->find(key).attributes;
2518 attributes.setConfigurable(false);
2519 attributes.setWritable(false);
2520 locked = locked->changeMember(key, attributes);
2521 }
2522 }
2523 }
2524
2525 object->setInternalClass(locked->d());
2526 }
2527}
2528
2529void ExecutionEngine::startTimer(const QString &timerName)
2530{
2531 if (!m_time.isValid())
2532 m_time.start();
2533 m_startedTimers[timerName] = m_time.elapsed();
2534}
2535
2536qint64 ExecutionEngine::stopTimer(const QString &timerName, bool *wasRunning)
2537{
2538 if (!m_startedTimers.contains(timerName)) {
2539 *wasRunning = false;
2540 return 0;
2541 }
2542 *wasRunning = true;
2543 qint64 startedAt = m_startedTimers.take(timerName);
2544 return m_time.elapsed() - startedAt;
2545}
2546
2547int ExecutionEngine::consoleCountHelper(const QString &file, quint16 line, quint16 column)
2548{
2549 const QString key = file + QString::number(line) + QString::number(column);
2550 int number = m_consoleCount.value(key, 0);
2551 number++;
2552 m_consoleCount.insert(key, number);
2553 return number;
2554}
2555
2556void ExecutionEngine::setExtensionData(int index, Deletable *data)
2557{
2558 if (m_extensionData.size() <= index)
2559 m_extensionData.resize(index + 1);
2560
2561 if (m_extensionData.at(index))
2562 delete m_extensionData.at(index);
2563
2564 m_extensionData[index] = data;
2565}
2566
2567template<typename Source>
2568bool convertToIterable(QMetaType metaType, void *data, Source *sequence)
2569{
2570 QMetaSequence::Iterable iterable;
2571 if (!QMetaType::view(metaType, data, QMetaType::fromType<QMetaSequence::Iterable>(), &iterable))
2572 return false;
2573
2574 // Clear the sequence before appending. There may be stale data in there.
2575 metaType.destruct(data);
2576 metaType.construct(data);
2577
2578 QV4::Scope scope(sequence->engine());
2579 QV4::ScopedValue v(scope);
2580
2581 const QMetaType elementMetaType = iterable.metaContainer().valueMetaType();
2582 QVariant element;
2583 void *elementData = nullptr;
2584 if (elementMetaType == QMetaType::fromType<QVariant>()) {
2585 elementData = &element;
2586 } else {
2587 element = QVariant(elementMetaType);
2588 elementData = element.data();
2589 }
2590
2591 for (qsizetype i = 0, end = sequence->getLength(); i < end; ++i) {
2592 v = sequence->get(i);
2593 ExecutionEngine::metaTypeFromJS(v, elementMetaType, elementData);
2594 iterable.append(element);
2595 }
2596
2597 return true;
2598}
2599
2600/*!
2601 * \internal
2602 *
2603 * Converts a JS value to a meta-type.
2604 * \a data must point to a default-constructed instance of \a metaType.
2605 * Returns \c true if conversion succeeded, \c false otherwise. In the latter case,
2606 * \a data is not modified.
2607 */
2608bool ExecutionEngine::metaTypeFromJS(const Value &value, QMetaType metaType, void *data)
2609{
2610 // check if it's one of the types we know
2611 switch (metaType.id()) {
2612 case QMetaType::Bool:
2613 *reinterpret_cast<bool*>(data) = value.toBoolean();
2614 return true;
2615 case QMetaType::Int:
2616 *reinterpret_cast<int*>(data) = value.toInt32();
2617 return true;
2618 case QMetaType::UInt:
2619 *reinterpret_cast<uint*>(data) = value.toUInt32();
2620 return true;
2621 case QMetaType::Long:
2622 *reinterpret_cast<long*>(data) = long(value.toInteger());
2623 return true;
2624 case QMetaType::ULong:
2625 *reinterpret_cast<ulong*>(data) = ulong(value.toInteger());
2626 return true;
2627 case QMetaType::LongLong:
2628 *reinterpret_cast<qlonglong*>(data) = qlonglong(value.toInteger());
2629 return true;
2630 case QMetaType::ULongLong:
2631 *reinterpret_cast<qulonglong*>(data) = qulonglong(value.toInteger());
2632 return true;
2633 case QMetaType::Double:
2634 *reinterpret_cast<double*>(data) = value.toNumber();
2635 return true;
2636 case QMetaType::QString:
2637 if (value.isUndefined())
2638 *reinterpret_cast<QString*>(data) = QStringLiteral("undefined");
2639 else if (value.isNull())
2640 *reinterpret_cast<QString*>(data) = QStringLiteral("null");
2641 else
2642 *reinterpret_cast<QString*>(data) = value.toQString();
2643 return true;
2644 case QMetaType::QByteArray:
2645 if (const ArrayBuffer *ab = value.as<ArrayBuffer>()) {
2646 *reinterpret_cast<QByteArray*>(data) = ab->asByteArray();
2647 } else if (const String *string = value.as<String>()) {
2648 *reinterpret_cast<QByteArray*>(data) = string->toQString().toUtf8();
2649 } else if (const ArrayObject *ao = value.as<ArrayObject>()) {
2650 // Since QByteArray is sequentially iterable, we have to construct it from a JS Array.
2651 QByteArray result;
2652 const qint64 length = ao->getLength();
2653 result.reserve(length);
2654 QV4::Scope scope(ao->engine());
2655 QV4::ScopedValue v(scope);
2656 for (qint64 i = 0; i < length; ++i) {
2657 char value = 0;
2658 v = ao->get(i);
2659 ExecutionEngine::metaTypeFromJS(v, QMetaType::fromType<char>(), &value);
2660 result.push_back(value);
2661 }
2662 *reinterpret_cast<QByteArray*>(data) = std::move(result);
2663 } else {
2664 *reinterpret_cast<QByteArray*>(data) = QByteArray();
2665 }
2666 return true;
2667 case QMetaType::Float:
2668 *reinterpret_cast<float*>(data) = value.toNumber();
2669 return true;
2670 case QMetaType::Short:
2671 *reinterpret_cast<short*>(data) = short(value.toInt32());
2672 return true;
2673 case QMetaType::UShort:
2674 *reinterpret_cast<unsigned short*>(data) = value.toUInt16();
2675 return true;
2676 case QMetaType::Char:
2677 *reinterpret_cast<char*>(data) = char(value.toInt32());
2678 return true;
2679 case QMetaType::UChar:
2680 *reinterpret_cast<unsigned char*>(data) = (unsigned char)(value.toInt32());
2681 return true;
2682 case QMetaType::SChar:
2683 *reinterpret_cast<signed char*>(data) = (signed char)(value.toInt32());
2684 return true;
2685 case QMetaType::QChar:
2686 if (String *s = value.stringValue()) {
2687 QString str = s->toQString();
2688 *reinterpret_cast<QChar*>(data) = str.isEmpty() ? QChar() : str.at(0);
2689 } else {
2690 *reinterpret_cast<QChar*>(data) = QChar(ushort(value.toUInt16()));
2691 }
2692 return true;
2693 case QMetaType::QDateTime:
2694 if (const QV4::DateObject *d = value.as<DateObject>()) {
2695 *reinterpret_cast<QDateTime *>(data) = d->toQDateTime();
2696 return true;
2697 } break;
2698 case QMetaType::QDate:
2699 if (const QV4::DateObject *d = value.as<DateObject>()) {
2700 *reinterpret_cast<QDate *>(data) = DateObject::dateTimeToDate(d->toQDateTime());
2701 return true;
2702 } break;
2703 case QMetaType::QTime:
2704 if (const QV4::DateObject *d = value.as<DateObject>()) {
2705 *reinterpret_cast<QTime *>(data) = d->toQDateTime().time();
2706 return true;
2707 } break;
2708 case QMetaType::QUrl:
2709 if (String *s = value.stringValue()) {
2710 *reinterpret_cast<QUrl *>(data) = QUrl(s->toQString());
2711 return true;
2712 } else if (const QV4::UrlObject *d = value.as<UrlObject>()) {
2713 *reinterpret_cast<QUrl *>(data) = d->toQUrl();
2714 return true;
2715 } else if (const QV4::VariantObject *d = value.as<VariantObject>()) {
2716 const QVariant *variant = &d->d()->data();
2717 if (variant->metaType() == QMetaType::fromType<QUrl>()) {
2718 *reinterpret_cast<QUrl *>(data)
2719 = *reinterpret_cast<const QUrl *>(variant->constData());
2720 return true;
2721 }
2722 }
2723 break;
2724#if QT_CONFIG(regularexpression)
2725 case QMetaType::QRegularExpression:
2726 if (const QV4::RegExpObject *r = value.as<QV4::RegExpObject>()) {
2727 *reinterpret_cast<QRegularExpression *>(data) = r->toQRegularExpression();
2728 return true;
2729 } break;
2730#endif
2731 case QMetaType::QObjectStar: {
2732 if (value.isNull()) {
2733 *reinterpret_cast<QObject* *>(data) = nullptr;
2734 return true;
2735 }
2736 if (value.as<QV4::QObjectWrapper>()) {
2737 *reinterpret_cast<QObject* *>(data) = qtObjectFromJS(value);
2738 return true;
2739 }
2740 break;
2741 }
2742 case QMetaType::QStringList: {
2743 const QV4::ArrayObject *a = value.as<QV4::ArrayObject>();
2744 if (a) {
2745 *reinterpret_cast<QStringList *>(data) = a->toQStringList();
2746 return true;
2747 }
2748 break;
2749 }
2750 case QMetaType::QVariantList: {
2751 const QV4::ArrayObject *a = value.as<QV4::ArrayObject>();
2752 if (a) {
2753 *reinterpret_cast<QVariantList *>(data) = ExecutionEngine::toVariant(
2754 *a, /*typeHint*/QMetaType{}, /*createJSValueForObjectsAndSymbols*/false)
2755 .toList();
2756 return true;
2757 }
2758 break;
2759 }
2760 case QMetaType::QVariantMap: {
2761 const QV4::Object *o = value.as<QV4::Object>();
2762 if (o) {
2763 *reinterpret_cast<QVariantMap *>(data) = o->engine()->variantMapFromJS(o);
2764 return true;
2765 }
2766 break;
2767 }
2768 case QMetaType::QVariant:
2769 if (value.as<QV4::Managed>()) {
2770 *reinterpret_cast<QVariant*>(data) = ExecutionEngine::toVariant(
2771 value, /*typeHint*/QMetaType{}, /*createJSValueForObjectsAndSymbols*/false);
2772 } else if (value.isNull()) {
2773 *reinterpret_cast<QVariant*>(data) = QVariant::fromValue(nullptr);
2774 } else if (value.isUndefined()) {
2775 *reinterpret_cast<QVariant*>(data) = QVariant();
2776 } else if (value.isBoolean()) {
2777 *reinterpret_cast<QVariant*>(data) = QVariant(value.booleanValue());
2778 } else if (value.isInteger()) {
2779 *reinterpret_cast<QVariant*>(data) = QVariant(value.integerValue());
2780 } else if (value.isDouble()) {
2781 *reinterpret_cast<QVariant*>(data) = QVariant(value.doubleValue());
2782 }
2783 return true;
2784 case QMetaType::QJsonValue:
2785 *reinterpret_cast<QJsonValue *>(data) = QV4::JsonObject::toJsonValue(value);
2786 return true;
2787 case QMetaType::QJsonObject: {
2788 *reinterpret_cast<QJsonObject *>(data) = QV4::JsonObject::toJsonObject(value.as<Object>());
2789 return true;
2790 }
2791 case QMetaType::QJsonArray: {
2792 *reinterpret_cast<QJsonArray *>(data) = QV4::JsonObject::toJsonArray(value.as<Object>());
2793 return true;
2794 }
2795 default:
2796 break;
2797 }
2798
2799 if (metaType.flags() & QMetaType::IsEnumeration) {
2800 // underlyingType() is invalid only for enumerations of unsupported size.
2801 // Those won't be useful anyway.
2802 if (const QMetaType underlyingType = metaType.underlyingType(); underlyingType.isValid())
2803 return metaTypeFromJS(value, underlyingType, data);
2804 return false;
2805 }
2806
2807 if (const QV4::QmlListWrapper *wrapper = value.as<QV4::QmlListWrapper>()) {
2808 if (metaType == QMetaType::fromType<QQmlListReference>()) {
2809 *reinterpret_cast<QQmlListReference *>(data) = wrapper->toListReference();
2810 return true;
2811 }
2812
2813 const auto wrapperPrivate = wrapper->d();
2814 if (metaType == QMetaType::fromType<QQmlListProperty<QObject> *>()
2815 || metaType == wrapperPrivate->propertyType()) {
2816 *reinterpret_cast<QQmlListProperty<QObject> *>(data) = *wrapperPrivate->property();
2817 return true;
2818 }
2819
2820 if (metaType == QMetaType::fromType<QObjectList>()) {
2821 *reinterpret_cast<QObjectList *>(data)
2822 = wrapperPrivate->property()->toList<QObjectList>();
2823 return true;
2824 }
2825
2826 if (convertToIterable(metaType, data, wrapper))
2827 return true;
2828 }
2829
2830 if (const QQmlValueTypeWrapper *vtw = value.as<QQmlValueTypeWrapper>()) {
2831 const QMetaType valueType = vtw->type();
2832 if (valueType == metaType)
2833 return vtw->toGadget(data);
2834
2835 Heap::QQmlValueTypeWrapper *d = vtw->d();
2836 if (d->isReference())
2837 d->readReference();
2838
2839 if (void *gadgetPtr = d->gadgetPtr()) {
2840 if (QQmlValueTypeProvider::populateValueType(
2841 metaType, data, valueType, gadgetPtr, vtw->engine())) {
2842 return true;
2843 }
2844 if (QMetaType::canConvert(valueType, metaType))
2845 return QMetaType::convert(valueType, gadgetPtr, metaType, data);
2846 } else {
2847 QVariant empty(valueType);
2848 if (QQmlValueTypeProvider::populateValueType(
2849 metaType, data, valueType, empty.data(), vtw->engine())) {
2850 return true;
2851 }
2852 if (QMetaType::canConvert(valueType, metaType))
2853 return QMetaType::convert(valueType, empty.data(), metaType, data);
2854 }
2855 }
2856
2857 // Try to use magic; for compatibility with qjsvalue_cast.
2858
2859 if (convertToNativeQObject(value, metaType, reinterpret_cast<void **>(data)))
2860 return true;
2861
2862 const bool isPointer = (metaType.flags() & QMetaType::IsPointer);
2863 const QV4::VariantObject *variantObject = value.as<QV4::VariantObject>();
2864 if (variantObject) {
2865 // Actually a reference, because we're poking it for its data() below and we want
2866 // the _original_ data, not some copy.
2867 QVariant &var = variantObject->d()->data();
2868
2869 if (var.metaType() == metaType) {
2870 metaType.destruct(data);
2871 metaType.construct(data, var.data());
2872 return true;
2873 }
2874
2875 if (isPointer) {
2876 const QByteArray pointedToTypeName = QByteArray(metaType.name()).chopped(1);
2877 const QMetaType valueType = QMetaType::fromName(pointedToTypeName);
2878
2879 if (valueType == var.metaType()) {
2880 // ### Qt7: Remove this. Returning pointers to potentially gc'd data is crazy.
2881 // We have T t, T* is requested, so return &t.
2882 *reinterpret_cast<const void **>(data) = var.data();
2883 return true;
2884 } else if (Object *o = value.objectValue()) {
2885 // Look in the prototype chain.
2886 QV4::Scope scope(o->engine());
2887 QV4::ScopedObject proto(scope, o->getPrototypeOf());
2888 while (proto) {
2889 bool canCast = false;
2890 if (QV4::VariantObject *vo = proto->as<QV4::VariantObject>()) {
2891 const QVariant &v = vo->d()->data();
2892 canCast = (metaType == v.metaType());
2893 }
2894 else if (proto->as<QV4::QObjectWrapper>()) {
2895 QV4::ScopedObject p(scope, proto.getPointer());
2896 if (QObject *qobject = qtObjectFromJS(p)) {
2897 if (const QMetaObject *metaObject = metaType.metaObject())
2898 canCast = metaObject->cast(qobject) != nullptr;
2899 else
2900 canCast = qobject->qt_metacast(pointedToTypeName);
2901 }
2902 }
2903 if (canCast) {
2904 const QMetaType varType = var.metaType();
2905 if (varType.flags() & QMetaType::IsPointer) {
2906 *reinterpret_cast<const void **>(data)
2907 = *reinterpret_cast<void *const *>(var.data());
2908 } else {
2909 *reinterpret_cast<const void **>(data) = var.data();
2910 }
2911 return true;
2912 }
2913 proto = proto->getPrototypeOf();
2914 }
2915 }
2916 } else if (QQmlValueTypeProvider::populateValueType(
2917 metaType, data, var.metaType(), var.data(), variantObject->engine())) {
2918 return true;
2919 }
2920 } else if (value.isNull() && isPointer) {
2921 *reinterpret_cast<void* *>(data) = nullptr;
2922 return true;
2923 } else if (metaType == QMetaType::fromType<QJSValue>()) {
2924 QJSValuePrivate::setValue(reinterpret_cast<QJSValue*>(data), value);
2925 return true;
2926 } else if (metaType == QMetaType::fromType<QJSPrimitiveValue>()) {
2927 *reinterpret_cast<QJSPrimitiveValue *>(data) = createPrimitive(&value);
2928 return true;
2929 } else if (metaType == QMetaType::fromType<QJSManagedValue>()) {
2930 QJSManagedValue *managedData = reinterpret_cast<QJSManagedValue *>(data);
2931
2932 const Managed *managedValue = value.as<Managed>();
2933 if (Value *d = QJSManagedValuePrivate::member(managedData)) {
2934 // If the QJSManagedValue has an engine already,
2935 // we can assign a primitive without risking crosstalk between engines.
2936 if (!managedValue) {
2937 *d = value;
2938 return true;
2939 }
2940
2941 // If the engines match, we don't have to allocate a new persistent value
2942 if (reinterpret_cast<const Managed *>(d)->engine() == managedValue->engine()) {
2943 *d = value;
2944 return true;
2945 }
2946 }
2947
2948 if (managedValue) {
2949 // If value is itself managed, we create a new QJSManagedValue
2950 // to make sure the engine matches.
2951 *managedData = QJSManagedValuePrivate::create(*managedValue);
2952 return true;
2953 }
2954
2955 // The default-constructed QJSManagedValue (without engine) equals undefined.
2956 // So we can get away with doing nothing in this case.
2957 if (value.isUndefined())
2958 return true;
2959
2960 // Otherwise we can't do it. We need an engine from somewhere.
2961 return false;
2962 } else if (!isPointer) {
2963 const QV4::Managed *managed = value.as<QV4::Managed>();
2964 if (QQmlValueTypeProvider::populateValueType(
2965 metaType, data, value, managed ? managed->engine() : nullptr)) {
2966 return true;
2967 }
2968 }
2969
2970 if (const QV4::Sequence *sequence = value.as<Sequence>()) {
2971 const QVariant result = QV4::SequencePrototype::toVariant(sequence);
2972 if (result.metaType() == metaType) {
2973 metaType.destruct(data);
2974 metaType.construct(data, result.constData());
2975 return true;
2976 }
2977
2978 if (convertToIterable(metaType, data, sequence))
2979 return true;
2980 }
2981
2982 if (const QV4::ArrayObject *array = value.as<ArrayObject>()) {
2983 if (convertToIterable(metaType, data, array))
2984 return true;
2985 }
2986
2987 return false;
2988}
2989
2990static bool convertToNativeQObject(const QV4::Value &value, QMetaType targetType, void **result)
2991{
2992 if (!(targetType.flags() & QMetaType::IsPointer))
2993 return false;
2994 if (QObject *qobject = qtObjectFromJS(value)) {
2995 // If the target type has a metaObject, use that for casting.
2996 if (const QMetaObject *targetMetaObject = targetType.metaObject()) {
2997 if (QObject *instance = targetMetaObject->cast(qobject)) {
2998 *result = instance;
2999 return true;
3000 }
3001 return false;
3002 }
3003
3004 // We have to call the generated qt_metacast rather than metaObject->cast() here so that
3005 // it works for types without QMetaObject, such as QStandardItem.
3006 const QByteArray targetTypeName = targetType.name();
3007 const int start = targetTypeName.startsWith("const ") ? 6 : 0;
3008 const QByteArray className = targetTypeName.mid(start, targetTypeName.size() - start - 1);
3009 if (void *instance = qobject->qt_metacast(className)) {
3010 *result = instance;
3011 return true;
3012 }
3013 }
3014 return false;
3015}
3016
3017static QObject *qtObjectFromJS(const QV4::Value &value)
3018{
3019 if (!value.isObject())
3020 return nullptr;
3021
3022 QV4::Scope scope(value.as<QV4::Managed>()->engine());
3023 QV4::Scoped<QV4::VariantObject> v(scope, value);
3024
3025 if (v) {
3026 QVariant variant = v->d()->data();
3027 int type = variant.userType();
3028 if (type == QMetaType::QObjectStar)
3029 return *reinterpret_cast<QObject* const *>(variant.constData());
3030 }
3031 QV4::Scoped<QV4::QObjectWrapper> wrapper(scope, value);
3032 if (wrapper)
3033 return wrapper->object();
3034
3035 QV4::Scoped<QV4::QQmlTypeWrapper> typeWrapper(scope, value);
3036 if (typeWrapper)
3037 return typeWrapper->object();
3038
3039 return nullptr;
3040}
3041
3050
3051QMutex *ExecutionEngine::registrationMutex()
3052{
3053 return &registrationData()->mutex;
3054}
3055
3056int ExecutionEngine::registerExtension()
3057{
3058 return registrationData()->extensionCount++;
3059}
3060
3061QT_END_NAMESPACE
Combined button and popup list for selecting options.
Definition qjsvalue.h:24
static char * v4StackTrace(const ExecutionContext *context)
static bool globalNamesAreStaticallyKnown(QV4::Object *globalObject)
static QObject * qtObjectFromJS(const QV4::Value &value)
static QVariant objectToVariant(const QV4::Object *o, V4ObjectSet *visitedObjects=nullptr, JSToQVariantConversionBehavior behavior=JSToQVariantConversionBehavior::Safish)
Q_QML_EXPORT char * qt_v4StackTraceForEngine(void *executionEngine)
DEFINE_BOOL_CONFIG_OPTION(forceDiskCache, QML_FORCE_DISK_CACHE)
static void freeze_recursive(QV4::ExecutionEngine *v4, QV4::Object *object)
ReturnType convertJSValueToVariantType(const QJSValue &value)
static QVariant toVariant(const QV4::Value &value, QMetaType typeHint, JSToQVariantConversionBehavior conversionBehavior, V4ObjectSet *visitedObjects)
JSToQVariantConversionBehavior
static QtMetaContainerPrivate::QMetaSequenceInterface emptySequenceInterface()
static ExecutionEngine::DiskCacheOptions transFormDiskCache(const char *v)
Q_GLOBAL_STATIC(QV4EngineRegistrationData, registrationData)
static QtMetaContainerPrivate::QMetaSequenceInterface sequenceInterface()
Q_QML_EXPORT char * qt_v4StackTrace(void *executionContext)
static bool convertToNativeQObject(const QV4::Value &value, QMetaType targetType, void **result)
Association objectToVariantAssociation(const QV4::Object *o, V4ObjectSet *visitedObjects, JSToQVariantConversionBehavior conversionBehvior)
static QMetaSequence::Iterable jsvalueToSequence(const QJSValue &value)
bool convertToIterable(QMetaType metaType, void *data, Source *sequence)
QSet< QV4::Heap::Object * > V4ObjectSet
ReturnedValue throwTypeError(const FunctionObject *b, const QV4::Value *, const QV4::Value *, int)
QJSValue const * data