1// Copyright (C) 2024 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
4#include "qv4compileddata_p.h"
5
6#include <private/inlinecomponentutils_p.h>
7#include <private/qqmlscriptdata_p.h>
8#include <private/qqmltypenamecache_p.h>
9#include <private/qv4resolvedtypereference_p.h>
10
11#include <QtQml/qqmlfile.h>
12
13#include <QtCore/qdir.h>
14#include <QtCore/qscopeguard.h>
15#include <QtCore/qstandardpaths.h>
16#include <QtCore/qxpfunctional.h>
17
18QT_BEGIN_NAMESPACE
19
20namespace QV4 {
21namespace CompiledData {
22
23
24bool Unit::verifyHeader(QDateTime expectedSourceTimeStamp, QString *errorString) const
25{
26 if (strncmp(s1: magic, s2: CompiledData::magic_str, n: sizeof(magic))) {
27 *errorString = QStringLiteral("Magic bytes in the header do not match");
28 return false;
29 }
30
31 if (version != quint32(QV4_DATA_STRUCTURE_VERSION)) {
32 *errorString = QString::fromUtf8(utf8: "V4 data structure version mismatch. Found %1 expected %2")
33 .arg(a: version, fieldWidth: 0, base: 16).arg(QV4_DATA_STRUCTURE_VERSION, fieldWidth: 0, base: 16);
34 return false;
35 }
36
37 if (sourceTimeStamp) {
38 // Files from the resource system do not have any time stamps, so fall back to the application
39 // executable.
40 if (!expectedSourceTimeStamp.isValid())
41 expectedSourceTimeStamp = QFileInfo(QCoreApplication::applicationFilePath()).lastModified();
42
43 if (expectedSourceTimeStamp.isValid()
44 && expectedSourceTimeStamp.toMSecsSinceEpoch() != sourceTimeStamp) {
45 *errorString = QStringLiteral("QML source file has a different time stamp than cached file.");
46 return false;
47 }
48 }
49
50 return true;
51}
52
53/*!
54 \internal
55 This function creates a temporary key vector and sorts it to guarantuee a stable
56 hash. This is used to calculate a check-sum on dependent meta-objects.
57 */
58bool ResolvedTypeReferenceMap::addToHash(
59 QCryptographicHash *hash, QHash<quintptr, QByteArray> *checksums) const
60{
61 std::vector<int> keys (size());
62 int i = 0;
63 for (auto it = constBegin(), end = constEnd(); it != end; ++it) {
64 keys[i] = it.key();
65 ++i;
66 }
67 std::sort(first: keys.begin(), last: keys.end());
68 for (int key: keys) {
69 if (!this->operator[](key)->addToHash(hash, checksums))
70 return false;
71 }
72
73 return true;
74}
75
76CompilationUnit::CompilationUnit(
77 const Unit *unitData, const QString &fileName, const QString &finalUrlString)
78{
79 setUnitData(unitData, qmlUnit: nullptr, fileName, finalUrlString);
80}
81
82CompilationUnit::~CompilationUnit()
83{
84 qDeleteAll(c: resolvedTypes);
85
86 if (data) {
87 if (data->qmlUnit() != qmlData)
88 free(ptr: const_cast<QmlUnit *>(qmlData));
89 qmlData = nullptr;
90
91 if (!(data->flags & QV4::CompiledData::Unit::StaticData))
92 free(ptr: const_cast<Unit *>(data));
93 }
94 data = nullptr;
95#if Q_BYTE_ORDER == Q_BIG_ENDIAN
96 delete [] constants;
97 constants = nullptr;
98#endif
99}
100
101QString CompilationUnit::localCacheFilePath(const QUrl &url)
102{
103 static const QByteArray envCachePath = qgetenv(varName: "QML_DISK_CACHE_PATH");
104
105 const QString localSourcePath = QQmlFile::urlToLocalFileOrQrc(url);
106 const QString cacheFileSuffix
107 = QFileInfo(localSourcePath + QLatin1Char('c')).completeSuffix();
108 QCryptographicHash fileNameHash(QCryptographicHash::Sha1);
109 fileNameHash.addData(data: localSourcePath.toUtf8());
110 QString directory = envCachePath.isEmpty()
111 ? QStandardPaths::writableLocation(type: QStandardPaths::CacheLocation)
112 + QLatin1String("/qmlcache/")
113 : QString::fromLocal8Bit(ba: envCachePath) + QLatin1String("/");
114 QDir::root().mkpath(dirPath: directory);
115 return directory + QString::fromUtf8(ba: fileNameHash.result().toHex())
116 + QLatin1Char('.') + cacheFileSuffix;
117}
118
119bool CompilationUnit::loadFromDisk(
120 const QUrl &url, const QDateTime &sourceTimeStamp, QString *errorString)
121{
122 if (!QQmlFile::isLocalFile(url)) {
123 *errorString = QStringLiteral("File has to be a local file.");
124 return false;
125 }
126
127 const QString sourcePath = QQmlFile::urlToLocalFileOrQrc(url);
128 auto cacheFile = std::make_unique<CompilationUnitMapper>();
129
130 const QStringList cachePaths = { sourcePath + QLatin1Char('c'), localCacheFilePath(url) };
131 for (const QString &cachePath : cachePaths) {
132 Unit *mappedUnit = cacheFile->get(cacheFilePath: cachePath, sourceTimeStamp, errorString);
133 if (!mappedUnit)
134 continue;
135
136 const Unit *oldData = unitData();
137 const Unit * const oldDataPtr
138 = (oldData && !(oldData->flags & Unit::StaticData))
139 ? oldData
140 : nullptr;
141
142 auto dataPtrRevert = qScopeGuard(f: [this, oldData](){
143 setUnitData(unitData: oldData);
144 });
145 setUnitData(unitData: mappedUnit);
146
147 if (mappedUnit->sourceFileIndex != 0) {
148 if (mappedUnit->sourceFileIndex >=
149 mappedUnit->stringTableSize + dynamicStrings.size()) {
150 *errorString = QStringLiteral("QML source file index is invalid.");
151 continue;
152 }
153 if (sourcePath !=
154 QQmlFile::urlToLocalFileOrQrc(stringAt(index: mappedUnit->sourceFileIndex))) {
155 *errorString = QStringLiteral("QML source file has moved to a different location.");
156 continue;
157 }
158 }
159
160 dataPtrRevert.dismiss();
161 free(ptr: const_cast<Unit*>(oldDataPtr));
162 backingFile = std::move(cacheFile);
163 return true;
164 }
165
166 return false;
167}
168
169bool CompilationUnit::saveToDisk(const QUrl &unitUrl, QString *errorString)
170{
171 if (unitData()->sourceTimeStamp == 0) {
172 *errorString = QStringLiteral("Missing time stamp for source file");
173 return false;
174 }
175
176 if (!QQmlFile::isLocalFile(url: unitUrl)) {
177 *errorString = QStringLiteral("File has to be a local file.");
178 return false;
179 }
180
181 return SaveableUnitPointer(unitData()).saveToDisk<char>(
182 writer: [&unitUrl, errorString](const char *data, quint32 size) {
183 const QString cachePath = localCacheFilePath(url: unitUrl);
184 if (SaveableUnitPointer::writeDataToFile(
185 outputFileName: cachePath, data, size, errorString)) {
186 CompilationUnitMapper::invalidate(cacheFilePath: cachePath);
187 return true;
188 }
189
190 return false;
191 });
192}
193
194QStringList CompilationUnit::moduleRequests() const
195{
196 QStringList requests;
197 requests.reserve(asize: data->moduleRequestTableSize);
198 for (uint i = 0; i < data->moduleRequestTableSize; ++i)
199 requests << stringAt(index: data->moduleRequestTable()[i]);
200 return requests;
201}
202
203ResolvedTypeReference *CompilationUnit::resolvedType(QMetaType type) const
204{
205 for (ResolvedTypeReference *ref : std::as_const(t: resolvedTypes)) {
206 if (ref->type().typeId() == type)
207 return ref;
208 }
209 return nullptr;
210
211}
212
213void CompiledData::CompilationUnit::finalizeCompositeType(const QQmlType &type)
214{
215 // Add to type registry of composites
216 if (propertyCaches.needsVMEMetaObject(/*root object*/index: 0)) {
217 // qmlType is only valid for types that have references to themselves.
218 if (type.isValid()) {
219 qmlType = type;
220 } else {
221 qmlType = QQmlMetaType::findCompositeType(
222 url: url(), compilationUnit: this, mode: (unitData()->flags & CompiledData::Unit::IsSingleton)
223 ? QQmlMetaType::Singleton
224 : QQmlMetaType::NonSingleton);
225 }
226
227 QQmlMetaType::registerInternalCompositeType(compilationUnit: this);
228 } else {
229 const QV4::CompiledData::Object *obj = objectAt(/*root object*/index: 0);
230 auto *typeRef = resolvedTypes.value(key: obj->inheritedTypeNameIndex);
231 Q_ASSERT(typeRef);
232 if (const auto compilationUnit = typeRef->compilationUnit())
233 qmlType = compilationUnit->qmlType;
234 else
235 qmlType = typeRef->type();
236 }
237}
238
239bool CompilationUnit::verifyChecksum(const DependentTypesHasher &dependencyHasher) const
240{
241 if (!dependencyHasher) {
242 for (size_t i = 0; i < sizeof(data->dependencyMD5Checksum); ++i) {
243 if (data->dependencyMD5Checksum[i] != 0)
244 return false;
245 }
246 return true;
247 }
248 const QByteArray checksum = dependencyHasher();
249 return checksum.size() == sizeof(data->dependencyMD5Checksum)
250 && memcmp(s1: data->dependencyMD5Checksum, s2: checksum.constData(),
251 n: sizeof(data->dependencyMD5Checksum)) == 0;
252}
253
254QQmlType CompilationUnit::qmlTypeForComponent(const QString &inlineComponentName) const
255{
256 if (inlineComponentName.isEmpty())
257 return qmlType;
258 return inlineComponentData[inlineComponentName].qmlType;
259}
260
261} // namespace CompiledData
262} // namespace QV4
263
264QT_END_NAMESPACE
265

source code of qtdeclarative/src/qml/common/qv4compileddata.cpp