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
qv4compileddata.cpp
Go to the documentation of this file.
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// Qt-Security score:critical data-parser
4
6
7#include <private/inlinecomponentutils_p.h>
8#include <private/qqmlscriptdata_p.h>
9#include <private/qqmltypenamecache_p.h>
10#include <private/qv4resolvedtypereference_p.h>
11
12#include <QtQml/qqmlfile.h>
13
14#include <QtCore/qdir.h>
15#include <QtCore/qscopeguard.h>
16#include <QtCore/qstandardpaths.h>
17#include <QtCore/qxpfunctional.h>
18
20
21namespace QV4 {
22namespace CompiledData {
23
24
25bool Unit::verifyHeader(QDateTime expectedSourceTimeStamp, QString *errorString) const
26{
27 if (strncmp(magic, CompiledData::magic_str, sizeof(magic))) {
28 *errorString = QStringLiteral("Magic bytes in the header do not match");
29 return false;
30 }
31
32 if (version != quint32(QV4_DATA_STRUCTURE_VERSION)) {
33 *errorString = QString::fromUtf8("V4 data structure version mismatch. Found %1 expected %2")
34 .arg(quint32(version), 0, 16).arg(QV4_DATA_STRUCTURE_VERSION, 0, 16);
35 return false;
36 }
37
38 switch (sourceTimeStamp) {
39 case 0:
40 // No validation necessary
41 return true;
42 case -1:
43 // Content-hash mode: the unit is validated against sourceChecksum rather than the source
44 // file's time stamp. The actual comparison is done in CompilationUnit::loadFromDisk, which
45 // has access to the source code.
46 return true;
47 default:
48 break;
49 }
50
51 // Files from the resource system do not have any time stamps, so fall back to the application
52 // executable.
53 if (!expectedSourceTimeStamp.isValid()) {
54 expectedSourceTimeStamp = QFileInfo(QCoreApplication::applicationFilePath()).lastModified();
55 if (!expectedSourceTimeStamp.isValid()) {
56 *errorString =
57 QStringLiteral("Failed to get valid timestamp from application executable");
58 return false;
59 }
60 }
61 if (expectedSourceTimeStamp.toMSecsSinceEpoch() != sourceTimeStamp) {
62 *errorString =
63 QStringLiteral("QML source file has a different time stamp than cached file.");
64 return false;
65 }
66
67 return true;
68}
69
70/*!
71 \internal
72 This function creates a temporary key vector and sorts it to guarantuee a stable
73 hash. This is used to calculate a check-sum on dependent meta-objects.
74 */
76 QCryptographicHash *hash, QHash<quintptr, QByteArray> *checksums) const
77{
78 std::vector<int> keys (size());
79 int i = 0;
80 for (auto it = constBegin(), end = constEnd(); it != end; ++it) {
81 keys[i] = it.key();
82 ++i;
83 }
84 std::sort(keys.begin(), keys.end());
85 for (int key: keys) {
86 if (!this->operator[](key)->addToHash(hash, checksums))
87 return false;
88 }
89
90 return true;
91}
92
93CompilationUnit::CompilationUnit(
94 const Unit *unitData, const QString &fileName, const QString &finalUrlString)
95{
96 setUnitData(unitData, nullptr, fileName, finalUrlString);
97}
98
100{
101 qDeleteAll(resolvedTypes);
102
103 if (data) {
105 free(const_cast<QmlUnit *>(qmlData));
106 qmlData = nullptr;
107
109 free(const_cast<Unit *>(data));
110 }
111 data = nullptr;
112#if Q_BYTE_ORDER == Q_BIG_ENDIAN
113 delete [] constants;
114 constants = nullptr;
115#endif
116}
117
118QString CompilationUnit::localCacheFilePath(const QUrl &url)
119{
120 static const QByteArray envCachePath = qgetenv("QML_DISK_CACHE_PATH");
121
122 const QString localSourcePath = QQmlFile::urlToLocalFileOrQrc(url);
123 const QString cacheFileSuffix
124 = QFileInfo(localSourcePath + QLatin1Char('c')).completeSuffix();
125 QCryptographicHash fileNameHash(QCryptographicHash::Sha1);
126 fileNameHash.addData(localSourcePath.toUtf8());
127 QString directory = envCachePath.isEmpty()
128 ? QStandardPaths::writableLocation(QStandardPaths::CacheLocation)
129 + QLatin1String("/qmlcache/")
130 : QString::fromLocal8Bit(envCachePath) + QLatin1String("/");
131 QDir::root().mkpath(directory);
132 return directory + QString::fromUtf8(fileNameHash.result().toHex())
133 + QLatin1Char('.') + cacheFileSuffix;
134}
135
136template<typename Target>
137static quint32 alignedTo(quint32 size)
138{
139 static constexpr quint32 Mask = alignof(Target) - 1u;
140 return (size + Mask) & ~Mask;
141}
142
144 const QUrl &url, const QDateTime &sourceTimeStamp,
146{
147 if (!QQmlFile::isLocalFile(url)) {
148 *errorString = QStringLiteral("File has to be a local file.");
149 return false;
150 }
151
152 const QString sourcePath = QQmlFile::urlToLocalFileOrQrc(url);
153 auto cacheFile = std::make_unique<CompilationUnitMapper>();
154
155 const QStringList cachePaths = { sourcePath + QLatin1Char('c'), localCacheFilePath(url) };
156 for (const QString &cachePath : cachePaths) {
157 Unit *mappedUnit = cacheFile->get(cachePath, sourceTimeStamp, errorString);
158 if (!mappedUnit)
159 continue;
160
161 const Unit *oldData = unitData();
162 const Unit * const oldDataPtr
163 = (oldData && !(oldData->flags & Unit::StaticData))
164 ? oldData
165 : nullptr;
166
167 auto dataPtrRevert = qScopeGuard([this, oldData](){
168 setUnitData(oldData);
169 });
170 setUnitData(mappedUnit);
171
172 if (mappedUnit->sourceTimeStamp == -1) {
173 const QByteArray checksum = sourceChecksum();
174 if (checksum.size() != sizeof(mappedUnit->sourceChecksum)
175 || memcmp(mappedUnit->sourceChecksum, checksum.constData(), checksum.size()) != 0) {
176 *errorString = QStringLiteral(
177 "QML source file has a different content checksum than cached file.");
178 continue;
179 }
180 }
181
182 if (mappedUnit->sourceFileIndex != 0) {
183 if (mappedUnit->sourceFileIndex >=
184 mappedUnit->stringTableSize + dynamicStrings.size()) {
185 *errorString = QStringLiteral("QML source file index is invalid.");
186 continue;
187 }
188 if (sourcePath !=
189 QQmlFile::urlToLocalFileOrQrc(stringAt(mappedUnit->sourceFileIndex))) {
190 *errorString = QStringLiteral("QML source file has moved to a different location.");
191 continue;
192 }
193 }
194
195 dataPtrRevert.dismiss();
196 free(const_cast<Unit*>(oldDataPtr));
197 if (const RuntimeDataBlock *mappedRuntimeData = mappedUnit->runtimeData()) {
198 runtimeData = mappedRuntimeData;
199 runtimeDataStorage.clear();
200 }
201
202 backingFile = std::move(cacheFile);
203 return true;
204 }
205
206 return false;
207}
208
210 const QUrl &unitUrl, qxp::function_ref<QByteArray() const> sourceChecksum,
211 QString *errorString) const
212{
213 if (!QQmlFile::isLocalFile(unitUrl)) {
214 *errorString = QStringLiteral("File has to be a local file.");
215 return false;
216 }
217
218 const Unit *base = unitData();
219 const QByteArray checksum = sourceChecksum();
220 if (checksum.size() != sizeof(base->sourceChecksum)) {
221 *errorString = QStringLiteral("Failed to compute source code checksum");
222 return false;
223 }
224
225 // Runtime-generated cache files are validated by content hash. sourceTimeStamp and
226 // sourceChecksum live before md5Checksum and are therefore not covered by it, so we can patch
227 // them without recomputing the integrity checksum. We only patch a copy of the header and
228 // leave the in-memory unit alone.
229
230 Unit header;
231 memcpy(&header, base, sizeof(Unit));
232 header.sourceTimeStamp = -1;
233 memcpy(header.sourceChecksum, checksum.constData(), sizeof(header.sourceChecksum));
234 return writeWithRuntimeData(unitUrl, &header, errorString);
235}
236
237bool CompilationUnit::persistRuntimeData(const QUrl &unitUrl, QString *errorString)
238{
239 if (!QQmlFile::isLocalFile(unitUrl)) {
240 *errorString = QStringLiteral("File has to be a local file.");
241 return false;
242 }
243
244 Unit header;
245
246 // Keep the sourceTimeStamp and sourceChecksum as they were.
247 // We don't have source code here.
248 memcpy(&header, unitData(), sizeof(Unit));
249
250 return writeWithRuntimeData(unitUrl, &header, errorString);
251}
252
253/*!
254 * \internal
255 *
256 * Writes the base unit with the given header, followed by the runtime data. The base unit may
257 * already carry (older) runtime data. We drop that and append our current runtime data. We keep
258 * the md5Checksum: It identifies the base unit and other units depend on it.
259 */
261 const QUrl &unitUrl, Unit *header, QString *errorString) const
262{
263 const Unit *base = unitData();
264 const quint32 baseSize = base->runtimeDataSize ? quint32(base->offsetToRuntimeData)
265 : quint32(base->unitSize);
266 const quint32 runtimeDataOffset = alignedTo<RuntimeDataBlock>(baseSize);
267 const quint32 runtimeDataSize = quint32(runtimeDataStorage.size());
268
269 header->flags |= quint32(Unit::StaticData);
270 header->offsetToRuntimeData = runtimeDataSize > 0 ? runtimeDataOffset : 0;
271 header->runtimeDataSize = runtimeDataSize;
272 header->unitSize = runtimeDataSize > 0 ? runtimeDataOffset + runtimeDataSize : baseSize;
273
274 const QString cachePath = localCacheFilePath(unitUrl);
275 if (!SaveableUnitPointer::writeDataToFile(
276 cachePath, reinterpret_cast<const char *>(header), sizeof(Unit),
277 reinterpret_cast<const char *>(base) + sizeof(Unit), sizeof(Unit),
278 baseSize - sizeof(Unit), runtimeDataStorage.constData(), runtimeDataOffset,
279 runtimeDataSize, errorString)) {
280 return false;
281 }
282
283 CompilationUnitMapper::invalidate(cachePath);
284 return true;
285}
286
287QStringList CompilationUnit::moduleRequests() const
288{
289 QStringList requests;
290 requests.reserve(data->moduleRequestTableSize);
291 for (uint i = 0; i < data->moduleRequestTableSize; ++i)
292 requests << stringAt(data->moduleRequestTable()[i]);
293 return requests;
294}
295
297{
298 for (ResolvedTypeReference *ref : std::as_const(resolvedTypes)) {
299 if (ref->type().typeId() == type)
300 return ref;
301 }
302 return nullptr;
303
304}
305
307{
308 // Add to type registry of composites
309 if (propertyCaches.needsVMEMetaObject(/*root object*/0)) {
310 // qmlType is only valid for types that have references to themselves.
311 if (type.isValid()) {
312 qmlType = type;
313 } else {
314 qmlType = QQmlMetaType::findCompositeType(
315 url(), this, (unitData()->flags & CompiledData::Unit::IsSingleton)
316 ? QQmlMetaType::Singleton
317 : QQmlMetaType::NonSingleton);
318 }
319
320 QQmlMetaType::registerInternalCompositeType(this);
321 } else {
322 const QV4::CompiledData::Object *obj = objectAt(/*root object*/0);
323 auto *typeRef = resolvedTypes.value(obj->inheritedTypeNameIndex);
324 Q_ASSERT(typeRef);
325 qmlType = typeRef->type();
326 }
327}
328
329bool RuntimeDataBlock::verifyChecksum(const DependentTypesHasher &dependencyHasher) const
330{
331 if (!dependencyHasher) {
332 for (size_t i = 0; i < sizeof(dependencyMD5Checksum); ++i) {
333 if (dependencyMD5Checksum[i] != 0)
334 return false;
335 }
336 return true;
337 }
338 const QByteArray checksum = dependencyHasher();
339 return checksum.size() == sizeof(dependencyMD5Checksum)
340 && memcmp(dependencyMD5Checksum, checksum.constData(),
341 sizeof(dependencyMD5Checksum)) == 0;
342}
343
344QQmlType CompilationUnit::qmlTypeForComponent(const QString &inlineComponentName) const
345{
346 if (inlineComponentName.isEmpty())
347 return qmlType;
348 return inlineComponentData[inlineComponentName].qmlType;
349}
350
352{
353 Q_ASSERT(qmlData);
354 const uint nObjects = qmlData->nObjects;
355
356 // An offset table for the objects, followed by each object, its bindings and its binding
357 // order. We pad each object so that the next one is aligned.
358 const auto objectSpan = [&](uint nBindings) -> quint32 {
359 return alignedTo<RuntimeObject>(sizeof(RuntimeObject) + nBindings * sizeof(RuntimeBinding)
360 + nBindings * sizeof(RuntimeBindingIndex));
361 };
362
363 quint32 size = sizeof(RuntimeDataBlock) + nObjects * sizeof(quint32_le);
364 for (uint i = 0; i < nObjects; ++i)
365 size += objectSpan(qmlData->objectAt(i)->nBindings);
366
367 runtimeDataStorage = QByteArray(size, 0);
368 char *base = runtimeDataStorage.data();
369
370 RuntimeDataBlock *block = reinterpret_cast<RuntimeDataBlock *>(base);
371 memset(block->dependencyMD5Checksum, 0, sizeof(block->dependencyMD5Checksum));
372 block->nObjects = nObjects;
373
374 quint32_le *objectOffsetTable = reinterpret_cast<quint32_le *>(base + sizeof(RuntimeDataBlock));
375 quint32 nextOffset = sizeof(RuntimeDataBlock) + nObjects * sizeof(quint32_le);
376
377 for (uint i = 0; i < nObjects; ++i) {
378 const Object *object = qmlData->objectAt(i);
379 const uint nBindings = object->nBindings;
380 objectOffsetTable[i] = nextOffset;
381
382 RuntimeObject *runtimeObject = reinterpret_cast<RuntimeObject *>(base + nextOffset);
383 runtimeObject->offsetToBindingOrder
384 = sizeof(RuntimeObject) + nBindings * sizeof(RuntimeBinding);
385 runtimeObject->objectId = -1;
386 nextOffset += objectSpan(nBindings);
387 }
388
389 runtimeData = block;
390}
391
392/*!
393 * \internal
394 *
395 * Allocate a table of \a count named objects in object \a objectIndex.
396 *
397 * We only know how many objects are named in each component once we have resolved the
398 * components. Therefore, the tables are appended to the runtime data as we go.
399 */
401{
402 Q_ASSERT(runtimeData);
403 const qsizetype tableOffset = runtimeDataStorage.size();
404 runtimeDataStorage.resize(tableOffset + count * sizeof(quint32_le));
405
406 char *base = runtimeDataStorage.data();
407 RuntimeDataBlock *block = reinterpret_cast<RuntimeDataBlock *>(base);
408 runtimeData = block;
409
410 RuntimeObject *runtimeObject = block->objectAt(resolvedIndex(objectIndex));
411 runtimeObject->nNamedObjectsInComponent = count;
412 runtimeObject->offsetToNamedObjectsInComponent
413 = tableOffset - (reinterpret_cast<char *>(runtimeObject) - base);
414 return runtimeObject->namedObjectsInComponentTable();
415}
416
417} // namespace CompiledData
418} // namespace QV4
419
420QT_END_NAMESPACE
Combined button and popup list for selecting options.
static quint32 alignedTo(quint32 size)
static const char magic_str[]
Definition qjsvalue.h:24
#define QV4_DATA_STRUCTURE_VERSION
void finalizeCompositeType(const QQmlType &type)
bool persistRuntimeData(const QUrl &unitUrl, QString *errorString)
ResolvedTypeReference * resolvedType(int id) const
quint32_le * allocateNamedObjectsInComponent(int objectIndex, quint32 count)
bool writeWithRuntimeData(const QUrl &unitUrl, Unit *header, QString *errorString) const
ResolvedTypeReferenceMap resolvedTypes
QQmlType qmlTypeForComponent(const QString &inlineComponentName=QString()) const
Q_QML_EXPORT bool saveToDisk(const QUrl &unitUrl, qxp::function_ref< QByteArray() const > sourceChecksum, QString *errorString) const
const CompiledObject * objectAt(int index) const
Q_QML_EXPORT bool loadFromDisk(const QUrl &url, const QDateTime &sourceTimeStamp, qxp::function_ref< QByteArray() const > sourceChecksum, QString *errorString)
const Object * objectAt(int idx) const
bool addToHash(QCryptographicHash *hash, QHash< quintptr, QByteArray > *checksums) const
bool verifyChecksum(const CompiledData::DependentTypesHasher &dependencyHasher) const
bool verifyHeader(QDateTime expectedSourceTimeStamp, QString *errorString) const
const QmlUnit * qmlUnit() const