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
qv4compiler.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// Copyright (C) 2018 Intel Corporation.
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
4// Qt-Security score:significant
5
6#include <qv4compiler_p.h>
7#include <qv4codegen_p.h>
8#include <private/qv4compileddata_p.h>
9#include <private/qv4staticvalue_p.h>
10#include <private/qv4alloca_p.h>
11#include <private/qqmljslexer_p.h>
12#include <private/qqmljsast_p.h>
13#include <private/qqmlirbuilder_p.h>
14#include <QCryptographicHash>
15#include <QtEndian>
16
17// Efficient implementation that takes advantage of powers of two.
18
20namespace QtPrivate { // Disambiguate from WTF::roundUpToMultipleOf
21static inline size_t roundUpToMultipleOf(size_t divisor, size_t x)
22{
23 Q_ASSERT(divisor && !(divisor & (divisor - 1)));
24 const size_t remainderMask = divisor - 1;
25 return (x + remainderMask) & ~remainderMask;
26}
27}
28QT_END_NAMESPACE
29
30QV4::Compiler::StringTableGenerator::StringTableGenerator()
31{
32 clear();
33}
34
35int QV4::Compiler::StringTableGenerator::registerString(const QString &str)
36{
37 Q_ASSERT(!frozen);
38 QHash<QString, int>::ConstIterator it = stringToId.constFind(str);
39 if (it != stringToId.cend())
40 return *it;
41 stringToId.insert(str, strings.size());
42 strings.append(str);
43 stringDataSize += QV4::CompiledData::String::calculateSize(str);
44 return strings.size() - 1;
45}
46
47int QV4::Compiler::StringTableGenerator::getStringId(const QString &string) const
48{
49 Q_ASSERT(stringToId.contains(string));
50 return stringToId.value(string);
51}
52
53void QV4::Compiler::StringTableGenerator::clear()
54{
55 strings.clear();
56 stringToId.clear();
57 stringDataSize = 0;
58 frozen = false;
59}
60
61void QV4::Compiler::StringTableGenerator::initializeFromBackingUnit(const QV4::CompiledData::Unit *unit)
62{
63 clear();
64 for (uint i = 0; i < unit->stringTableSize; ++i)
65 registerString(unit->stringAtInternal(i));
66 backingUnitTableSize = unit->stringTableSize;
67 stringDataSize = 0;
68}
69
70void QV4::Compiler::StringTableGenerator::serialize(CompiledData::Unit *unit)
71{
72 char *dataStart = reinterpret_cast<char *>(unit);
73 quint32_le *stringTable = reinterpret_cast<quint32_le *>(dataStart + unit->offsetToStringTable);
74 char *stringData = reinterpret_cast<char *>(stringTable)
75 + QtPrivate::roundUpToMultipleOf(8, unit->stringTableSize * sizeof(uint));
76 for (int i = backingUnitTableSize ; i < strings.size(); ++i) {
77 const int index = i - backingUnitTableSize;
78 stringTable[index] = stringData - dataStart;
79 const QString &qstr = strings.at(i);
80
81 QV4::CompiledData::String *s = reinterpret_cast<QV4::CompiledData::String *>(stringData);
82 Q_ASSERT(reinterpret_cast<uintptr_t>(s) % alignof(QV4::CompiledData::String) == 0);
83 Q_ASSERT(qstr.size() >= 0);
84 s->size = qstr.size();
85
86 ushort *uc = reinterpret_cast<ushort *>(reinterpret_cast<char *>(s) + sizeof(*s));
87 qToLittleEndian<ushort>(qstr.constData(), s->size, uc);
88 uc[s->size] = 0;
89
90 stringData += QV4::CompiledData::String::calculateSize(qstr);
91 }
92}
93
94void QV4::Compiler::JSUnitGenerator::generateUnitChecksum(QV4::CompiledData::Unit *unit)
95{
96#ifndef QT_CRYPTOGRAPHICHASH_ONLY_SHA1
97 QCryptographicHash hash(QCryptographicHash::Md5);
98
99 const int checksummableDataOffset
100 = offsetof(QV4::CompiledData::Unit, md5Checksum) + sizeof(unit->md5Checksum);
101
102 const char *dataPtr = reinterpret_cast<const char *>(unit) + checksummableDataOffset;
103 hash.addData({dataPtr, qsizetype(unit->unitSize - checksummableDataOffset)});
104
105 QByteArray checksum = hash.result();
106 Q_ASSERT(checksum.size() == sizeof(unit->md5Checksum));
107 memcpy(unit->md5Checksum, checksum.constData(), sizeof(unit->md5Checksum));
108#else
109 memset(unit->md5Checksum, 0, sizeof(unit->md5Checksum));
110#endif
111}
112
113QV4::Compiler::JSUnitGenerator::JSUnitGenerator(QV4::Compiler::Module *module)
114 : module(module)
115{
116 // Make sure the empty string always gets index 0
117 registerString(QString());
118}
119
120int QV4::Compiler::JSUnitGenerator::registerGetterLookup(const QString &name, LookupMode mode)
121{
122 return registerGetterLookup(registerString(name), mode);
123}
124
125static QV4::CompiledData::Lookup::Mode lookupMode(QV4::Compiler::JSUnitGenerator::LookupMode mode)
126{
127 return mode == QV4::Compiler::JSUnitGenerator::LookupForCall
128 ? QV4::CompiledData::Lookup::Mode_ForCall
129 : QV4::CompiledData::Lookup::Mode_ForStorage;
130}
131
132int QV4::Compiler::JSUnitGenerator::registerGetterLookup(int nameIndex, LookupMode mode)
133{
134 lookups << CompiledData::Lookup(
135 CompiledData::Lookup::Type_Getter, lookupMode(mode), nameIndex);
136 return lookups.size() - 1;
137}
138
139int QV4::Compiler::JSUnitGenerator::registerSetterLookup(const QString &name)
140{
141 return registerSetterLookup(registerString(name));
142}
143
144int QV4::Compiler::JSUnitGenerator::registerSetterLookup(int nameIndex)
145{
146 lookups << CompiledData::Lookup(
147 CompiledData::Lookup::Type_Setter,
148 CompiledData::Lookup::Mode_ForStorage, nameIndex);
149 return lookups.size() - 1;
150}
151
152int QV4::Compiler::JSUnitGenerator::registerGlobalGetterLookup(int nameIndex, LookupMode mode)
153{
154 lookups << CompiledData::Lookup(
155 CompiledData::Lookup::Type_GlobalGetter, lookupMode(mode), nameIndex);
156 return lookups.size() - 1;
157}
158
159int QV4::Compiler::JSUnitGenerator::registerQmlContextPropertyGetterLookup(
160 int nameIndex, LookupMode mode)
161{
162 lookups << CompiledData::Lookup(
163 CompiledData::Lookup::Type_QmlContextPropertyGetter, lookupMode(mode),
164 nameIndex);
165 return lookups.size() - 1;
166}
167
168int QV4::Compiler::JSUnitGenerator::registerRegExp(QQmlJS::AST::RegExpLiteral *regexp)
169{
170 quint32 flags = 0;
171 if (regexp->flags & QQmlJS::Lexer::RegExp_Global)
172 flags |= CompiledData::RegExp::RegExp_Global;
173 if (regexp->flags & QQmlJS::Lexer::RegExp_IgnoreCase)
174 flags |= CompiledData::RegExp::RegExp_IgnoreCase;
175 if (regexp->flags & QQmlJS::Lexer::RegExp_Multiline)
176 flags |= CompiledData::RegExp::RegExp_Multiline;
177 if (regexp->flags & QQmlJS::Lexer::RegExp_Unicode)
178 flags |= CompiledData::RegExp::RegExp_Unicode;
179 if (regexp->flags & QQmlJS::Lexer::RegExp_Sticky)
180 flags |= CompiledData::RegExp::RegExp_Sticky;
181
182 regexps.append(CompiledData::RegExp(flags, registerString(regexp->pattern.toString())));
183 return regexps.size() - 1;
184}
185
186int QV4::Compiler::JSUnitGenerator::registerConstant(QV4::ReturnedValue v)
187{
188 int idx = constants.indexOf(v);
189 if (idx >= 0)
190 return idx;
191 constants.append(v);
192 return constants.size() - 1;
193}
194
195QV4::ReturnedValue QV4::Compiler::JSUnitGenerator::constant(int idx) const
196{
197 return constants.at(idx);
198}
199
200// The JSClass object and its members are stored contiguously in the jsClassData.
201// In order to get to the members you have to skip over the JSClass, therefore +1.
202static constexpr qsizetype jsClassMembersOffset = 1;
203
204int QV4::Compiler::JSUnitGenerator::registerJSClass(const QStringList &members)
205{
206 // ### re-use existing class definitions.
207
208 const int size = CompiledData::JSClass::calculateSize(members.size());
209 jsClassOffsets.append(jsClassData.size());
210 const int oldSize = jsClassData.size();
211 jsClassData.resize(jsClassData.size() + size);
212 memset(jsClassData.data() + oldSize, 0, size);
213
214 CompiledData::JSClass *jsClass = reinterpret_cast<CompiledData::JSClass*>(jsClassData.data() + oldSize);
215 jsClass->nMembers = members.size();
216 CompiledData::JSClassMember *member
217 = reinterpret_cast<CompiledData::JSClassMember*>(jsClass + jsClassMembersOffset);
218
219 for (const auto &name : members) {
220 member->set(registerString(name), false);
221 ++member;
222 }
223
224 return jsClassOffsets.size() - 1;
225}
226
227int QV4::Compiler::JSUnitGenerator::jsClassSize(int jsClassId) const
228{
229 const CompiledData::JSClass *jsClass
230 = reinterpret_cast<const CompiledData::JSClass*>(
231 jsClassData.data() + jsClassOffsets[jsClassId]);
232 return jsClass->nMembers;
233}
234
235QString QV4::Compiler::JSUnitGenerator::jsClassMember(int jsClassId, int member) const
236{
237 const CompiledData::JSClass *jsClass = reinterpret_cast<const CompiledData::JSClass*>(
238 jsClassData.data() + jsClassOffsets[jsClassId]);
239 Q_ASSERT(member >= 0);
240 Q_ASSERT(uint(member) < jsClass->nMembers);
241 const CompiledData::JSClassMember *members
242 = reinterpret_cast<const CompiledData::JSClassMember*>(jsClass + jsClassMembersOffset);
243 return stringForIndex(members[member].nameOffset());
244}
245
246int QV4::Compiler::JSUnitGenerator::registerTranslation(const QV4::CompiledData::TranslationData &translation)
247{
248 translations.append(translation);
249 return translations.size() - 1;
250}
251
252QV4::CompiledData::Unit *QV4::Compiler::JSUnitGenerator::generateUnit(GeneratorOption option)
253{
254 const auto registerTypeStrings = [this](QQmlJS::AST::Type *type) {
255 if (!type)
256 return;
257
258 if (type->typeArgument) {
259 registerString(type->typeArgument->toString());
260 registerString(type->typeId->toString());
261 }
262 registerString(type->toString());
263 };
264
265 registerString(module->fileName);
266 registerString(module->finalUrl);
267 for (Context *f : std::as_const(module->functions)) {
268 registerString(f->name);
269 registerTypeStrings(f->returnType);
270 for (int i = 0; i < f->arguments.size(); ++i) {
271 registerString(f->arguments.at(i).id);
272 if (const QQmlJS::AST::TypeAnnotation *annotation
273 = f->arguments.at(i).typeAnnotation.data()) {
274 registerTypeStrings(annotation->type);
275 }
276 }
277 for (int i = 0; i < f->locals.size(); ++i)
278 registerString(f->locals.at(i));
279 }
280 for (Context *c : std::as_const(module->blocks)) {
281 for (int i = 0; i < c->locals.size(); ++i)
282 registerString(c->locals.at(i));
283 }
284 {
285 const auto registerExportEntry = [this](const Compiler::ExportEntry &entry) {
286 registerString(entry.exportName);
287 registerString(entry.moduleRequest);
288 registerString(entry.importName);
289 registerString(entry.localName);
290 };
291 std::for_each(module->localExportEntries.constBegin(), module->localExportEntries.constEnd(), registerExportEntry);
292 std::for_each(module->indirectExportEntries.constBegin(), module->indirectExportEntries.constEnd(), registerExportEntry);
293 std::for_each(module->starExportEntries.constBegin(), module->starExportEntries.constEnd(), registerExportEntry);
294 }
295 {
296 for (const auto &entry: module->importEntries) {
297 registerString(entry.moduleRequest);
298 registerString(entry.importName);
299 registerString(entry.localName);
300 }
301
302 for (const QString &request: module->moduleRequests)
303 registerString(request);
304 }
305
306 Q_ALLOCA_VAR(quint32_le, blockClassAndFunctionOffsets, (module->functions.size() + module->classes.size() + module->templateObjects.size() + module->blocks.size()) * sizeof(quint32_le));
307 uint jsClassDataOffset = 0;
308
309 char *dataPtr;
310 CompiledData::Unit *unit;
311 {
312 QV4::CompiledData::Unit tempHeader = generateHeader(option, blockClassAndFunctionOffsets, &jsClassDataOffset);
313 dataPtr = reinterpret_cast<char *>(malloc(tempHeader.unitSize));
314 memset(dataPtr, 0, tempHeader.unitSize);
315 memcpy(&unit, &dataPtr, sizeof(CompiledData::Unit*));
316 memcpy(unit, &tempHeader, sizeof(tempHeader));
317 }
318
319 memcpy(dataPtr + unit->offsetToFunctionTable, blockClassAndFunctionOffsets, unit->functionTableSize * sizeof(quint32_le));
320 memcpy(dataPtr + unit->offsetToClassTable, blockClassAndFunctionOffsets + unit->functionTableSize, unit->classTableSize * sizeof(quint32_le));
321 memcpy(dataPtr + unit->offsetToTemplateObjectTable, blockClassAndFunctionOffsets + unit->functionTableSize + unit->classTableSize, unit->templateObjectTableSize * sizeof(quint32_le));
322 memcpy(dataPtr + unit->offsetToBlockTable, blockClassAndFunctionOffsets + unit->functionTableSize + unit->classTableSize + unit->templateObjectTableSize, unit->blockTableSize * sizeof(quint32_le));
323
324 for (int i = 0; i < module->functions.size(); ++i) {
325 Context *function = module->functions.at(i);
326 if (function == module->rootContext)
327 unit->indexOfRootFunction = i;
328
329 writeFunction(dataPtr + blockClassAndFunctionOffsets[i], function);
330 }
331
332 for (int i = 0; i < module->classes.size(); ++i) {
333 const Class &c = module->classes.at(i);
334
335 writeClass(dataPtr + blockClassAndFunctionOffsets[i + module->functions.size()], c);
336 }
337
338 for (int i = 0; i < module->templateObjects.size(); ++i) {
339 const TemplateObject &t = module->templateObjects.at(i);
340
341 writeTemplateObject(dataPtr + blockClassAndFunctionOffsets[i + module->functions.size() + module->classes.size()], t);
342 }
343
344 for (int i = 0; i < module->blocks.size(); ++i) {
345 Context *block = module->blocks.at(i);
346
347 writeBlock(dataPtr + blockClassAndFunctionOffsets[i + module->classes.size() + module->templateObjects.size() + module->functions.size()], block);
348 }
349
350 CompiledData::Lookup *lookupsToWrite = reinterpret_cast<CompiledData::Lookup*>(dataPtr + unit->offsetToLookupTable);
351 for (const CompiledData::Lookup &l : std::as_const(lookups))
352 *lookupsToWrite++ = l;
353
354 CompiledData::RegExp *regexpTable = reinterpret_cast<CompiledData::RegExp *>(dataPtr + unit->offsetToRegexpTable);
355 if (regexps.size())
356 memcpy(regexpTable, regexps.constData(), regexps.size() * sizeof(*regexpTable));
357
358#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
359 ReturnedValue *constantTable = reinterpret_cast<ReturnedValue *>(dataPtr + unit->offsetToConstantTable);
360 if (constants.size())
361 memcpy(constantTable, constants.constData(), constants.size() * sizeof(ReturnedValue));
362#else
363 quint64_le *constantTable = reinterpret_cast<quint64_le *>(dataPtr + unit->offsetToConstantTable);
364 for (int i = 0; i < constants.count(); ++i)
365 constantTable[i] = constants.at(i);
366#endif
367
368 {
369 if (jsClassData.size())
370 memcpy(dataPtr + jsClassDataOffset, jsClassData.constData(), jsClassData.size());
371
372 // write js classes and js class lookup table
373 quint32_le *jsClassOffsetTable = reinterpret_cast<quint32_le *>(dataPtr + unit->offsetToJSClassTable);
374 for (int i = 0; i < jsClassOffsets.size(); ++i)
375 jsClassOffsetTable[i] = jsClassDataOffset + jsClassOffsets.at(i);
376 }
377
378 if (translations.size()) {
379 memcpy(dataPtr + unit->offsetToTranslationTable, translations.constData(), translations.size() * sizeof(CompiledData::TranslationData));
380 }
381
382 {
383 const auto populateExportEntryTable = [this, dataPtr](const QList<Compiler::ExportEntry> &table, quint32_le offset) {
384 CompiledData::ExportEntry *entryToWrite = reinterpret_cast<CompiledData::ExportEntry *>(dataPtr + offset);
385 for (const Compiler::ExportEntry &entry: table) {
386 entryToWrite->exportName = getStringId(entry.exportName);
387 entryToWrite->moduleRequest = getStringId(entry.moduleRequest);
388 entryToWrite->importName = getStringId(entry.importName);
389 entryToWrite->localName = getStringId(entry.localName);
390 entryToWrite->location = entry.location;
391 entryToWrite++;
392 }
393 };
394 populateExportEntryTable(module->localExportEntries, unit->offsetToLocalExportEntryTable);
395 populateExportEntryTable(module->indirectExportEntries, unit->offsetToIndirectExportEntryTable);
396 populateExportEntryTable(module->starExportEntries, unit->offsetToStarExportEntryTable);
397 }
398
399 {
400 CompiledData::ImportEntry *entryToWrite = reinterpret_cast<CompiledData::ImportEntry *>(dataPtr + unit->offsetToImportEntryTable);
401 for (const Compiler::ImportEntry &entry: module->importEntries) {
402 entryToWrite->moduleRequest = getStringId(entry.moduleRequest);
403 entryToWrite->importName = getStringId(entry.importName);
404 entryToWrite->localName = getStringId(entry.localName);
405 entryToWrite->location = entry.location;
406 entryToWrite++;
407 }
408 }
409
410 {
411 quint32_le *moduleRequestEntryToWrite = reinterpret_cast<quint32_le *>(dataPtr + unit->offsetToModuleRequestTable);
412 for (const QString &moduleRequest: module->moduleRequests) {
413 *moduleRequestEntryToWrite = getStringId(moduleRequest);
414 moduleRequestEntryToWrite++;
415 }
416 }
417
418 // write strings and string table
419 if (option == GenerateWithStringTable)
420 stringTable.serialize(unit);
421
422 generateUnitChecksum(unit);
423
424 return unit;
425}
426
427void QV4::Compiler::JSUnitGenerator::writeFunction(char *f, QV4::Compiler::Context *irFunction) const
428{
429 QV4::CompiledData::Function *function = (QV4::CompiledData::Function *)f;
430
431 quint32 currentOffset = static_cast<quint32>(QtPrivate::roundUpToMultipleOf(8, sizeof(*function)));
432
433 function->nameIndex = getStringId(irFunction->name);
434 function->flags = 0;
435 if (irFunction->isStrict)
436 function->flags |= CompiledData::Function::IsStrict;
437 if (irFunction->isArrowFunction)
438 function->flags |= CompiledData::Function::IsArrowFunction;
439 if (irFunction->isGenerator)
440 function->flags |= CompiledData::Function::IsGenerator;
441 if (irFunction->returnsClosure)
442 function->flags |= CompiledData::Function::IsClosureWrapper;
443
444 if (!irFunction->returnsClosure
445 || (irFunction->usesArgumentsObject == Context::UsesArgumentsObject::Used)
446 || irFunction->innerFunctionAccessesThis
447 || irFunction->innerFunctionAccessesNewTarget) {
448 // If the inner function does things with this and new.target we need to do some work in
449 // the outer function. Then we shouldn't directly access the nested function.
450 function->nestedFunctionIndex = std::numeric_limits<uint32_t>::max();
451 } else {
452 // Otherwise we can directly use the nested function.
453 function->nestedFunctionIndex
454 = quint32(module->functions.indexOf(irFunction->nestedContexts.first()));
455 }
456
457 function->length = irFunction->formals ? irFunction->formals->length() : 0;
458 function->nFormals = irFunction->arguments.size();
459 function->formalsOffset = currentOffset;
460 currentOffset += function->nFormals * sizeof(CompiledData::Parameter);
461
462 const auto idGenerator = [this](const QString &str) { return getStringId(str); };
463
464 QmlIR::Parameter::initType(&function->returnType, idGenerator, irFunction->returnType);
465
466 function->sizeOfLocalTemporalDeadZone = irFunction->sizeOfLocalTemporalDeadZone;
467 function->sizeOfRegisterTemporalDeadZone = irFunction->sizeOfRegisterTemporalDeadZone;
468 function->firstTemporalDeadZoneRegister = irFunction->firstTemporalDeadZoneRegister;
469
470 function->nLocals = irFunction->locals.size();
471 function->localsOffset = currentOffset;
472 currentOffset += function->nLocals * sizeof(quint32);
473
474 function->nLineAndStatementNumbers
475 = irFunction->lineAndStatementNumberMapping.size();
476 Q_ASSERT(function->lineAndStatementNumberOffset() == currentOffset);
477 currentOffset += function->nLineAndStatementNumbers
478 * sizeof(CompiledData::CodeOffsetToLineAndStatement);
479
480 function->nRegisters = irFunction->registerCountInFunction;
481
482 if (!irFunction->labelInfo.empty()) {
483 function->nLabelInfos = quint32(irFunction->labelInfo.size());
484 Q_ASSERT(function->labelInfosOffset() == currentOffset);
485 currentOffset += function->nLabelInfos * sizeof(quint32);
486 }
487
488 function->location.set(irFunction->line, irFunction->column);
489
490 function->codeOffset = currentOffset;
491 function->codeSize = irFunction->code.size();
492
493 // write formals
494 CompiledData::Parameter *formals = (CompiledData::Parameter *)(f + function->formalsOffset);
495 for (int i = 0; i < irFunction->arguments.size(); ++i) {
496 auto *formal = &formals[i];
497 formal->nameIndex = getStringId(irFunction->arguments.at(i).id);
498 if (QQmlJS::AST::TypeAnnotation *annotation = irFunction->arguments.at(i).typeAnnotation.data())
499 QmlIR::Parameter::initType(&formal->type, idGenerator, annotation->type);
500 }
501
502 // write locals
503 quint32_le *locals = (quint32_le *)(f + function->localsOffset);
504 for (int i = 0; i < irFunction->locals.size(); ++i)
505 locals[i] = getStringId(irFunction->locals.at(i));
506
507 // write line and statement numbers
508 memcpy(f + function->lineAndStatementNumberOffset(),
509 irFunction->lineAndStatementNumberMapping.constData(),
510 irFunction->lineAndStatementNumberMapping.size()
511 * sizeof(CompiledData::CodeOffsetToLineAndStatement));
512
513 quint32_le *labels = (quint32_le *)(f + function->labelInfosOffset());
514 for (unsigned u : irFunction->labelInfo) {
515 *labels++ = u;
516 }
517
518 // write byte code
519 memcpy(f + function->codeOffset, irFunction->code.constData(), irFunction->code.size());
520}
521
522static_assert(int(QV4::Compiler::Class::Method::Regular) == int(QV4::CompiledData::Method::Regular), "Incompatible layout");
523static_assert(int(QV4::Compiler::Class::Method::Getter) == int(QV4::CompiledData::Method::Getter), "Incompatible layout");
524static_assert(int(QV4::Compiler::Class::Method::Setter) == int(QV4::CompiledData::Method::Setter), "Incompatible layout");
525
526void QV4::Compiler::JSUnitGenerator::writeClass(char *b, const QV4::Compiler::Class &c)
527{
528 QV4::CompiledData::Class *cls = reinterpret_cast<QV4::CompiledData::Class *>(b);
529
530 quint32 currentOffset = sizeof(QV4::CompiledData::Class);
531
532 QList<Class::Method> allMethods = c.staticMethods;
533 allMethods += c.methods;
534
535 cls->constructorFunction = c.constructorIndex;
536 cls->nameIndex = c.nameIndex;
537 cls->nMethods = c.methods.size();
538 cls->nStaticMethods = c.staticMethods.size();
539 cls->methodTableOffset = currentOffset;
540 CompiledData::Method *method = reinterpret_cast<CompiledData::Method *>(b + currentOffset);
541
542 // write methods
543 for (int i = 0; i < allMethods.size(); ++i) {
544 method->name = allMethods.at(i).nameIndex;
545 method->type = allMethods.at(i).type;
546 method->function = allMethods.at(i).functionIndex;
547 ++method;
548 }
549
550 static const bool showCode = qEnvironmentVariableIsSet("QV4_SHOW_BYTECODE");
551 if (showCode) {
552 qDebug() << "=== Class" << stringForIndex(cls->nameIndex) << "static methods"
553 << cls->nStaticMethods << "methods" << cls->nMethods;
554 qDebug() << " constructor:" << cls->constructorFunction;
555 for (uint i = 0; i < cls->nStaticMethods + cls->nMethods; ++i) {
556 QDebug output = qDebug().nospace();
557 output << " " << i << ": ";
558 if (i < cls->nStaticMethods)
559 output << "static ";
560 switch (cls->methodTable()[i].type) {
561 case CompiledData::Method::Getter:
562 output << "get "; break;
563 case CompiledData::Method::Setter:
564 output << "set "; break;
565 default:
566 break;
567 }
568 output << stringForIndex(cls->methodTable()[i].name) << " "
569 << cls->methodTable()[i].function;
570 }
571 qDebug().space();
572 }
573}
574
575void QV4::Compiler::JSUnitGenerator::writeTemplateObject(char *b, const QV4::Compiler::TemplateObject &t)
576{
577 QV4::CompiledData::TemplateObject *tmpl = reinterpret_cast<QV4::CompiledData::TemplateObject *>(b);
578 tmpl->size = t.strings.size();
579
580 quint32 currentOffset = sizeof(QV4::CompiledData::TemplateObject);
581
582 quint32_le *strings = reinterpret_cast<quint32_le *>(b + currentOffset);
583
584 // write methods
585 for (int i = 0; i < t.strings.size(); ++i)
586 strings[i] = t.strings.at(i);
587 strings += t.strings.size();
588
589 for (int i = 0; i < t.rawStrings.size(); ++i)
590 strings[i] = t.rawStrings.at(i);
591
592 static const bool showCode = qEnvironmentVariableIsSet("QV4_SHOW_BYTECODE");
593 if (showCode) {
594 qDebug() << "=== TemplateObject size" << tmpl->size;
595 for (uint i = 0; i < tmpl->size; ++i) {
596 qDebug() << " " << i << stringForIndex(tmpl->stringIndexAt(i));
597 qDebug() << " raw: " << stringForIndex(tmpl->rawStringIndexAt(i));
598 }
599 qDebug();
600 }
601}
602
603void QV4::Compiler::JSUnitGenerator::writeBlock(char *b, QV4::Compiler::Context *irBlock) const
604{
605 QV4::CompiledData::Block *block = reinterpret_cast<QV4::CompiledData::Block *>(b);
606
607 quint32 currentOffset = static_cast<quint32>(QtPrivate::roundUpToMultipleOf(8, sizeof(*block)));
608
609 block->sizeOfLocalTemporalDeadZone = irBlock->sizeOfLocalTemporalDeadZone;
610 block->nLocals = irBlock->locals.size();
611 block->localsOffset = currentOffset;
612 currentOffset += block->nLocals * sizeof(quint32);
613
614 // write locals
615 quint32_le *locals = (quint32_le *)(b + block->localsOffset);
616 for (int i = 0; i < irBlock->locals.size(); ++i)
617 locals[i] = getStringId(irBlock->locals.at(i));
618
619 static const bool showCode = qEnvironmentVariableIsSet("QV4_SHOW_BYTECODE");
620 if (showCode) {
621 qDebug() << "=== Variables for block" << irBlock->blockIndex;
622 for (int i = 0; i < irBlock->locals.size(); ++i)
623 qDebug() << " " << i << ":" << locals[i];
624 qDebug();
625 }
626}
627
628QV4::CompiledData::Unit QV4::Compiler::JSUnitGenerator::generateHeader(QV4::Compiler::JSUnitGenerator::GeneratorOption option, quint32_le *blockAndFunctionOffsets, uint *jsClassDataOffset)
629{
630 CompiledData::Unit unit;
631 memset(&unit, 0, sizeof(unit));
632 memcpy(unit.magic, CompiledData::magic_str, sizeof(unit.magic));
633 unit.flags = QV4::CompiledData::Unit::IsJavascript;
634 unit.flags |= module->unitFlags;
635 unit.version = QV4_DATA_STRUCTURE_VERSION;
636 memset(unit.md5Checksum, 0, sizeof(unit.md5Checksum));
637 memset(unit.dependencyMD5Checksum, 0, sizeof(unit.dependencyMD5Checksum));
638
639 quint32 nextOffset = sizeof(CompiledData::Unit);
640
641 unit.functionTableSize = module->functions.size();
642 unit.offsetToFunctionTable = nextOffset;
643 nextOffset += unit.functionTableSize * sizeof(uint);
644
645 unit.classTableSize = module->classes.size();
646 unit.offsetToClassTable = nextOffset;
647 nextOffset += unit.classTableSize * sizeof(uint);
648
649 unit.templateObjectTableSize = module->templateObjects.size();
650 unit.offsetToTemplateObjectTable = nextOffset;
651 nextOffset += unit.templateObjectTableSize * sizeof(uint);
652
653 unit.blockTableSize = module->blocks.size();
654 unit.offsetToBlockTable = nextOffset;
655 nextOffset += unit.blockTableSize * sizeof(uint);
656
657 unit.lookupTableSize = lookups.size();
658 unit.offsetToLookupTable = nextOffset;
659 nextOffset += unit.lookupTableSize * sizeof(CompiledData::Lookup);
660
661 unit.regexpTableSize = regexps.size();
662 unit.offsetToRegexpTable = nextOffset;
663 nextOffset += unit.regexpTableSize * sizeof(CompiledData::RegExp);
664
665 unit.constantTableSize = constants.size();
666
667 // Ensure we load constants from well-aligned addresses into for example SSE registers.
668 nextOffset = static_cast<quint32>(QtPrivate::roundUpToMultipleOf(16, nextOffset));
669 unit.offsetToConstantTable = nextOffset;
670 nextOffset += unit.constantTableSize * sizeof(ReturnedValue);
671
672 unit.jsClassTableSize = jsClassOffsets.size();
673 unit.offsetToJSClassTable = nextOffset;
674 nextOffset += unit.jsClassTableSize * sizeof(uint);
675
676 *jsClassDataOffset = nextOffset;
677 nextOffset += jsClassData.size();
678
679 nextOffset = static_cast<quint32>(QtPrivate::roundUpToMultipleOf(8, nextOffset));
680
681 unit.translationTableSize = translations.size();
682 unit.offsetToTranslationTable = nextOffset;
683 nextOffset += unit.translationTableSize * sizeof(CompiledData::TranslationData);
684 if (unit.translationTableSize != 0) {
685 constexpr auto spaceForTranslationContextId = sizeof(quint32_le);
686 nextOffset += spaceForTranslationContextId;
687 }
688
689 nextOffset = static_cast<quint32>(QtPrivate::roundUpToMultipleOf(8, nextOffset));
690
691 const auto reserveExportTable = [&nextOffset](int count, quint32_le *tableSizePtr, quint32_le *offsetPtr) {
692 *tableSizePtr = count;
693 *offsetPtr = nextOffset;
694 nextOffset += count * sizeof(CompiledData::ExportEntry);
695 nextOffset = static_cast<quint32>(QtPrivate::roundUpToMultipleOf(8, nextOffset));
696 };
697
698 reserveExportTable(module->localExportEntries.size(), &unit.localExportEntryTableSize, &unit.offsetToLocalExportEntryTable);
699 reserveExportTable(module->indirectExportEntries.size(), &unit.indirectExportEntryTableSize, &unit.offsetToIndirectExportEntryTable);
700 reserveExportTable(module->starExportEntries.size(), &unit.starExportEntryTableSize, &unit.offsetToStarExportEntryTable);
701
702 unit.importEntryTableSize = module->importEntries.size();
703 unit.offsetToImportEntryTable = nextOffset;
704 nextOffset += unit.importEntryTableSize * sizeof(CompiledData::ImportEntry);
705 nextOffset = static_cast<quint32>(QtPrivate::roundUpToMultipleOf(8, nextOffset));
706
707 unit.moduleRequestTableSize = module->moduleRequests.size();
708 unit.offsetToModuleRequestTable = nextOffset;
709 nextOffset += unit.moduleRequestTableSize * sizeof(uint);
710 nextOffset = static_cast<quint32>(QtPrivate::roundUpToMultipleOf(8, nextOffset));
711
712 quint32 functionSize = 0;
713 for (int i = 0; i < module->functions.size(); ++i) {
714 Context *f = module->functions.at(i);
715 blockAndFunctionOffsets[i] = nextOffset;
716
717 quint32 size = QV4::CompiledData::Function::calculateSize(
718 f->arguments.size(), f->locals.size(), f->lineAndStatementNumberMapping.size(),
719 f->nestedContexts.size(), int(f->labelInfo.size()), f->code.size());
720 functionSize += size - f->code.size();
721 nextOffset += size;
722 }
723
724 blockAndFunctionOffsets += module->functions.size();
725
726 for (int i = 0; i < module->classes.size(); ++i) {
727 const Class &c = module->classes.at(i);
728 blockAndFunctionOffsets[i] = nextOffset;
729
730 nextOffset += QV4::CompiledData::Class::calculateSize(c.staticMethods.size(), c.methods.size());
731 }
732 blockAndFunctionOffsets += module->classes.size();
733
734 for (int i = 0; i < module->templateObjects.size(); ++i) {
735 const TemplateObject &t = module->templateObjects.at(i);
736 blockAndFunctionOffsets[i] = nextOffset;
737
738 nextOffset += QV4::CompiledData::TemplateObject::calculateSize(t.strings.size());
739 }
740 blockAndFunctionOffsets += module->templateObjects.size();
741
742 for (int i = 0; i < module->blocks.size(); ++i) {
743 Context *c = module->blocks.at(i);
744 blockAndFunctionOffsets[i] = nextOffset;
745
746 nextOffset += QV4::CompiledData::Block::calculateSize(c->locals.size());
747 }
748
749 if (option == GenerateWithStringTable) {
750 unit.stringTableSize = stringTable.stringCount();
751 nextOffset = static_cast<quint32>(QtPrivate::roundUpToMultipleOf(8, nextOffset));
752 unit.offsetToStringTable = nextOffset;
753 nextOffset += stringTable.sizeOfTableAndData();
754 } else {
755 unit.stringTableSize = 0;
756 unit.offsetToStringTable = 0;
757 }
758 unit.indexOfRootFunction = -1;
759 unit.sourceFileIndex = getStringId(module->fileName);
760 unit.finalUrlIndex = getStringId(module->finalUrl);
761 unit.sourceTimeStamp = module->sourceTimeStamp.isValid() ? module->sourceTimeStamp.toMSecsSinceEpoch() : 0;
762 unit.offsetToQmlUnit = 0;
763
764 unit.unitSize = nextOffset;
765
766 static const bool showStats = qEnvironmentVariableIsSet("QML_SHOW_UNIT_STATS");
767 if (showStats) {
768 qDebug() << "Generated JS unit that is" << unit.unitSize << "bytes contains:";
769 qDebug() << " " << functionSize << "bytes for non-code function data for" << unit.functionTableSize << "functions";
770 qDebug() << " " << translations.size() * sizeof(CompiledData::TranslationData) << "bytes for" << translations.size() << "translations";
771 }
772
773 return unit;
774}
Combined button and popup list for selecting options.
static size_t roundUpToMultipleOf(size_t divisor, size_t x)
static constexpr qsizetype jsClassMembersOffset
static QV4::CompiledData::Lookup::Mode lookupMode(QV4::Compiler::JSUnitGenerator::LookupMode mode)