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
qqmljsloadergenerator.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
3// Qt-Security score:critical reason:code-generation
4
6
7#include <QByteArray>
8#include <QRegularExpression>
9#include <QString>
10#include <QStringList>
11#include <QTextStream>
12#include <QVector>
13#include <QtEndian>
14#include <QStack>
15#include <QFileInfo>
16#include <QSaveFile>
17
19
20/*!
21 * \internal
22 * Mangles \a str to be a unique C++ identifier. Characters that are invalid for C++ identifiers
23 * are replaced by the pattern \c _0x<hex>_ where <hex> is the hexadecimal unicode
24 * representation of the character. As identifiers with leading underscores followed by either
25 * another underscore or a capital letter are reserved in C++, we also escape those, by escaping
26 * the first underscore, using the above method.
27 *
28 * \note
29 * Although C++11 allows for non-ascii (unicode) characters to be used in identifiers,
30 * many compilers forgot to read the spec and do not implement this. Some also do not
31 * implement C99 identifiers, because that is \e {at the implementation's discretion}. So,
32 * we are stuck with plain old boring identifiers.
33 */
34QString mangledIdentifier(const QString &str)
35{
36 Q_ASSERT(!str.isEmpty());
37
38 QString mangled;
39 mangled.reserve(str.size());
40
41 int i = 0;
42 if (str.startsWith(QLatin1Char('_')) && str.size() > 1) {
43 QChar ch = str.at(1);
44 if (ch == QLatin1Char('_')
45 || (ch >= QLatin1Char('A') && ch <= QLatin1Char('Z'))) {
46 mangled += QLatin1String("_0x5f_");
47 ++i;
48 }
49 }
50
51 for (int ei = str.size(); i != ei; ++i) {
52 auto c = str.at(i).unicode();
53 if ((c >= QLatin1Char('0') && c <= QLatin1Char('9'))
54 || (c >= QLatin1Char('a') && c <= QLatin1Char('z'))
55 || (c >= QLatin1Char('A') && c <= QLatin1Char('Z'))
56 || c == QLatin1Char('_')) {
57 mangled += QChar(c);
58 } else {
59 mangled += QLatin1String("_0x") + QString::number(c, 16) + QLatin1Char('_');
60 }
61 }
62
63 return mangled;
64}
65
66QString qQmlJSSymbolNamespaceForPath(const QString &relativePath)
67{
68 QFileInfo fi(relativePath);
69 QString symbol = fi.path();
70 if (symbol.size() == 1 && symbol.startsWith(QLatin1Char('.'))) {
71 symbol.clear();
72 } else {
73 symbol.replace(QLatin1Char('/'), QLatin1Char('_'));
74 symbol += QLatin1Char('_');
75 }
76 symbol += fi.baseName();
77 symbol += QLatin1Char('_');
78 symbol += fi.completeSuffix();
79 return mangledIdentifier(symbol);
80}
81
82static QString qtResourceNameForFile(const QString &fileName)
83{
84 QFileInfo fi(fileName);
85 QString name = fi.completeBaseName();
86 if (name.isEmpty())
87 name = fi.fileName();
88 name.replace(QRegularExpression(QLatin1String("[^a-zA-Z0-9_]")), QLatin1String("_"));
89 return name;
90}
91
92bool qQmlJSGenerateLoader(const QStringList &compiledFiles, const QString &outputFileName,
93 const QStringList &resourceFileMappings, QString *errorString)
94{
95 QByteArray generatedLoaderCode;
96
97 {
98 QTextStream stream(&generatedLoaderCode);
99 stream << "#include <QtQml/qqmlprivate.h>\n";
100 stream << "#include <QtCore/qdir.h>\n";
101 stream << "#include <QtCore/qurl.h>\n";
102 stream << "#include <QtCore/qhash.h>\n";
103 stream << "#include <QtCore/qstring.h>\n";
104 stream << "\n";
105
106 stream << "namespace QmlCacheGeneratedCode {\n";
107 for (int i = 0; i < compiledFiles.size(); ++i) {
108 const QString compiledFile = compiledFiles.at(i);
109 const QString ns = qQmlJSSymbolNamespaceForPath(compiledFile);
110 stream << "namespace " << ns << " { \n";
111 stream << " extern const unsigned char qmlData[];\n";
112 stream << " extern const QQmlPrivate::AOTCompiledFunction aotBuiltFunctions[];\n";
113 stream << " const QQmlPrivate::CachedQmlUnit unit = {\n";
114 stream << " reinterpret_cast<const QV4::CompiledData::Unit*>(&qmlData), &aotBuiltFunctions[0], nullptr\n";
115 stream << " };\n";
116 stream << "}\n";
117 }
118
119 stream << "\n}\n";
120 stream << "namespace {\n";
121
122 stream << "struct Registry {\n";
123 stream << " Registry();\n";
124 stream << " ~Registry();\n";
125 stream << " QHash<QString, const QQmlPrivate::CachedQmlUnit*> resourcePathToCachedUnit;\n";
126 stream << " static const QQmlPrivate::CachedQmlUnit *lookupCachedUnit(const QUrl &url);\n";
127 stream << "};\n\n";
128 stream << "Q_GLOBAL_STATIC(Registry, unitRegistry)\n";
129 stream << "\n\n";
130
131 stream << "Registry::Registry() {\n";
132
133 for (int i = 0; i < compiledFiles.size(); ++i) {
134 const QString qrcFile = compiledFiles.at(i);
135 const QString ns = qQmlJSSymbolNamespaceForPath(qrcFile);
136 stream << " resourcePathToCachedUnit.insert(QStringLiteral(\"" << qrcFile << "\"), &QmlCacheGeneratedCode::" << ns << "::unit);\n";
137 }
138
139 stream << " QQmlPrivate::RegisterQmlUnitCacheHook registration;\n";
140 stream << " registration.structVersion = 0;\n";
141 stream << " registration.lookupCachedQmlUnit = &lookupCachedUnit;\n";
142 stream << " QQmlPrivate::qmlregister(QQmlPrivate::QmlUnitCacheHookRegistration, &registration);\n";
143
144 stream << "}\n\n";
145 stream << "Registry::~Registry() {\n";
146 stream << " QQmlPrivate::qmlunregister(QQmlPrivate::QmlUnitCacheHookRegistration, quintptr(&lookupCachedUnit));\n";
147 stream << "}\n\n";
148
149 stream << "const QQmlPrivate::CachedQmlUnit *Registry::lookupCachedUnit(const QUrl &url) {\n";
150 stream << " if (url.scheme() != QLatin1String(\"qrc\"))\n";
151 stream << " return nullptr;\n";
152 stream << " QString resourcePath = QDir::cleanPath(url.path());\n";
153 stream << " if (resourcePath.isEmpty())\n";
154 stream << " return nullptr;\n";
155 stream << " if (!resourcePath.startsWith(QLatin1Char('/')))\n";
156 stream << " resourcePath.prepend(QLatin1Char('/'));\n";
157 stream << " return unitRegistry()->resourcePathToCachedUnit.value(resourcePath, nullptr);\n";
158 stream << "}\n";
159 stream << "}\n";
160
161 for (const QString &mapping: resourceFileMappings) {
162 QString originalResourceFile = mapping;
163 QString newResourceFile;
164 const int mappingSplit = originalResourceFile.indexOf(QLatin1Char('='));
165 if (mappingSplit != -1) {
166 newResourceFile = originalResourceFile.mid(mappingSplit + 1);
167 originalResourceFile.truncate(mappingSplit);
168 }
169
170 const QString suffix = qtResourceNameForFile(originalResourceFile);
171 const QString initFunction = QLatin1String("qInitResources_") + suffix;
172
173 stream << QStringLiteral("int QT_MANGLE_NAMESPACE(%1)() {\n").arg(initFunction);
174 stream << " ::unitRegistry();\n";
175 if (!newResourceFile.isEmpty())
176 stream << " Q_INIT_RESOURCE(" << qtResourceNameForFile(newResourceFile) << ");\n";
177 stream << " return 1;\n";
178 stream << "}\n";
179 stream << "Q_CONSTRUCTOR_FUNCTION(QT_MANGLE_NAMESPACE(" << initFunction << "))\n";
180
181 const QString cleanupFunction = QLatin1String("qCleanupResources_") + suffix;
182 stream << QStringLiteral("int QT_MANGLE_NAMESPACE(%1)() {\n").arg(cleanupFunction);
183 if (!newResourceFile.isEmpty())
184 stream << " Q_CLEANUP_RESOURCE(" << qtResourceNameForFile(newResourceFile) << ");\n";
185 stream << " return 1;\n";
186 stream << "}\n";
187 }
188 }
189
190#if QT_CONFIG(temporaryfile)
191 QSaveFile f(outputFileName);
192#else
193 QFile f(outputFileName);
194#endif
195 if (!f.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
196 *errorString = f.errorString();
197 return false;
198 }
199
200 if (f.write(generatedLoaderCode) != generatedLoaderCode.size()) {
201 *errorString = f.errorString();
202 return false;
203 }
204
205#if QT_CONFIG(temporaryfile)
206 if (!f.commit()) {
207 *errorString = f.errorString();
208 return false;
209 }
210#endif
211
212 return true;
213}
214
215QT_END_NAMESPACE
static QString qtResourceNameForFile(const QString &fileName)
bool qQmlJSGenerateLoader(const QStringList &compiledFiles, const QString &outputFileName, const QStringList &resourceFileMappings, QString *errorString)
QString qQmlJSSymbolNamespaceForPath(const QString &relativePath)