1/****************************************************************************
2**
3** Copyright (C) 2016 The Qt Company Ltd.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the QtQml module of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:GPL-EXCEPT$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** GNU General Public License Usage
18** Alternatively, this file may be used under the terms of the GNU
19** General Public License version 3 as published by the Free Software
20** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
21** included in the packaging of this file. Please review the following
22** information to ensure the GNU General Public License requirements will
23** be met: https://www.gnu.org/licenses/gpl-3.0.html.
24**
25** $QT_END_LICENSE$
26**
27****************************************************************************/
28#include <QByteArray>
29#include <QRegExp>
30#include <QString>
31#include <QStringList>
32#include <QTextStream>
33#include <QVector>
34#include <QtEndian>
35#include <QStack>
36#include <QFileInfo>
37#include <QSaveFile>
38
39#include <algorithm>
40
41/*!
42 * \internal
43 * Mangles \a str to be a unique C++ identifier. Characters that are invalid for C++ identifiers
44 * are replaced by the pattern \c _0x<hex>_ where <hex> is the hexadecimal unicode
45 * representation of the character. As identifiers with leading underscores followed by either
46 * another underscore or a capital letter are reserved in C++, we also escape those, by escaping
47 * the first underscore, using the above method.
48 *
49 * \note
50 * Although C++11 allows for non-ascii (unicode) characters to be used in identifiers,
51 * many compilers forgot to read the spec and do not implement this. Some also do not
52 * implement C99 identifiers, because that is \e {at the implementation's discretion}. So,
53 * we are stuck with plain old boring identifiers.
54 */
55QString mangledIdentifier(const QString &str)
56{
57 Q_ASSERT(!str.isEmpty());
58
59 QString mangled;
60 mangled.reserve(asize: str.size());
61
62 int i = 0;
63 if (str.startsWith(c: QLatin1Char('_')) && str.size() > 1) {
64 QChar ch = str.at(i: 1);
65 if (ch == QLatin1Char('_')
66 || (ch >= QLatin1Char('A') && ch <= QLatin1Char('Z'))) {
67 mangled += QLatin1String("_0x5f_");
68 ++i;
69 }
70 }
71
72 for (int ei = str.length(); i != ei; ++i) {
73 auto c = str.at(i).unicode();
74 if ((c >= QLatin1Char('0') && c <= QLatin1Char('9'))
75 || (c >= QLatin1Char('a') && c <= QLatin1Char('z'))
76 || (c >= QLatin1Char('A') && c <= QLatin1Char('Z'))
77 || c == QLatin1Char('_')) {
78 mangled += QChar(c);
79 } else {
80 mangled += QLatin1String("_0x") + QString::number(c, base: 16) + QLatin1Char('_');
81 }
82 }
83
84 return mangled;
85}
86
87QString symbolNamespaceForPath(const QString &relativePath)
88{
89 QFileInfo fi(relativePath);
90 QString symbol = fi.path();
91 if (symbol.length() == 1 && symbol.startsWith(c: QLatin1Char('.'))) {
92 symbol.clear();
93 } else {
94 symbol.replace(before: QLatin1Char('/'), after: QLatin1Char('_'));
95 symbol += QLatin1Char('_');
96 }
97 symbol += fi.baseName();
98 symbol += QLatin1Char('_');
99 symbol += fi.completeSuffix();
100 return mangledIdentifier(str: symbol);
101}
102
103static QString qtResourceNameForFile(const QString &fileName)
104{
105 QFileInfo fi(fileName);
106 QString name = fi.completeBaseName();
107 if (name.isEmpty())
108 name = fi.fileName();
109 name.replace(rx: QRegExp(QLatin1String("[^a-zA-Z0-9_]")), after: QLatin1String("_"));
110 return name;
111}
112
113bool generateLoader(const QStringList &compiledFiles, const QString &outputFileName,
114 const QStringList &resourceFileMappings, QString *errorString)
115{
116 QByteArray generatedLoaderCode;
117
118 {
119 QTextStream stream(&generatedLoaderCode);
120 stream << "#include <QtQml/qqmlprivate.h>\n";
121 stream << "#include <QtCore/qdir.h>\n";
122 stream << "#include <QtCore/qurl.h>\n";
123 stream << "\n";
124
125 stream << "namespace QmlCacheGeneratedCode {\n";
126 for (int i = 0; i < compiledFiles.count(); ++i) {
127 const QString compiledFile = compiledFiles.at(i);
128 const QString ns = symbolNamespaceForPath(relativePath: compiledFile);
129 stream << "namespace " << ns << " { \n";
130 stream << " extern const unsigned char qmlData[];\n";
131 stream << " const QQmlPrivate::CachedQmlUnit unit = {\n";
132 stream << " reinterpret_cast<const QV4::CompiledData::Unit*>(&qmlData), nullptr, nullptr\n";
133 stream << " };\n";
134 stream << "}\n";
135 }
136
137 stream << "\n}\n";
138 stream << "namespace {\n";
139
140 stream << "struct Registry {\n";
141 stream << " Registry();\n";
142 stream << " ~Registry();\n";
143 stream << " QHash<QString, const QQmlPrivate::CachedQmlUnit*> resourcePathToCachedUnit;\n";
144 stream << " static const QQmlPrivate::CachedQmlUnit *lookupCachedUnit(const QUrl &url);\n";
145 stream << "};\n\n";
146 stream << "Q_GLOBAL_STATIC(Registry, unitRegistry)\n";
147 stream << "\n\n";
148
149 stream << "Registry::Registry() {\n";
150
151 for (int i = 0; i < compiledFiles.count(); ++i) {
152 const QString qrcFile = compiledFiles.at(i);
153 const QString ns = symbolNamespaceForPath(relativePath: qrcFile);
154 stream << " resourcePathToCachedUnit.insert(QStringLiteral(\"" << qrcFile << "\"), &QmlCacheGeneratedCode::" << ns << "::unit);\n";
155 }
156
157 stream << " QQmlPrivate::RegisterQmlUnitCacheHook registration;\n";
158 stream << " registration.version = 0;\n";
159 stream << " registration.lookupCachedQmlUnit = &lookupCachedUnit;\n";
160 stream << " QQmlPrivate::qmlregister(QQmlPrivate::QmlUnitCacheHookRegistration, &registration);\n";
161
162 stream << "}\n\n";
163 stream << "Registry::~Registry() {\n";
164 stream << " QQmlPrivate::qmlunregister(QQmlPrivate::QmlUnitCacheHookRegistration, quintptr(&lookupCachedUnit));\n";
165 stream << "}\n\n";
166
167 stream << "const QQmlPrivate::CachedQmlUnit *Registry::lookupCachedUnit(const QUrl &url) {\n";
168 stream << " if (url.scheme() != QLatin1String(\"qrc\"))\n";
169 stream << " return nullptr;\n";
170 stream << " QString resourcePath = QDir::cleanPath(url.path());\n";
171 stream << " if (resourcePath.isEmpty())\n";
172 stream << " return nullptr;\n";
173 stream << " if (!resourcePath.startsWith(QLatin1Char('/')))\n";
174 stream << " resourcePath.prepend(QLatin1Char('/'));\n";
175 stream << " return unitRegistry()->resourcePathToCachedUnit.value(resourcePath, nullptr);\n";
176 stream << "}\n";
177 stream << "}\n";
178
179 for (const QString &mapping: resourceFileMappings) {
180 QString originalResourceFile = mapping;
181 QString newResourceFile;
182 const int mappingSplit = originalResourceFile.indexOf(c: QLatin1Char('='));
183 if (mappingSplit != -1) {
184 newResourceFile = originalResourceFile.mid(position: mappingSplit + 1);
185 originalResourceFile.truncate(pos: mappingSplit);
186 }
187
188 const QString suffix = qtResourceNameForFile(fileName: originalResourceFile);
189 const QString initFunction = QLatin1String("qInitResources_") + suffix;
190
191 stream << QStringLiteral("int QT_MANGLE_NAMESPACE(%1)() {\n").arg(a: initFunction);
192 stream << " ::unitRegistry();\n";
193 if (!newResourceFile.isEmpty())
194 stream << " Q_INIT_RESOURCE(" << qtResourceNameForFile(fileName: newResourceFile) << ");\n";
195 stream << " return 1;\n";
196 stream << "}\n";
197 stream << "Q_CONSTRUCTOR_FUNCTION(QT_MANGLE_NAMESPACE(" << initFunction << "))\n";
198
199 const QString cleanupFunction = QLatin1String("qCleanupResources_") + suffix;
200 stream << QStringLiteral("int QT_MANGLE_NAMESPACE(%1)() {\n").arg(a: cleanupFunction);
201 if (!newResourceFile.isEmpty())
202 stream << " Q_CLEANUP_RESOURCE(" << qtResourceNameForFile(fileName: newResourceFile) << ");\n";
203 stream << " return 1;\n";
204 stream << "}\n";
205 }
206 }
207
208#if QT_CONFIG(temporaryfile)
209 QSaveFile f(outputFileName);
210#else
211 QFile f(outputFileName);
212#endif
213 if (!f.open(flags: QIODevice::WriteOnly | QIODevice::Truncate)) {
214 *errorString = f.errorString();
215 return false;
216 }
217
218 if (f.write(data: generatedLoaderCode) != generatedLoaderCode.size()) {
219 *errorString = f.errorString();
220 return false;
221 }
222
223#if QT_CONFIG(temporaryfile)
224 if (!f.commit()) {
225 *errorString = f.errorString();
226 return false;
227 }
228#endif
229
230 return true;
231}
232

source code of qtdeclarative/tools/qmlcachegen/generateloader.cpp