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
qqmltypeloader.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 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:significant
4
5#include <private/qqmltypeloader_p.h>
6
7#include <private/qqmldirdata_p.h>
8#include <private/qqmlprofiler_p.h>
9#include <private/qqmlscriptblob_p.h>
10#include <private/qqmlscriptdata_p.h>
11#include <private/qqmlsourcecoordinate_p.h>
12#include <private/qqmltypedata_p.h>
13#include <private/qqmltypeloaderqmldircontent_p.h>
14#include <private/qqmltypeloaderthread_p.h>
15#include <private/qv4compiler_p.h>
16#include <private/qv4compilercontext_p.h>
17#include <private/qv4runtimecodegen_p.h>
18
19#include <QtQml/qqmlabstracturlinterceptor.h>
20#include <QtQml/qqmlengine.h>
21#include <QtQml/qqmlextensioninterface.h>
22#include <QtQml/qqmlfile.h>
23#include <QtQml/qqmlnetworkaccessmanagerfactory.h>
24
25#include <qtqml_tracepoints_p.h>
26
27#include <QtCore/qdir.h>
28#include <QtCore/qdirlisting.h>
29#include <QtCore/qfile.h>
30#include <QtCore/qlibraryinfo.h>
31#include <QtCore/qthread.h>
32
33#include <functional>
34
35#define ASSERT_LOADTHREAD()
36 Q_ASSERT(thread() && thread()->isThisThread())
37#define ASSERT_ENGINETHREAD()
38 Q_ASSERT(!engine()->jsEngine() || engine()->jsEngine()->thread()->isCurrentThread())
39
40QT_BEGIN_NAMESPACE
41
42Q_TRACE_POINT(qtqml, QQmlCompiling_entry, const QUrl &url)
43Q_TRACE_POINT(qtqml, QQmlCompiling_exit)
44
45/*!
46\class QQmlTypeLoader
47\brief The QQmlTypeLoader class abstracts loading files and their dependencies over the network.
48\internal
49
50The QQmlTypeLoader class is provided for the exclusive use of the QQmlTypeLoader class.
51
52Clients create QQmlDataBlob instances and submit them to the QQmlTypeLoader class
53through the QQmlTypeLoader::load() or QQmlTypeLoader::loadWithStaticData() methods.
54The loader then fetches the data over the network or from the local file system in an efficient way.
55QQmlDataBlob is an abstract class, so should always be specialized.
56
57Once data is received, the QQmlDataBlob::dataReceived() method is invoked on the blob. The
58derived class should use this callback to process the received data. Processing of the data can
59result in an error being set (QQmlDataBlob::setError()), or one or more dependencies being
60created (QQmlDataBlob::addDependency()). Dependencies are other QQmlDataBlob's that
61are required before processing can fully complete.
62
63To complete processing, the QQmlDataBlob::done() callback is invoked. done() is called when
64one of these three preconditions are met.
65
66\list 1
67\li The QQmlDataBlob has no dependencies.
68\li The QQmlDataBlob has an error set.
69\li All the QQmlDataBlob's dependencies are themselves "done()".
70\endlist
71
72Thus QQmlDataBlob::done() will always eventually be called, even if the blob has an error set.
73*/
74
75void QQmlTypeLoader::invalidate()
76{
78
79 shutdownThread();
80
81#if QT_CONFIG(qml_network)
82 // Need to delete the network replies after
83 // the loader thread is shutdown as it could be
84 // getting new replies while we clear them
85 QQmlTypeLoaderThreadDataPtr data(&m_data);
86 data->networkReplies.clear();
87#endif // qml_network
88}
89
90void QQmlTypeLoader::addUrlInterceptor(QQmlAbstractUrlInterceptor *urlInterceptor)
91{
93 QQmlTypeLoaderConfiguredDataPtr data(&m_data);
94 data->urlInterceptors.append(urlInterceptor);
95}
96
97void QQmlTypeLoader::removeUrlInterceptor(QQmlAbstractUrlInterceptor *urlInterceptor)
98{
100 QQmlTypeLoaderConfiguredDataPtr data(&m_data);
101 data->urlInterceptors.removeOne(urlInterceptor);
102}
103
104QList<QQmlAbstractUrlInterceptor *> QQmlTypeLoader::urlInterceptors() const
105{
107 QQmlTypeLoaderConfiguredDataConstPtr data(&m_data);
108 return data->urlInterceptors;
109}
110
111QUrl QQmlTypeLoader::interceptUrl(const QUrl &url, QQmlAbstractUrlInterceptor::DataType type) const
112{
113 // Can be called from either thread, but only after interceptor setup is done.
114 // Mustn't be called with the lock already held.
115
116 switch (type) {
117 case QQmlAbstractUrlInterceptor::QmlFile:
118 case QQmlAbstractUrlInterceptor::JavaScriptFile: {
119 // Check the typeCache first. The typeCache is supposed to be indexed by original,
120 // unintercepted URLs, and the types it holds know their intercepted URLs. Therefore
121 // we can omit the URL interceptors by using the cache.
122
123 // TODO: This is not entirely true. There are some intercepted URLs in the typeCache, but
124 // that only matters if some URL interceptor is not idempotent. That is, if it maps
125 // URLs in a cycle. Doing so will produce interesting results all by itself.
126 // Nevertheless we should fix the typeCache. We will be able to fix it when we move
127 // all type lookup by name into the the type loader and all type lookup by "physical",
128 // intercepted URL into the global type registry. See QTBUG-142737
129
130 // We assume that calling the interceptor is more expensive than taking the shared data
131 // lock. Usually that's true because the interceptor will have to perform file system
132 // operations, either in the resource or the physical file system.
133 const QQmlTypeLoaderSharedDataConstPtr data(&m_data);
134 const auto it = data->typeCache.constFind(QQmlMetaType::normalizedUrl(url));
135 if (it != data->typeCache.constEnd())
136 return (*it)->url();
137 break;
138 }
139 case QQmlAbstractUrlInterceptor::QmldirFile:
140 // TODO: We could use qmldirCache here if it was keyed by original URLs
141 default:
142 break;
143 }
144
145 return interceptUncachedUrl(url, type);
146}
147
148static QUrl doInterceptUrl(
149 const QUrl &url, QQmlAbstractUrlInterceptor::DataType type,
150 const QList<QQmlAbstractUrlInterceptor *> &urlInterceptors)
151{
152 QUrl result = url;
153 for (QQmlAbstractUrlInterceptor *interceptor : urlInterceptors)
154 result = interceptor->intercept(result, type);
155 return result;
156}
157
158QUrl QQmlTypeLoader::interceptUncachedUrl(const QUrl &url,
159 QQmlAbstractUrlInterceptor::DataType type) const
160{
161 // Can be called from either thread, but only after interceptor setup is done.
162
163 QQmlTypeLoaderConfiguredDataConstPtr data(&m_data);
164 return doInterceptUrl(url, type, data->urlInterceptors);
165}
166
167bool QQmlTypeLoader::hasUrlInterceptors() const
168{
169 // Can be called from either thread, but only after interceptor setup is done.
170 QQmlTypeLoaderConfiguredDataConstPtr data(&m_data);
171 return !data->urlInterceptors.isEmpty();
172}
173
174#if QT_CONFIG(qml_debug)
175void QQmlTypeLoader::setProfiler(QQmlProfiler *profiler)
176{
177 ASSERT_ENGINETHREAD();
178
179 QQmlTypeLoaderConfiguredDataPtr data(&m_data);
180 Q_ASSERT(!data->profiler);
181 data->profiler.reset(profiler);
182}
183#endif
184
185struct PlainLoader {
186 void loadThread(QQmlTypeLoader *loader, const QQmlDataBlob::Ptr &blob) const
187 {
188 loader->loadThread(blob);
189 }
190 void load(QQmlTypeLoader *loader, const QQmlDataBlob::Ptr &blob) const
191 {
192 loader->ensureThread()->load(blob);
193 }
194 void loadAsync(QQmlTypeLoader *loader, const QQmlDataBlob::Ptr &blob) const
195 {
196 loader->ensureThread()->loadAsync(blob);
197 }
198};
199
202 StaticLoader(const QByteArray &data) : data(data) {}
203
204 void loadThread(QQmlTypeLoader *loader, const QQmlDataBlob::Ptr &blob) const
205 {
206 loader->loadWithStaticDataThread(blob, data);
207 }
208 void load(QQmlTypeLoader *loader, const QQmlDataBlob::Ptr &blob) const
209 {
210 loader->ensureThread()->loadWithStaticData(blob, data);
211 }
212 void loadAsync(QQmlTypeLoader *loader, const QQmlDataBlob::Ptr &blob) const
213 {
214 loader->ensureThread()->loadWithStaticDataAsync(blob, data);
215 }
216};
217
220 CachedLoader(const QQmlPrivate::CachedQmlUnit *unit) : unit(unit) {}
221
222 void loadThread(QQmlTypeLoader *loader, const QQmlDataBlob::Ptr &blob) const
223 {
224 loader->loadWithCachedUnitThread(blob, unit);
225 }
226 void load(QQmlTypeLoader *loader, const QQmlDataBlob::Ptr &blob) const
227 {
228 loader->ensureThread()->loadWithCachedUnit(blob, unit);
229 }
230 void loadAsync(QQmlTypeLoader *loader, const QQmlDataBlob::Ptr &blob) const
231 {
232 loader->ensureThread()->loadWithCachedUnitAsync(blob, unit);
233 }
234};
235
236template<typename Loader>
237void QQmlTypeLoader::doLoad(const Loader &loader, const QQmlDataBlob::Ptr &blob, Mode mode)
238{
239 // Can be called from either thread.
240#ifdef DATABLOB_DEBUG
241 qWarning("QQmlTypeLoader::doLoad(%s): %s thread", qPrintable(blob->urlString()),
242 (m_thread && m_thread->isThisThread()) ? "Compile" : "Engine");
243#endif
244 blob->startLoading();
245
246 if (QQmlTypeLoaderThread *t = thread(); t && t->isThisThread()) {
247 loader.loadThread(this, blob);
248 return;
249 }
250
251 if (mode == Asynchronous) {
252 blob->setIsAsync(true);
253 loader.loadAsync(this, blob);
254 return;
255 }
256
257 loader.load(this, blob);
258 if (blob->isCompleteOrError())
259 return;
260
261 if (mode == PreferSynchronous) {
262 blob->setIsAsync(true);
263 return;
264 }
265
266 Q_ASSERT(mode == Synchronous);
267 Q_ASSERT(thread());
268
269 QQmlTypeLoaderSharedDataConstPtr lock(&m_data);
270 do {
271 m_data.thread()->waitForNextMessage();
272 } while (!blob->isCompleteOrError());
273}
274
275/*!
276Load the provided \a blob from the network or filesystem.
277
278The loader must be locked.
279*/
280void QQmlTypeLoader::load(const QQmlDataBlob::Ptr &blob, Mode mode)
281{
282 // Can be called from either thread.
283 doLoad(PlainLoader(), blob, mode);
284}
285
286/*!
287Load the provided \a blob with \a data. The blob's URL is not used by the data loader in this case.
288
289The loader must be locked.
290*/
291void QQmlTypeLoader::loadWithStaticData(
292 const QQmlDataBlob::Ptr &blob, const QByteArray &data, Mode mode)
293{
294 // Can be called from either thread.
295 doLoad(StaticLoader(data), blob, mode);
296}
297
298void QQmlTypeLoader::loadWithCachedUnit(
299 const QQmlDataBlob::Ptr &blob, const QQmlPrivate::CachedQmlUnit *unit, Mode mode)
300{
301 // Can be called from either thread.
302 doLoad(CachedLoader(unit), blob, mode);
303}
304
305void QQmlTypeLoader::drop(const QQmlDataBlob::Ptr &blob)
306{
308
309 // We must not destroy a QQmlDataBlob from the main thread
310 // since it will shuffle its dependencies around.
311 // Therefore, if we're not on the type loader thread,
312 // we defer the destruction to the type loader thread.
313 if (QQmlTypeLoaderThread *t = thread(); t && !t->isThisThread())
314 t->drop(blob);
315}
316
317void QQmlTypeLoader::loadWithStaticDataThread(const QQmlDataBlob::Ptr &blob, const QByteArray &data)
318{
320
321 setData(blob, data, DataOrigin::Static);
322}
323
324void QQmlTypeLoader::loadWithCachedUnitThread(const QQmlDataBlob::Ptr &blob, const QQmlPrivate::CachedQmlUnit *unit)
325{
327
328 setCachedUnit(blob, unit);
329}
330
331void QQmlTypeLoader::loadThread(const QQmlDataBlob::Ptr &blob)
332{
334
335 if (blob->m_url.isEmpty()) {
336 QQmlError error;
337 error.setDescription(QLatin1String("Invalid null URL"));
338 blob->setError(error);
339 return;
340 }
341
342 if (QQmlFile::isSynchronous(blob->m_url)) {
343 const QString fileName = QQmlFile::urlToLocalFileOrQrc(blob->m_url);
344 if (fileName.isEmpty()) {
345 blob->setError(QLatin1String("URL cannot be represented as a local file: "
346 "unexpected NUL or percent-encoded directory separator "
347 "(%2F, or %5C on Windows)."));
348 return;
349 }
350
351 const bool exists = fileExists(fileName);
352 if (!exists && !isResource(fileName) && QFileInfo::exists(fileName)) {
353 // If the file doesn't exist at all, that's fine. It may be cached. If it's a case
354 // mismatch, though, we have to error out.
355 // NB: The resource file system is case-sensitive. No need to check there.
356 blob->setError(QLatin1String("File name case mismatch"));
357 return;
358 }
359
360 if (blob->setProgress(1.f) && blob->isAsync())
361 thread()->callDownloadProgressChanged(blob, 1.);
362
363 setData(blob, fileName, exists);
364
365 } else {
366#if QT_CONFIG(qml_network)
367 QNetworkReply *reply = thread()->networkAccessManager()->get(QNetworkRequest(blob->m_url));
368 QQmlTypeLoaderNetworkReplyProxy *nrp = thread()->networkReplyProxy();
369
370 QQmlTypeLoaderThreadDataPtr data(&m_data);
371 data->networkReplies.insert(reply, blob);
372
373 if (reply->isFinished()) {
374 nrp->manualFinished(reply);
375 } else {
376 QObject::connect(reply, &QNetworkReply::downloadProgress,
377 nrp, &QQmlTypeLoaderNetworkReplyProxy::downloadProgress);
378 QObject::connect(reply, &QNetworkReply::finished,
379 nrp, &QQmlTypeLoaderNetworkReplyProxy::finished);
380 }
381
382#ifdef DATABLOB_DEBUG
383 qWarning("QQmlDataBlob: requested %s", qPrintable(blob->urlString()));
384#endif // DATABLOB_DEBUG
385#endif // qml_network
386 }
387}
388
389#define DATALOADER_MAXIMUM_REDIRECT_RECURSION 16
390
391#if QT_CONFIG(qml_network)
392void QQmlTypeLoader::networkReplyFinished(QNetworkReply *reply)
393{
394 ASSERT_LOADTHREAD();
395
396 reply->deleteLater();
397
398 QQmlTypeLoaderThreadDataPtr data(&m_data);
399 QQmlRefPointer<QQmlDataBlob> blob = data->networkReplies.take(reply);
400
401 Q_ASSERT(blob);
402
403 blob->m_redirectCount++;
404
405 if (blob->m_redirectCount < DATALOADER_MAXIMUM_REDIRECT_RECURSION) {
406 QVariant redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
407 if (redirect.isValid()) {
408 QUrl url = reply->url().resolved(redirect.toUrl());
409 blob->m_finalUrl = url;
410 blob->m_finalUrlString.clear();
411
412 QNetworkReply *reply = thread()->networkAccessManager()->get(QNetworkRequest(url));
413 QObject *nrp = thread()->networkReplyProxy();
414 QObject::connect(reply, SIGNAL(finished()), nrp, SLOT(finished()));
415 data->networkReplies.insert(reply, std::move(blob));
416#ifdef DATABLOB_DEBUG
417 qWarning("QQmlDataBlob: redirected to %s", qPrintable(blob->finalUrlString()));
418#endif
419 return;
420 }
421 }
422
423 if (reply->error()) {
424 blob->networkError(reply->error());
425 } else {
426 QByteArray data = reply->readAll();
427 setData(blob, data, DataOrigin::Device);
428 }
429}
430
431void QQmlTypeLoader::networkReplyProgress(QNetworkReply *reply,
432 qint64 bytesReceived, qint64 bytesTotal)
433{
434 ASSERT_LOADTHREAD();
435
436 QQmlTypeLoaderThreadDataConstPtr data(&m_data);
437 const QQmlRefPointer<QQmlDataBlob> blob = data->networkReplies.value(reply);
438
439 Q_ASSERT(blob);
440
441 if (bytesTotal != 0) {
442 const qreal progress = (qreal(bytesReceived) / qreal(bytesTotal));
443 if (blob->setProgress(progress) && blob->isAsync())
444 thread()->callDownloadProgressChanged(blob, blob->progress());
445 }
446}
447#endif // qml_network
448
449/*! \internal
450Call the initializeEngine() method on \a iface. Used by QQmlTypeLoader to ensure it
451gets called in the correct thread.
452*/
453template<class Interface>
455 Interface *iface, QQmlTypeLoaderThread *thread, QQmlTypeLoaderLockedData *data,
456 const char *uri)
457{
458 // Can be called from either thread
459 // Must not touch engine if called from type loader thread
460
461 if (thread && thread->isThisThread())
462 thread->initializeEngine(iface, uri);
463 else
464 iface->initializeEngine(data->engine()->qmlEngine(), uri);
465}
466
467void QQmlTypeLoader::initializeEngine(QQmlEngineExtensionInterface *iface, const char *uri)
468{
469 // Can be called from either thread
470 doInitializeEngine(iface, thread(), &m_data, uri);
471}
472
473void QQmlTypeLoader::initializeEngine(QQmlExtensionInterface *iface, const char *uri)
474{
475 // Can be called from either thread
476 doInitializeEngine(iface, thread(), &m_data, uri);
477}
478
479/*!
480 * \internal
481 * Use the given \a data as source code for the given \a blob. \a origin states where the \a data
482 * came from and what we can do with it. DataOrigin::Static means that it's arbitrary static data
483 * passed by the user. We shall not produce a .qmlc file for it and we shall disregard any existing
484 * compilation units. DataOrigin::Device means that it was loaded from a file or other device and
485 * can be assumed to remain the same. We can use any caching mechanism to load a compilation unit
486 * for it and we can produce a .qmlc file for it.
487 */
488void QQmlTypeLoader::setData(const QQmlDataBlob::Ptr &blob, const QByteArray &data, DataOrigin origin)
489{
491
492 QQmlDataBlob::SourceCodeData d;
493 d.inlineSourceCode = QString::fromUtf8(data);
494 d.hasInlineSourceCode = true;
495 d.hasStaticData = (origin == DataOrigin::Static);
496 setData(blob, d);
497}
498
499void QQmlTypeLoader::setData(const QQmlDataBlob::Ptr &blob, const QString &fileName, bool exists)
500{
502
503 QQmlDataBlob::SourceCodeData d;
504 d.fileInfo = QFileInfo(fileName);
505 d.fileExists = exists;
506 setData(blob, d);
507}
508
509void QQmlTypeLoader::setData(const QQmlDataBlob::Ptr &blob, const QQmlDataBlob::SourceCodeData &d)
510{
512
513 Q_TRACE_SCOPE(QQmlCompiling, blob->url());
514 QQmlCompilingProfiler prof(profiler(), blob.data());
515
516 blob->m_inCallback = true;
517
518 blob->dataReceived(d);
519
520 if (!blob->isError() && !blob->isWaiting())
521 blob->allDependenciesDone();
522
523 blob->m_inCallback = false;
524
525 blob->tryDone();
526}
527
528void QQmlTypeLoader::setCachedUnit(const QQmlDataBlob::Ptr &blob, const QQmlPrivate::CachedQmlUnit *unit)
529{
531
532 Q_TRACE_SCOPE(QQmlCompiling, blob->url());
533 QQmlCompilingProfiler prof(profiler(), blob.data());
534
535 blob->m_inCallback = true;
536
537 blob->initializeFromCachedUnit(unit);
538
539 if (!blob->isError() && !blob->isWaiting())
540 blob->allDependenciesDone();
541
542 blob->m_inCallback = false;
543
544 blob->tryDone();
545}
546
547static bool isPathAbsolute(const QString &path)
548{
549#if defined(Q_OS_UNIX)
550 return (path.at(0) == QLatin1Char('/'));
551#else
552 QFileInfo fi(path);
553 return fi.isAbsolute();
554#endif
555}
556
557static bool isPathQrcOrAbsolute(const QString &path)
558{
559 return path.startsWith(u':') || isPathAbsolute(path);
560}
561
562// importPathList() and the qmldir candidate paths derived from it are a mixture of absolute
563// file system paths, qrc paths (":/...") and URLs (e.g. "qrc:/...", "file:///...", remote URLs,
564// or whatever a URL interceptor produced). cleanFilePath() and fileExists() only understand
565// paths, not URLs. Turn any local URL into its path here. Returns an empty string for empty
566// input or for anything that does not resolve to a local path (in particular remote URLs).
567static QString localPathForUrlOrPath(const QString &urlOrPath)
568{
569 if (urlOrPath.isEmpty() || isPathQrcOrAbsolute(urlOrPath))
570 return urlOrPath;
571 return QQmlFile::urlToLocalFileOrQrc(urlOrPath);
572}
573
574/*!
575 \internal
576*/
577QStringList QQmlTypeLoader::importPathList(PathType type) const
578{
579 QQmlTypeLoaderConfiguredDataConstPtr data(&m_data);
580 if (type == LocalOrRemote)
581 return data->importPaths;
582
583 QStringList list;
584 for (const QString &path : data->importPaths) {
585 // The import paths are a mixture of absolute file system paths and URLs. None of them
586 // starts with a bare ':' because addImportPath() rewrites qrc paths (":/foo") to
587 // "qrc:/foo" URLs before storing them. So an absolute-path check together with
588 // QQmlFile::isLocalFile() is enough to tell local entries (resolvable on the file
589 // system or in qrc) from remote ones.
590 if ((isPathAbsolute(path) || QQmlFile::isLocalFile(path)) == (type == Local))
591 list.append(path);
592 }
593
594 return list;
595}
596
597/*!
598 \internal
599*/
600void QQmlTypeLoader::addImportPath(const QString &path, AddPathMode mode)
601{
602 qCDebug(lcQmlImport) << "addImportPath:" << path;
603
604 if (path.isEmpty())
605 return;
606
607 QUrl url = QUrl(path);
608 QString cPath;
609
610 if (url.scheme() == QLatin1String("file")) {
611 cPath = QQmlFile::urlToLocalFileOrQrc(url);
612 } else if (path.startsWith(QLatin1Char(':'))) {
613 // qrc directory, e.g. :/foo
614 // need to convert to a qrc url, e.g. qrc:/foo
615 cPath = QLatin1String("qrc") + path;
616 cPath.replace(QLatin1Char('\\'), QLatin1Char('/'));
617 } else if (url.isRelative() ||
618 (url.scheme().size() == 1 && QFile::exists(path)) ) { // windows path
619 QDir dir = QDir(path);
620 cPath = dir.canonicalPath();
621 } else {
622 cPath = path;
623 cPath.replace(QLatin1Char('\\'), QLatin1Char('/'));
624 }
625
626 QQmlTypeLoaderConfiguredDataPtr data(&m_data);
627 if (!cPath.isEmpty()) {
628 if (mode == PrependPath) {
629 // Prepending an existing path moves it to the front, to reflect
630 // its new, higher priority.
631 if (data->importPaths.contains(cPath))
632 data->importPaths.move(data->importPaths.indexOf(cPath), 0);
633 else
634 data->importPaths.prepend(cPath);
635 } else if (!data->importPaths.contains(cPath)) {
636 // Appending leaves an already known path untouched, so that we
637 // don't lower the priority of a path that was explicitly prepended.
638 data->importPaths.append(cPath);
639 }
640 }
641}
642
643/*!
644 \internal
645*/
646void QQmlTypeLoader::setImportPathList(const QStringList &paths)
647{
648 qCDebug(lcQmlImport) << "setImportPathList:" << paths;
649
650 QQmlTypeLoaderConfiguredDataPtr data(&m_data);
651 data->importPaths.clear();
652 for (const QString &path : paths)
653 addImportPath(path, AppendPath);
654
655 // Our existing cached paths may have been invalidated
656 clearQmldirInfo();
657}
658
659
660/*!
661 \internal
662*/
663void QQmlTypeLoader::setPluginPathList(const QStringList &paths)
664{
665 qCDebug(lcQmlImport) << "setPluginPathList:" << paths;
666 QQmlTypeLoaderConfiguredDataPtr data(&m_data);
667 data->pluginPaths = paths;
668}
669
670/*!
671 \internal
672*/
673void QQmlTypeLoader::addPluginPath(const QString& path, AddPathMode mode)
674{
675 qCDebug(lcQmlImport) << "addPluginPath:" << path;
676
677 QQmlTypeLoaderConfiguredDataPtr data(&m_data);
678
679 QUrl url = QUrl(path);
680 QString canonicalPath = path;
681 if (url.isRelative() || url.scheme() == QLatin1String("file")
682 || (url.scheme().size() == 1 && QFile::exists(path)) ) { // windows path
683 QDir dir = QDir(path);
684 canonicalPath = dir.canonicalPath();
685 }
686
687 if (mode == PrependPath)
688 data->pluginPaths.prepend(canonicalPath);
689 else
690 data->pluginPaths.append(canonicalPath);
691}
692
693#if QT_CONFIG(qml_network)
694QQmlNetworkAccessManagerFactoryPtrConst QQmlTypeLoader::networkAccessManagerFactory() const
695{
696 ASSERT_ENGINETHREAD();
697 return QQmlNetworkAccessManagerFactoryPtrConst(&m_data);
698}
699
700void QQmlTypeLoader::setNetworkAccessManagerFactory(QQmlNetworkAccessManagerFactory *factory)
701{
702 ASSERT_ENGINETHREAD();
703 QQmlNetworkAccessManagerFactoryPtr(&m_data).reset(factory);
704}
705
706QNetworkAccessManager *QQmlTypeLoader::createNetworkAccessManager(QObject *parent) const
707{
708 // Can be called from both threads, or even from a WorkerScript
709
710 // TODO: Calling the user's create() method under the lock is quite rude.
711 // However, we've been doing so for a long time and stopping the
712 // practice would expose thread safety issues in user code.
713 // ### Qt7: Maybe change the factory interface to provide a different method
714 // that can be called without the lock.
715 if (const auto factory = QQmlNetworkAccessManagerFactoryPtrConst(&m_data))
716 return factory->create(parent);
717
718 return new QNetworkAccessManager(parent);
719}
720#endif // QT_CONFIG(qml_network)
721
722void QQmlTypeLoader::clearQmldirInfo()
723{
724 QQmlTypeLoaderThreadDataPtr data(&m_data);
725
726 auto itr = data->qmldirInfo.constBegin();
727 while (itr != data->qmldirInfo.constEnd()) {
728 const QQmlTypeLoaderThreadData::QmldirInfo *cache = *itr;
729 do {
730 const QQmlTypeLoaderThreadData::QmldirInfo *nextCache = cache->next;
731 delete cache;
732 cache = nextCache;
733 } while (cache);
734
735 ++itr;
736 }
737 data->qmldirInfo.clear();
738}
739
741 const QQmlTypeLoaderConfiguredDataPtr &data, QV4::ExecutionEngine *engine)
742{
743 data->diskCacheOptions = engine->diskCacheOptions();
744 data->debugInstructionPass = engine->debugInstructionPass();
745 data->initialized = true;
746}
747
748void QQmlTypeLoader::startThread()
749{
751
752 if (!m_data.thread()) {
753 // Re-read the relevant configuration values at the last possible moment before we start
754 // the thread. After the thread has been started, changing the configuration would result
755 // in UB. Therefore we can disregard this case. We need to re-read it because a preview
756 // or a debugger may have been connected in between.
757 QQmlTypeLoaderConfiguredDataPtr data(&m_data);
758 initializeConfiguredData(data, m_data.engine());
759 m_data.createThread(this);
760 }
761}
762
763void QQmlTypeLoader::shutdownThread()
764{
766
767 if (m_data.thread())
768 m_data.deleteThread();
769}
770
771QQmlTypeLoader::Blob::PendingImport::PendingImport(
772 const QQmlRefPointer<Blob> &blob, const QV4::CompiledData::Import *import,
773 QQmlImports::ImportFlags flags)
774 : uri(blob->stringAt(import->uriIndex))
775 , qualifier(blob->stringAt(import->qualifierIndex))
776 , type(static_cast<QV4::CompiledData::Import::ImportType>(quint32(import->type)))
777 , location(import->location)
778 , flags(flags)
779 , version(import->version)
780 , searchVersion(import->version)
781{
782}
783
784QQmlTypeLoader::Blob::Blob(const QUrl &url, QQmlDataBlob::Type type, QQmlTypeLoader *loader)
785 : QQmlDataBlob(url, type, loader)
786 , m_importCache(new QQmlImports(), QQmlRefPointer<QQmlImports>::Adopt)
787{
788}
789
790QQmlTypeLoader::Blob::~Blob()
791{
792}
793
794bool QQmlTypeLoader::Blob::fetchQmldir(
795 const QUrl &url, const QQmlTypeLoader::Blob::PendingImportPtr &import, int priority,
796 QList<QQmlError> *errors)
797{
798 assertTypeLoaderThread();
799
800 QQmlRefPointer<QQmlQmldirData> data = typeLoader()->getQmldir(url);
801
802 data->setPriority(this, import, priority);
803
804 if (data->status() == Error) {
805 // This qmldir must not exist - which is not an error
806 return true;
807 } else if (data->status() == Complete) {
808 // This data is already available
809 return qmldirDataAvailable(data, errors);
810 }
811
812 // Wait for this data to become available
813 addDependency(data.data());
814 return true;
815}
816
817/*!
818 * \internal
819 * Import any qualified scripts of for \a import as listed in \a qmldir.
820 * Precondition is that \a import is actually qualified.
821 */
822void QQmlTypeLoader::Blob::importQmldirScripts(
823 const QQmlTypeLoader::Blob::PendingImportPtr &import,
824 const QQmlTypeLoaderQmldirContent &qmldir, const QUrl &qmldirUrl)
825{
826 assertTypeLoaderThread();
827
828 // A "prefer" directive in the qmldir redirects file lookups to another
829 // location, typically the compiled-in resources. Honor it here so that
830 // qualified scripts resolve from the same location as components and
831 // unqualified scripts, which inherit the redirect via the import URL set
832 // up by QQmlImports::addLibraryImport(). Otherwise a deployed module whose
833 // files only exist in the resources would try to load the script from a
834 // nonexistent file next to the qmldir on disk. See QTBUG-143877.
835 QQmlTypeLoaderQmldirContent redirectedQmldir = qmldir;
836 const QUrl scriptBaseUrl = redirectedQmldir.hasRedirection()
837 ? QUrl{QQmlImports::redirectQmldirContent(typeLoader(), &redirectedQmldir)}
838 : qmldirUrl;
839 const auto qmldirScripts = redirectedQmldir.scripts();
840 for (const QQmlDirParser::Script &script : qmldirScripts) {
841 const QUrl plainUrl = QUrl(script.fileName);
842 const QUrl scriptUrl = scriptBaseUrl.resolved(plainUrl);
843 QQmlRefPointer<QQmlScriptBlob> blob = typeLoader()->getScript(scriptUrl, plainUrl);
844
845 // Self-import via qmldir is OK-ish. We ignore it.
846 if (blob.data() == this)
847 continue;
848
849 addDependency(blob.data());
850 scriptImported(blob, import->location, script.nameSpace, import->qualifier);
851 }
852}
853
854template<typename URL>
856 QQmlTypeLoader::Blob *self,
857 const QQmlTypeLoader::Blob::PendingImportPtr &import, const QString &qmldirFilePath,
858 const URL &qmldirUrl)
859{
860 self->assertTypeLoaderThread();
861
862 const QQmlTypeLoaderQmldirContent qmldir = self->typeLoader()->qmldirContent(qmldirFilePath);
863 if (!import->qualifier.isEmpty())
864 self->importQmldirScripts(import, qmldir, QUrl(qmldirUrl));
865
866 if (qmldir.plugins().isEmpty()) {
867 // If the qmldir does not register a plugin, we might still have declaratively
868 // registered types (if we are dealing with an application instead of a library)
869 // We should use module name given in the qmldir rather than the one given by the
870 // import since the import may be a directory import.
871 auto module = QQmlMetaType::typeModule(qmldir.typeNamespace(), import->version);
872 if (!module)
873 QQmlMetaType::qmlRegisterModuleTypes(qmldir.typeNamespace());
874 // else: If the module already exists, the types must have been already registered
875 }
876}
877
879 const QQmlTypeLoader::Blob::PendingImportPtr &import, QList<QQmlError> *errors)
880{
881 QQmlError error;
882 QString reason = errors->front().description();
883 if (reason.size() > 512)
884 reason = reason.first(252) + QLatin1String("... ...") + reason.last(252);
885 if (import->version.hasMajorVersion()) {
886 error.setDescription(
887 QQmlImports::tr("module \"%1\" version %2.%3 cannot be imported because:\n%4")
888 .arg(import->uri, QString::number(import->version.majorVersion()),
889 import->version.hasMinorVersion()
890 ? QString::number(import->version.minorVersion())
891 : QLatin1String("x"),
892 reason));
893 } else {
894 error.setDescription(QQmlImports::tr("module \"%1\" cannot be imported because:\n%2")
895 .arg(import->uri, reason));
896 }
897 errors->prepend(error);
898}
899
900bool QQmlTypeLoader::Blob::handleLocalQmldirForImport(
901 const PendingImportPtr &import, const QString &qmldirFilePath,
902 const QString &qmldirUrl, QList<QQmlError> *errors)
903{
904 // This is a local library import
905 const QTypeRevision actualVersion = m_importCache->addLibraryImport(
906 typeLoader(), import->uri, import->qualifier, import->version, qmldirFilePath,
907 qmldirUrl, import->flags, import->precedence, errors);
908 if (!actualVersion.isValid())
909 return false;
910
911 // Use more specific version for dependencies if possible
912 if (actualVersion.hasMajorVersion())
913 import->version = actualVersion;
914
915 if (!loadImportDependencies(import, qmldirFilePath, import->flags, errors)) {
916 addDependencyImportError(import, errors);
917 return false;
918 }
919
920 postProcessQmldir(this, import, qmldirFilePath, qmldirUrl);
921 return true;
922}
923
924bool QQmlTypeLoader::Blob::updateQmldir(const QQmlRefPointer<QQmlQmldirData> &data, const QQmlTypeLoader::Blob::PendingImportPtr &import, QList<QQmlError> *errors)
925{
926 // TODO: Shouldn't this lock?
927
928 assertTypeLoaderThread();
929
930 QString qmldirIdentifier = data->urlString();
931 QString qmldirUrl = qmldirIdentifier.left(qmldirIdentifier.lastIndexOf(QLatin1Char('/')) + 1);
932
933 typeLoader()->setQmldirContent(qmldirIdentifier, data->content());
934
935 const QTypeRevision version = m_importCache->updateQmldirContent(
936 typeLoader(), import->uri, import->version, import->qualifier, qmldirIdentifier,
937 qmldirUrl, errors);
938 if (!version.isValid())
939 return false;
940
941 // Use more specific version for dependencies if possible
942 if (version.hasMajorVersion())
943 import->version = version;
944
945 if (!loadImportDependencies(import, qmldirIdentifier, import->flags, errors))
946 return false;
947
948 import->priority = 0;
949
950 // Release this reference at destruction
951 m_qmldirs << data;
952
953 postProcessQmldir(this, import, qmldirIdentifier, qmldirUrl);
954 return true;
955}
956
957bool QQmlTypeLoader::Blob::addScriptImport(const QQmlTypeLoader::Blob::PendingImportPtr &import)
958{
959 assertTypeLoaderThread();
960 const QUrl url(import->uri);
961 QQmlTypeLoader *loader = typeLoader();
962 QQmlRefPointer<QQmlScriptBlob> blob = loader->getScript(finalUrl().resolved(url), url);
963 addDependency(blob.data());
964 scriptImported(blob, import->location, import->qualifier, QString());
965 return true;
966}
967
968bool QQmlTypeLoader::Blob::addFileImport(const QQmlTypeLoader::Blob::PendingImportPtr &import, QList<QQmlError> *errors)
969{
970 assertTypeLoaderThread();
971 QQmlImports::ImportFlags flags;
972
973 QUrl importUrl(import->uri);
974 QString path = importUrl.path();
975 path.append(QLatin1String(path.endsWith(QLatin1Char('/')) ? "qmldir" : "/qmldir"));
976 importUrl.setPath(path);
977
978 // Can't resolve a relative URL if we don't know where we are
979 if (!finalUrl().isValid() && importUrl.isRelative()) {
980 QQmlError error;
981 error.setDescription(
982 QString::fromLatin1("Can't resolve relative qmldir URL %1 on invalid base URL")
983 .arg(importUrl.toString()));
984 errors->append(error);
985 return false;
986 }
987
988 QUrl qmldirUrl = finalUrl().resolved(importUrl);
989 if (!QQmlImports::isLocal(qmldirUrl)) {
990 // This is a remote file; the import is currently incomplete
991 flags = QQmlImports::ImportIncomplete;
992 }
993
994 const QTypeRevision version = m_importCache->addFileImport(
995 typeLoader(), import->uri, import->qualifier, import->version, flags,
996 import->precedence, nullptr, errors);
997 if (!version.isValid())
998 return false;
999
1000 // Use more specific version for the qmldir if possible
1001 if (version.hasMajorVersion())
1002 import->version = version;
1003
1004 if (flags & QQmlImports::ImportIncomplete) {
1005 if (!fetchQmldir(qmldirUrl, import, 1, errors))
1006 return false;
1007 } else {
1008 const QString qmldirFilePath = QQmlFile::urlToLocalFileOrQrc(qmldirUrl);
1009 if (!loadImportDependencies(import, qmldirFilePath, import->flags, errors))
1010 return false;
1011
1012 postProcessQmldir(this, import, qmldirFilePath, qmldirUrl);
1013 }
1014
1015 return true;
1016}
1017
1018bool QQmlTypeLoader::Blob::addLibraryImport(const QQmlTypeLoader::Blob::PendingImportPtr &import, QList<QQmlError> *errors)
1019{
1020 assertTypeLoaderThread();
1021
1022 const LocalQmldirResult qmldirResult = typeLoader()->locateLocalQmldir(this, import, errors);
1023 switch (qmldirResult) {
1024 case QmldirFound:
1025 return true;
1026 case QmldirNotFound: {
1027 if (!loadImportDependencies(import, QString(), import->flags, errors)) {
1028 addDependencyImportError(import, errors);
1029 return false;
1030 }
1031 break;
1032 }
1033 case QmldirInterceptedToRemote:
1034 break;
1035 case QmldirRejected:
1036 return false;
1037 }
1038
1039 // If there is a qmldir we cannot see, yet, then we have to wait.
1040 // The qmldir might contain import directives.
1041 // TODO: This should trigger on any potentially remote URLs, not only intercepted ones.
1042 // However, fixing this would open the door for follow-up problems while providing
1043 // rather limited benefits.
1044 if (qmldirResult != QmldirInterceptedToRemote && registerPendingTypes(import)) {
1045 if (m_importCache->addLibraryImport(
1046 typeLoader(), import->uri, import->qualifier, import->version, QString(),
1047 QString(), import->flags, import->precedence, errors).isValid()) {
1048 return true;
1049 }
1050
1051 return false;
1052 }
1053
1054 // We haven't yet resolved this import
1055 m_unresolvedImports << import;
1056
1057 // Add this library and request the possible locations for it
1058 const QTypeRevision version = m_importCache->addLibraryImport(
1059 typeLoader(), import->uri, import->qualifier, import->version, QString(),
1060 QString(), import->flags | QQmlImports::ImportIncomplete, import->precedence,
1061 errors);
1062
1063 if (!version.isValid())
1064 return false;
1065
1066 // Use more specific version for finding the qmldir if possible
1067 if (version.hasMajorVersion())
1068 import->version = version;
1069
1070 const bool hasInterceptors = m_typeLoader->hasUrlInterceptors();
1071
1072 // Query any network import paths for this library.
1073 // Interceptor might redirect local paths.
1074 QStringList remotePathList = typeLoader()->importPathList(
1075 hasInterceptors ? LocalOrRemote : Remote);
1076 if (!remotePathList.isEmpty()) {
1077 // Probe for all possible locations
1078 int priority = 0;
1079 const QStringList qmlDirPaths = QQmlImports::completeQmldirPaths(
1080 import->uri, remotePathList, import->searchVersion);
1081 for (const QString &qmldirPath : qmlDirPaths) {
1082 if (hasInterceptors) {
1083 QUrl url = m_typeLoader->interceptUrl(
1084 QQmlImports::urlFromLocalFileOrQrcOrUrl(qmldirPath),
1085 QQmlAbstractUrlInterceptor::QmldirFile);
1086 if (!QQmlFile::isLocalFile(url)
1087 && !fetchQmldir(url, import, ++priority, errors)) {
1088 return false;
1089 }
1090 } else if (!fetchQmldir(QUrl(qmldirPath), import, ++priority, errors)) {
1091 return false;
1092 }
1093 }
1094 }
1095
1096 return true;
1097}
1098
1099bool QQmlTypeLoader::Blob::registerPendingTypes(const PendingImportPtr &import)
1100{
1101 assertTypeLoaderThread();
1102
1103 return
1104 // Major version of module already registered:
1105 // We believe that the registration is complete.
1106 QQmlMetaType::typeModule(import->uri, import->version)
1107
1108 // Otherwise, try to register further module types.
1109 || QQmlMetaType::qmlRegisterModuleTypes(import->uri)
1110
1111 // Otherwise, there is no way to register any further types.
1112 // Try with any module of that name.
1113 || QQmlMetaType::latestModuleVersion(import->uri).isValid();
1114}
1115
1116bool QQmlTypeLoader::Blob::addImport(const QV4::CompiledData::Import *import,
1117 QQmlImports::ImportFlags flags, QList<QQmlError> *errors)
1118{
1119 assertTypeLoaderThread();
1120 return addImport(std::make_shared<PendingImport>(this, import, flags), errors);
1121}
1122
1123bool QQmlTypeLoader::Blob::addImport(
1124 const QQmlTypeLoader::Blob::PendingImportPtr &import, QList<QQmlError> *errors)
1125{
1126 assertTypeLoaderThread();
1127
1128 Q_ASSERT(errors);
1129
1130 switch (import->type)
1131 {
1132 case QV4::CompiledData::Import::ImportLibrary:
1133 return addLibraryImport(import, errors);
1134 case QV4::CompiledData::Import::ImportFile:
1135 return addFileImport(import ,errors);
1136 case QV4::CompiledData::Import::ImportScript:
1137 return addScriptImport(import);
1138 case QV4::CompiledData::Import::ImportInlineComponent:
1139 Q_UNREACHABLE_RETURN(false); // addImport is never called with an inline component import
1140 }
1141
1142 Q_UNREACHABLE_RETURN(false);
1143}
1144
1145void QQmlTypeLoader::Blob::dependencyComplete(const QQmlDataBlob::Ptr &blob)
1146{
1147 assertTypeLoaderThread();
1148
1149 if (blob->type() == QQmlDataBlob::QmldirFile) {
1150 QQmlQmldirData *data = static_cast<QQmlQmldirData *>(blob.data());
1151 QList<QQmlError> errors;
1152 if (!qmldirDataAvailable(data, &errors)) {
1153 Q_ASSERT(errors.size());
1154 QQmlError error(errors.takeFirst());
1155 error.setUrl(m_importCache->baseUrl());
1156 const QV4::CompiledData::Location importLocation = data->importLocation(this);
1157 error.setLine(qmlConvertSourceCoordinate<quint32, int>(importLocation.line()));
1158 error.setColumn(qmlConvertSourceCoordinate<quint32, int>(importLocation.column()));
1159 errors.prepend(error); // put it back on the list after filling out information.
1160 setError(errors);
1161 }
1162 }
1163}
1164
1165bool QQmlTypeLoader::Blob::loadDependentImports(
1166 const QList<QQmlDirParser::Import> &imports, const QString &qualifier,
1167 QTypeRevision version, QTypeRevision searchVersion, quint8 precedence,
1168 QQmlImports::ImportFlags flags, QList<QQmlError> *errors)
1169{
1170 assertTypeLoaderThread();
1171
1172 for (const auto &import : imports) {
1173 if (import.flags & QQmlDirParser::Import::Optional)
1174 continue;
1175 auto dependencyImport = std::make_shared<PendingImport>();
1176 dependencyImport->uri = import.module;
1177 dependencyImport->qualifier = qualifier;
1178 if (import.flags & QQmlDirParser::Import::Auto) {
1179 dependencyImport->version = version;
1180 dependencyImport->searchVersion = searchVersion;
1181 } else {
1182 dependencyImport->version = import.version;
1183 dependencyImport->searchVersion = import.version;
1184 }
1185 dependencyImport->flags = flags;
1186 dependencyImport->precedence = precedence;
1187
1188 qCDebug(lcQmlImport)
1189 << "loading dependent import" << dependencyImport->uri << "version"
1190 << dependencyImport->version << "as" << dependencyImport->qualifier;
1191
1192 if (!addImport(dependencyImport, errors)) {
1193 QQmlError error;
1194 error.setDescription(
1195 QString::fromLatin1(
1196 "Failed to load dependent import \"%1\" version %2.%3")
1197 .arg(dependencyImport->uri)
1198 .arg(dependencyImport->version.majorVersion())
1199 .arg(dependencyImport->version.minorVersion()));
1200 errors->append(error);
1201 return false;
1202 }
1203 }
1204
1205 return true;
1206}
1207
1208bool QQmlTypeLoader::Blob::loadImportDependencies(
1209 const QQmlTypeLoader::Blob::PendingImportPtr &currentImport, const QString &qmldirUri,
1210 QQmlImports::ImportFlags flags, QList<QQmlError> *errors)
1211{
1212 assertTypeLoaderThread();
1213
1214 QList<QQmlDirParser::Import> implicitImports
1215 = QQmlMetaType::moduleImports(currentImport->uri, currentImport->version);
1216 if (!qmldirUri.isEmpty())
1217 implicitImports += typeLoader()->qmldirContent(qmldirUri).imports();
1218
1219 // Prevent overflow from one category of import into the other.
1220 switch (currentImport->precedence) {
1221 case QQmlImportInstance::Implicit - 1:
1222 case QQmlImportInstance::Lowest: {
1223 QQmlError error;
1224 error.setDescription(
1225 QString::fromLatin1("Too many dependent imports for %1 %2.%3")
1226 .arg(currentImport->uri)
1227 .arg(currentImport->version.majorVersion())
1228 .arg(currentImport->version.minorVersion()));
1229 errors->append(error);
1230 return false;
1231 }
1232 default:
1233 break;
1234 }
1235
1236 if (!loadDependentImports(
1237 implicitImports, currentImport->qualifier, currentImport->version,
1238 currentImport->searchVersion, currentImport->precedence + 1, flags, errors)) {
1239 QQmlError error;
1240 error.setDescription(
1241 QString::fromLatin1(
1242 "Failed to load dependencies for module \"%1\" version %2.%3")
1243 .arg(currentImport->uri)
1244 .arg(currentImport->version.majorVersion())
1245 .arg(currentImport->version.minorVersion()));
1246 errors->append(error);
1247 return false;
1248 }
1249
1250 return true;
1251}
1252
1253static QQmlTypeLoaderConfiguredDataConstPtr configuredData(QQmlTypeLoaderLockedData *m_data)
1254{
1255 if (!QQmlTypeLoaderConfiguredDataConstPtr(m_data)->initialized)
1256 initializeConfiguredData(QQmlTypeLoaderConfiguredDataPtr(m_data), m_data->engine());
1257
1258 return QQmlTypeLoaderConfiguredDataConstPtr(m_data);
1259}
1260
1261QV4::Moth::DebugInstructionPass QQmlTypeLoader::debugInstructionPass()
1262{
1263 return configuredData(&m_data)->debugInstructionPass;
1264}
1265
1266bool QQmlTypeLoader::readCacheFile()
1267{
1268 return configuredData(&m_data)->diskCacheOptions & QV4::ExecutionEngine::DiskCache::QmlcRead;
1269}
1270
1271bool QQmlTypeLoader::writeCacheFile()
1272{
1273 return configuredData(&m_data)->diskCacheOptions & QV4::ExecutionEngine::DiskCache::QmlcWrite;
1274}
1275
1276QQmlMetaType::CacheMode QQmlTypeLoader::aotCacheMode()
1277{
1278 const QV4::ExecutionEngine::DiskCacheOptions options
1279 = configuredData(&m_data)->diskCacheOptions;
1280 if (!(options & QV4::ExecutionEngine::DiskCache::Aot))
1281 return QQmlMetaType::RejectAll;
1282 if (options & QV4::ExecutionEngine::DiskCache::AotByteCode)
1283 return QQmlMetaType::AcceptUntyped;
1284 return QQmlMetaType::RequireFullyTyped;
1285}
1286
1287bool QQmlTypeLoader::Blob::qmldirDataAvailable(const QQmlRefPointer<QQmlQmldirData> &data, QList<QQmlError> *errors)
1288{
1289 assertTypeLoaderThread();
1290 return data->processImports(this, [&](const PendingImportPtr &import) {
1291 return updateQmldir(data, import, errors);
1292 });
1293}
1294
1295static QStringList parseEnvPath(const QString &envImportPath)
1296{
1297 if (QDir::listSeparator() == u':') {
1298 // Double colons are interpreted as separator + resource path.
1299 QStringList paths = envImportPath.split(u':');
1300 bool wasEmpty = false;
1301 for (auto it = paths.begin(); it != paths.end();) {
1302 if (it->isEmpty()) {
1303 wasEmpty = true;
1304 it = paths.erase(it);
1305 } else {
1306 if (wasEmpty) {
1307 it->prepend(u':');
1308 wasEmpty = false;
1309 }
1310 ++it;
1311 }
1312 }
1313 return paths;
1314 } else {
1315 return envImportPath.split(QDir::listSeparator(), Qt::SkipEmptyParts);
1316 }
1317}
1318
1319/*!
1320Constructs a new type loader that uses the given \a engine.
1321*/
1322QQmlTypeLoader::QQmlTypeLoader(QV4::ExecutionEngine *engine)
1323 : m_data(engine)
1324{
1325 // Add default import and plugin paths. Paths are added in decreasting
1326 // priority, by appending to the path lists.
1327
1328 const bool isPluginApplication = QCoreApplication::testAttribute(Qt::AA_PluginApplication);
1329
1330 auto addEnvPath = [this, isPluginApplication](const char *var, auto addPath) {
1331 if (Q_UNLIKELY(!isPluginApplication && !qEnvironmentVariableIsEmpty(var))) {
1332 const QStringList paths = parseEnvPath(qEnvironmentVariable(var));
1333 for (const QString &path : paths)
1334 (this->*addPath)(path, AppendPath);
1335 }
1336 };
1337
1338 // Import paths, used for looking up QML modules, e.g. `MyModules/qmldir`
1339
1340#if defined(Q_OS_ANDROID)
1341 addImportPath(QStringLiteral("qrc:/android_rcc_bundle/qml"), AppendPath);
1342#endif
1343
1344 if (!isPluginApplication)
1345 addImportPath(QCoreApplication::applicationDirPath(), AppendPath);
1346
1347 addImportPath(QStringLiteral("qrc:/qt-project.org/imports"), AppendPath);
1348 addImportPath(QStringLiteral("qrc:/qt/qml"), AppendPath);
1349
1350 addEnvPath("QML2_IMPORT_PATH", &QQmlTypeLoader::addImportPath);
1351 addEnvPath("QML_IMPORT_PATH", &QQmlTypeLoader::addImportPath);
1352
1353 const auto qmlImportPaths = QLibraryInfo::paths(QLibraryInfo::QmlImportsPath);
1354 for (const auto &qmlImportPath : qmlImportPaths)
1355 addImportPath(qmlImportPath, AppendPath);
1356
1357 // Plugin paths, used for looking up the backing library of a QML module
1358
1359#if defined(Q_OS_ANDROID)
1360 addEnvPath("QT_BUNDLED_LIBS_PATH", &QQmlTypeLoader::addPluginPath);
1361#endif
1362 addEnvPath("QML_PLUGIN_PATH", &QQmlTypeLoader::addPluginPath);
1363
1364 const auto pluginPaths = QLibraryInfo::paths(QLibraryInfo::PluginsPath);
1365 for (const auto &pluginPath : pluginPaths)
1366 addPluginPath(pluginPath, AppendPath);
1367
1368 // Explicitly add "." to the plugin paths, to represent the path relative
1369 // to where the qmldir was found. We can't use addPluginPath() here, as
1370 // it will resolve the path to an absolute path based on the working dir.
1371 QQmlTypeLoaderConfiguredDataPtr data(&m_data);
1372 data->pluginPaths << QLatin1String(".");
1373}
1374
1375/*!
1376Destroys the type loader, first clearing the cache of any information about
1377loaded files.
1378*/
1379QQmlTypeLoader::~QQmlTypeLoader()
1380{
1382
1383 shutdownThread();
1384
1385 // Delete the thread before clearing the cache. Otherwise it will be started up again.
1386 invalidate();
1387
1388 clearCache();
1389
1390 clearQmldirInfo();
1391}
1392
1393template<typename Blob>
1395 const QQmlTypeLoaderSharedDataPtr &data, QQmlRefPointer<Blob> &&blob,
1396 QQmlTypeLoader::Mode mode)
1397{
1398 if ((mode == QQmlTypeLoader::PreferSynchronous && QQmlFile::isSynchronous(blob->finalUrl()))
1399 || mode == QQmlTypeLoader::Synchronous) {
1400 // this was started Asynchronous, but we need to force Synchronous
1401 // completion now.
1402
1403 // This only works when called directly from e.g. the UI thread, but not
1404 // when recursively called on the QML thread via resolveTypes()
1405
1406 // NB: We do not want to know whether the thread is the main thread, but specifically
1407 // that the thread is _not_ the thread we're waiting for.
1408 // If !QT_CONFIG(qml_type_loader_thread) the QML thread is the main thread.
1409
1410 QQmlTypeLoaderThread *thread = data.thread();
1411 if (thread && !thread->isThisThread()) {
1412 while (!blob->isCompleteOrError())
1413 thread->waitForNextMessage(); // Requires lock to be held, via data above
1414 }
1415 }
1416 return blob;
1417}
1418
1419/*!
1420Returns a QQmlTypeData for the specified \a url. The QQmlTypeData may be cached.
1421*/
1422QQmlRefPointer<QQmlTypeData> QQmlTypeLoader::getType(const QUrl &unNormalizedUrl, Mode mode)
1423{
1424 // This can be called from either thread.
1425
1426 Q_ASSERT(!unNormalizedUrl.isRelative() &&
1427 (QQmlFile::urlToLocalFileOrQrc(unNormalizedUrl).isEmpty() ||
1428 !QDir::isRelativePath(QQmlFile::urlToLocalFileOrQrc(unNormalizedUrl))));
1429
1430 QQmlRefPointer<QQmlTypeData> typeData;
1431 {
1432 const QUrl url = QQmlMetaType::normalizedUrl(unNormalizedUrl);
1433 QQmlTypeLoaderSharedDataPtr data(&m_data);
1434
1435 typeData = data->typeCache.value(url);
1436 if (typeData)
1437 return handleExisting(data, std::move(typeData), mode);
1438
1439 // Trim before adding the new type, so that we don't immediately trim it away
1440 if (data->typeCache.size() >= data->typeCacheTrimThreshold)
1441 trimCache(data);
1442
1443 typeData = QQml::makeRefPointer<QQmlTypeData>(url, this);
1444
1445 // TODO: if (compiledData == 0), is it safe to omit this insertion?
1446 data->typeCache.insert(url, typeData);
1447 }
1448
1449 return finalizeBlob(std::move(typeData), mode);
1450}
1451
1452/*!
1453Returns a QQmlTypeData for the given \a data with the provided base \a url. The
1454QQmlTypeData will not be cached.
1455*/
1456QQmlRefPointer<QQmlTypeData> QQmlTypeLoader::getType(
1457 const QByteArray &data, const QUrl &url, Mode mode)
1458{
1459 // Can be called from either thread.
1460
1461 QQmlRefPointer<QQmlTypeData> typeData = QQml::makeRefPointer<QQmlTypeData>(url, this);
1462 QQmlTypeLoader::loadWithStaticData(QQmlDataBlob::Ptr(typeData.data()), data, mode);
1463 return typeData;
1464}
1465
1466static bool isModuleUrl(const QUrl &url)
1467{
1468 return url.fragment() == QLatin1String("module") || url.path().endsWith(QLatin1String(".mjs"));
1469}
1470
1471QQmlRefPointer<QQmlScriptBlob> QQmlTypeLoader::getScript(const QUrl &unNormalizedUrl, Mode mode)
1472{
1473 // This can be called from either thread.
1474
1475 Q_ASSERT(!unNormalizedUrl.isRelative() &&
1476 (QQmlFile::urlToLocalFileOrQrc(unNormalizedUrl).isEmpty() ||
1477 !QDir::isRelativePath(QQmlFile::urlToLocalFileOrQrc(unNormalizedUrl))));
1478
1479 QQmlRefPointer<QQmlScriptBlob> scriptBlob;
1480 {
1481 const QUrl url = QQmlMetaType::normalizedUrl(unNormalizedUrl);
1482 QQmlTypeLoaderSharedDataPtr data(&m_data);
1483
1484 scriptBlob = data->scriptCache.value(url);
1485 if (scriptBlob)
1486 return handleExisting(data, std::move(scriptBlob), mode);
1487
1488 scriptBlob = QQml::makeRefPointer<QQmlScriptBlob>(url, this, isModuleUrl(url)
1489 ? QQmlScriptBlob::IsESModule::Yes
1490 : QQmlScriptBlob::IsESModule::No);
1491 data->scriptCache.insert(url, scriptBlob);
1492 }
1493
1494 return finalizeBlob(std::move(scriptBlob), mode);
1495}
1496
1497QQmlRefPointer<QV4::CompiledData::CompilationUnit> QQmlTypeLoader::injectModule(
1498 const QUrl &relativeUrl, const QV4::CompiledData::Unit *unit)
1499{
1501
1502 QQmlRefPointer<QQmlScriptBlob> blob = QQml::makeRefPointer<QQmlScriptBlob>(
1503 relativeUrl, this, QQmlScriptBlob::IsESModule::Yes);
1504 QQmlPrivate::CachedQmlUnit cached { unit, nullptr, nullptr};
1505
1506 {
1507 QQmlTypeLoaderSharedDataPtr data(&m_data);
1508 data->scriptCache.insert(relativeUrl, blob);
1509 }
1510
1511 loadWithCachedUnit(blob.data(), &cached, Synchronous);
1512 Q_ASSERT(blob->isComplete());
1513 return blob->scriptData()->compilationUnit();
1514}
1515
1516/*!
1517Return a QQmlScriptBlob for \a unNormalizedUrl or \a relativeUrl.
1518This assumes PreferSynchronous, and therefore the result may not be ready yet.
1519*/
1520QQmlRefPointer<QQmlScriptBlob> QQmlTypeLoader::getScript(
1521 const QUrl &unNormalizedUrl, const QUrl &relativeUrl)
1522{
1523 // Can be called from either thread
1524
1525 Q_ASSERT(!unNormalizedUrl.isRelative() &&
1526 (QQmlFile::urlToLocalFileOrQrc(unNormalizedUrl).isEmpty() ||
1527 !QDir::isRelativePath(QQmlFile::urlToLocalFileOrQrc(unNormalizedUrl))));
1528
1529 const QUrl url = QQmlMetaType::normalizedUrl(unNormalizedUrl);
1530
1531 QQmlRefPointer<QQmlScriptBlob> scriptBlob;
1532 {
1533 QQmlTypeLoaderSharedDataPtr data(&m_data);
1534 scriptBlob = data->scriptCache.value(url);
1535
1536 // Also try the relative URL since manually registering native modules doesn't require
1537 // passing an absolute URL and we don't have a reference URL for native modules.
1538 if (!scriptBlob && unNormalizedUrl != relativeUrl)
1539 scriptBlob = data->scriptCache.value(relativeUrl);
1540
1541 // Do not try to finish the loading via handleExisting() here.
1542 if (scriptBlob)
1543 return scriptBlob;
1544
1545 scriptBlob = QQml::makeRefPointer<QQmlScriptBlob>(url, this, isModuleUrl(url)
1546 ? QQmlScriptBlob::IsESModule::Yes
1547 : QQmlScriptBlob::IsESModule::No);
1548 data->scriptCache.insert(url, scriptBlob);
1549 }
1550
1551 return finalizeBlob(std::move(scriptBlob), PreferSynchronous);
1552}
1553
1554/*!
1555Returns a QQmlQmldirData for \a url. The QQmlQmldirData may be cached.
1556*/
1557QQmlRefPointer<QQmlQmldirData> QQmlTypeLoader::getQmldir(const QUrl &url)
1558{
1559 // Can be called from either thread.
1560
1561 Q_ASSERT(!url.isRelative() &&
1562 (QQmlFile::urlToLocalFileOrQrc(url).isEmpty() ||
1563 !QDir::isRelativePath(QQmlFile::urlToLocalFileOrQrc(url))));
1564
1565 QQmlRefPointer<QQmlQmldirData> qmldirData;
1566 {
1567 QQmlTypeLoaderSharedDataPtr data(&m_data);
1568 qmldirData = data->qmldirCache.value(url);
1569 if (qmldirData)
1570 return qmldirData;
1571
1572 qmldirData = QQml::makeRefPointer<QQmlQmldirData>(url, this);
1573 data->qmldirCache.insert(url, qmldirData);
1574 }
1575
1576 QQmlTypeLoader::load(QQmlDataBlob::Ptr(qmldirData.data()));
1577 return qmldirData;
1578}
1579
1580bool QQmlTypeLoader::isResource(const QString &path)
1581{
1582 const bool startsWithColon = path.at(0) == QLatin1Char(':');
1583#if defined(Q_OS_ANDROID)
1584 return startsWithColon || path.startsWith(QLatin1String("assets:/"), Qt::CaseInsensitive)
1585 || path.startsWith(QLatin1String("content:/"), Qt::CaseInsensitive);
1586#else
1587 return startsWithColon;
1588#endif
1589}
1590
1591/*!
1592Returns the clean filename of path via a directory cache.
1593Returns a empty string if the path does not exist.
1594
1595Why a directory cache? QML checks for files in many paths with
1596invalid directories. By caching whether a directory exists
1597we avoid many stats. We also cache the files' existence in the
1598directory, for the same reason.
1599*/
1600QString QQmlTypeLoader::cleanFilePath(const QString &path) const
1601{
1602 // Can be called from either thread.
1603
1604 if (path.isEmpty())
1605 return QString();
1606
1607 const QString cleanPath = QDir::cleanPath(path);
1608 if (isResource(cleanPath)) {
1609 // qrc resource
1610 QFileInfo fileInfo(cleanPath);
1611 return fileInfo.isFile() ? cleanPath : QString();
1612 }
1613
1614 return fileExists(cleanPath)
1615 ? cleanPath
1616 : QString();
1617}
1618
1619static QString stripTrailingSlashes(const QString &path)
1620{
1621 for (qsizetype length = path.size(); length > 0; --length) {
1622 if (path[length - 1] != QLatin1Char('/'))
1623 return path.left(length);
1624 }
1625
1626 return QString();
1627}
1628
1629bool QQmlTypeLoader::fileExists(const QString &dirPath, const QString &file) const
1630{
1631 // Can be called from either thread.
1632
1633 // We want to use QDirListing here because that gives us case-sensitive results even on
1634 // case-insensitive file systems. That is, for a file date.qml it only lists date.qml, not
1635 // Date.qml, dAte.qml, DATE.qml etc. QFileInfo::exists(), on the other hand, will happily
1636 // claim that Date.qml exists in such a situation on a case-insensitive file sysem. Such a
1637 // thing then shadows the JavaScript Date object and disaster ensues.
1638
1639 const QChar nullChar(QChar::Null);
1640 if (dirPath.isEmpty() || dirPath.contains(nullChar) || file.isEmpty()
1641 || file.contains(nullChar)) {
1642 return false;
1643 }
1644
1645 // NB: We really shouldn't see URLs (qrc:/ or the like) here. This is explicitly about paths.
1646 // We don't handle file:/ either.
1647
1648 if (isResource(dirPath)) {
1649 // The resource file system is case-sensitive. So we don't have to do the below gymnastics.
1650 // However, it changes spontanously as resources are loaded. Therefore we can't cache it.
1651 const QFileInfo info(dirPath + u'/' + file);
1652 return info.exists();
1653 }
1654
1655 const QString path = stripTrailingSlashes(dirPath);
1656
1657 QQmlTypeLoaderSharedDataConstPtr data(&m_data);
1658 return data->importDirCache.fileExists(path, file);
1659}
1660
1661
1662/*!
1663Returns true if the path is a directory via a directory cache. Cache is
1664shared with cleanFilePath().
1665*/
1666bool QQmlTypeLoader::directoryExists(const QString &path) const
1667{
1668 // Can be called from either thread.
1669
1670 if (path.isEmpty())
1671 return false;
1672
1673 if (isResource(path)) {
1674 // qrc resource
1675 QFileInfo fileInfo(path);
1676 return fileInfo.exists() && fileInfo.isDir();
1677 }
1678
1679 const QString dirPath = stripTrailingSlashes(path);
1680
1681 QQmlTypeLoaderSharedDataConstPtr data(&m_data);
1682 return data->importDirCache.directoryExists(path);
1683
1684}
1685
1686
1687/*!
1688
1689\internal
1690
1691Return a QQmlTypeLoaderQmldirContent for \a filePathIn.
1692The QQmlTypeLoaderQmldirContent may be cached.
1693
1694It can also be a remote path for a remote directory import, but it will have
1695been cached by now in this case.
1696*/
1697const QQmlTypeLoaderQmldirContent QQmlTypeLoader::qmldirContent(const QString &filePathIn)
1698{
1700
1701 QString filePath;
1702
1703 // Try to guess if filePathIn is already a URL. This is necessarily fragile, because
1704 // - paths can contain ':', which might make them appear as URLs with schemes.
1705 // - windows drive letters appear as schemes (thus "< 2" below).
1706 // - a "file:" URL is equivalent to the respective file, but will be treated differently.
1707 // Yet, this heuristic is the best we can do until we pass more structured information here,
1708 // for example a QUrl also for local files.
1709 QUrl url(filePathIn);
1710
1711 QQmlTypeLoaderThreadDataPtr data(&m_data);
1712
1713 if (url.scheme().size() < 2) {
1714 filePath = filePathIn;
1715 } else {
1716 filePath = QQmlFile::urlToLocalFileOrQrc(url);
1717 if (filePath.isEmpty()) { // Can't load the remote here, but should be cached
1718 if (auto entry = data->importQmlDirCache.value(filePathIn))
1719 return **entry;
1720 else
1721 return QQmlTypeLoaderQmldirContent();
1722 }
1723 }
1724
1725 QQmlTypeLoaderQmldirContent **val = data->importQmlDirCache.value(filePath);
1726 if (val)
1727 return **val;
1728 QQmlTypeLoaderQmldirContent *qmldir = new QQmlTypeLoaderQmldirContent;
1729
1730#define ERROR(description) { QQmlError e; e.setDescription(description); qmldir->setError(e); }
1731#define NOT_READABLE_ERROR QString(QLatin1String("module \"$$URI$$\" definition \"%1\" not readable"))
1732#define NOT_FOUND_ERROR QString(QLatin1String("cannot load module \"$$URI$$\": File \"%1\" not found"))
1733
1734 QFile file(filePath);
1735 if (!fileExists(filePath)) {
1736 ERROR(NOT_FOUND_ERROR.arg(filePath));
1737 } else if (file.open(QFile::ReadOnly)) {
1738 QByteArray data = file.readAll();
1739 qmldir->setContent(filePath, QString::fromUtf8(data));
1740 } else {
1741 ERROR(NOT_READABLE_ERROR.arg(filePath));
1742 }
1743
1744#undef ERROR
1745#undef NOT_READABLE_ERROR
1746#undef NOT_FOUND_ERROR
1747
1748 data->importQmlDirCache.insert(filePath, qmldir);
1749 return *qmldir;
1750}
1751
1752void QQmlTypeLoader::setQmldirContent(const QString &url, const QString &content)
1753{
1755
1756 QQmlTypeLoaderThreadDataPtr data(&m_data);
1757 QQmlTypeLoaderQmldirContent *qmldir;
1758 QQmlTypeLoaderQmldirContent **val = data->importQmlDirCache.value(url);
1759 if (val) {
1760 qmldir = *val;
1761 } else {
1762 qmldir = new QQmlTypeLoaderQmldirContent;
1763 data->importQmlDirCache.insert(url, qmldir);
1764 }
1765
1766 if (!qmldir->hasContent())
1767 qmldir->setContent(url, content);
1768}
1769
1770template<typename Blob>
1771void clearBlobs(QHash<QUrl, QQmlRefPointer<Blob>> *blobs)
1772{
1773 std::for_each(blobs->cbegin(), blobs->cend(), [](const QQmlRefPointer<Blob> &blob) {
1774 blob->resetTypeLoader();
1775 });
1776 blobs->clear();
1777}
1778
1779/*!
1780Clears cached information about loaded files, including any type data, scripts
1781and qmldir information.
1782*/
1783void QQmlTypeLoader::clearCache()
1784{
1785 // This looks dangerous because we're dropping live blobs on the engine thread.
1786 // However, it's safe because we shut down the type loader thread before we do so.
1787
1789
1790 // Temporarily shut the thread down and discard all messages, making it safe to
1791 // hack into the various data structures below.
1792 shutdownThread();
1793
1794 QQmlTypeLoaderThreadDataPtr threadData(&m_data);
1795 qDeleteAll(threadData->importQmlDirCache);
1796 threadData->checksumCache.clear();
1797 threadData->importQmlDirCache.clear();
1798
1799 QQmlTypeLoaderSharedDataPtr data(&m_data);
1800 clearBlobs(&data->typeCache);
1801 clearBlobs(&data->scriptCache);
1802 clearBlobs(&data->qmldirCache);
1803 data->typeCacheTrimThreshold = QQmlTypeLoaderSharedData::MinimumTypeCacheTrimThreshold;
1804 data->importDirCache.clear();
1805
1806 // The thread will auto-restart next time we need it.
1807}
1808
1809/*!
1810 \internal
1811 Remove any cached artifacts for \a url.
1812
1813 Returns \c true if anything was removed, or \c false otherwise.
1814*/
1815bool QQmlTypeLoader::removeFromCache(const QUrl &url)
1816{
1817 const QUrl normalized = QQmlMetaType::normalizedUrl(url);
1818 const QQmlTypeLoaderSharedDataPtr data(&m_data);
1819 return data->typeCache.remove(normalized) || data->scriptCache.remove(normalized)
1820 || data->qmldirCache.remove(normalized);
1821}
1822
1823void QQmlTypeLoader::trimCache()
1824{
1825 const QQmlTypeLoaderSharedDataPtr data(&m_data);
1826 trimCache(data);
1827}
1828
1829void QQmlTypeLoader::updateTypeCacheTrimThreshold(const QQmlTypeLoaderSharedDataPtr &data)
1830{
1831 // This can be called from either thread and is called from a method that locks.
1832
1833 int size = data->typeCache.size();
1834 if (size > data->typeCacheTrimThreshold)
1835 data->typeCacheTrimThreshold = size * 2;
1836 if (size < data->typeCacheTrimThreshold / 2) {
1837 data->typeCacheTrimThreshold
1838 = qMax(size * 2, int(QQmlTypeLoaderSharedData::MinimumTypeCacheTrimThreshold));
1839 }
1840}
1841
1842void QQmlTypeLoader::trimCache(const QQmlTypeLoaderSharedDataPtr &data)
1843{
1844 // This can be called from either thread. It has to be called while the type loader mutex
1845 // is locked. It drops potentially live blobs, but only ones which are isCompleteOrError and
1846 // are not depended on by other blobs.
1847
1848 while (true) {
1849 bool deletedOneType = false;
1850 for (auto iter = data->typeCache.begin(), end = data->typeCache.end(); iter != end;) {
1851 const QQmlRefPointer<QQmlTypeData> &typeData = iter.value();
1852
1853 // typeData->m_compiledData may be set early on in the proccess of loading a file, so
1854 // it's important to check the general loading status of the typeData before making any
1855 // other decisions.
1856 if (typeData->count() != 1 || !typeData->isCompleteOrError()) {
1857 ++iter;
1858 continue;
1859 }
1860
1861 // isCompleteOrError means the waitingFor list of this typeData is empty.
1862 // Therefore, it cannot interfere with other blobs on destruction anymore.
1863 // Therefore, we can drop it on either the engine thread or the type loader thread.
1864
1865 const QQmlRefPointer<QV4::CompiledData::CompilationUnit> &compilationUnit
1866 = typeData->m_compiledData;
1867 if (compilationUnit) {
1868 if (compilationUnit->count()
1869 > QQmlMetaType::countInternalCompositeTypeSelfReferences(
1870 compilationUnit) + 1) {
1871 ++iter;
1872 continue;
1873 }
1874
1875 QQmlMetaType::unregisterInternalCompositeType(compilationUnit);
1876 Q_ASSERT(compilationUnit->count() == 1);
1877 }
1878
1879 // There are no live objects of this type
1880 iter = data->typeCache.erase(iter);
1881 deletedOneType = true;
1882 }
1883
1884 if (!deletedOneType)
1885 break;
1886 }
1887
1888 // TODO: release any scripts which are no longer referenced by any types
1889
1890 updateTypeCacheTrimThreshold(data);
1891
1892 QQmlMetaType::freeUnusedTypesAndCaches();
1893}
1894
1895bool QQmlTypeLoader::isTypeLoaded(const QUrl &url) const
1896{
1897 const QQmlTypeLoaderSharedDataConstPtr data(&m_data);
1898 return data->typeCache.contains(url);
1899}
1900
1901bool QQmlTypeLoader::isScriptLoaded(const QUrl &url) const
1902{
1903 const QQmlTypeLoaderSharedDataConstPtr data(&m_data);
1904 return data->scriptCache.contains(url);
1905}
1906
1907static QString pathToUrl(const QString &path)
1908{
1909 const auto dir = path.left(path.lastIndexOf(u"/") + 1);
1910 if (dir.at(0) == u':')
1911 return QStringLiteral("qrc") + dir;
1912 else
1913 return QUrl::fromLocalFile(dir).toString();
1914};
1915
1916/*!
1917\internal
1918
1919Locates the qmldir files for \a import. For each one, calls
1920handleLocalQmldirForImport() on \a blob. If that returns \c true, returns
1921\c QmldirFound.
1922
1923If at least one callback invocation returned \c false and there are no qmldir
1924files left to check, returns \c QmldirRejected.
1925
1926Otherwise, if interception redirects a previously local qmldir URL to a remote
1927one, returns \c QmldirInterceptedToRemote. Otherwise, returns \c QmldirNotFound.
1928*/
1929QQmlTypeLoader::LocalQmldirResult QQmlTypeLoader::locateLocalQmldir(
1930 QQmlTypeLoader::Blob *blob, const QQmlTypeLoader::Blob::PendingImportPtr &import,
1931 QList<QQmlError> *errors)
1932{
1933 // Check cache first
1934
1935 LocalQmldirResult result = QmldirNotFound;
1936 QQmlTypeLoaderThreadData::QmldirInfo *cacheTail = nullptr;
1937
1938 QQmlTypeLoaderThreadDataPtr threadData(&m_data);
1939 QQmlTypeLoaderThreadData::QmldirInfo **cachePtr = threadData->qmldirInfo.value(import->uri);
1940 QQmlTypeLoaderThreadData::QmldirInfo *cacheHead = cachePtr ? *cachePtr : nullptr;
1941 if (cacheHead) {
1942 cacheTail = cacheHead;
1943 do {
1944 if (cacheTail->version == import->searchVersion) {
1945 if (cacheTail->qmldirFilePath.isEmpty()) {
1946 return cacheTail->qmldirPathUrl.isEmpty()
1947 ? QmldirNotFound
1948 : QmldirInterceptedToRemote;
1949 }
1950 if (blob->handleLocalQmldirForImport(
1951 import, cacheTail->qmldirFilePath, cacheTail->qmldirPathUrl, errors)) {
1952 return QmldirFound;
1953 }
1954 result = QmldirRejected;
1955 }
1956 } while (cacheTail->next && (cacheTail = cacheTail->next));
1957 }
1958
1959
1960 // Do not try to construct the cache if it already had any entries for the URI.
1961 // Otherwise we might duplicate cache entries.
1962 if (result != QmldirNotFound
1963 || QQmlMetaType::isStronglyLockedModule(import->uri, import->version)) {
1964 return result;
1965 }
1966
1967 QQmlTypeLoaderConfiguredDataConstPtr configuredData(&m_data);
1968 const bool hasInterceptors = !configuredData->urlInterceptors.isEmpty();
1969
1970 // Interceptor might redirect remote files to local ones.
1971 QStringList localImportPaths = importPathList(hasInterceptors ? LocalOrRemote : Local);
1972
1973 // Search local import paths for a matching version
1974 const QStringList qmlDirPaths = QQmlImports::completeQmldirPaths(
1975 import->uri, localImportPaths, import->searchVersion);
1976
1977 QString qmldirCleanFilePath;
1978 for (QString qmldirPath : qmlDirPaths) {
1979 if (hasInterceptors) {
1980 // TODO:
1981 // 1. This is inexact. It triggers only on the existence of interceptors, not on
1982 // actual interception. If the URL was remote to begin with but no interceptor
1983 // actually changes it, we still clear the qmldirPath and consider it
1984 // QmldirInterceptedToRemote.
1985 // 2. This misdiagnosis makes addLibraryImport do the right thing and postpone
1986 // the loading of pre-registered types for any QML engine that has interceptors
1987 // (even if they don't do anything in this case).
1988 // Fixing this would open the door to follow-up problems but wouldn't result in any
1989 // significant benefit.
1990 const QUrl intercepted = doInterceptUrl(
1991 QQmlImports::urlFromLocalFileOrQrcOrUrl(qmldirPath),
1992 QQmlAbstractUrlInterceptor::QmldirFile,
1993 configuredData->urlInterceptors);
1994 qmldirPath = QQmlFile::urlToLocalFileOrQrc(intercepted);
1995 if (result != QmldirInterceptedToRemote
1996 && qmldirPath.isEmpty()
1997 && !QQmlFile::isLocalFile(intercepted)) {
1998 result = QmldirInterceptedToRemote;
1999 }
2000 }
2001
2002 // qmldirPath can be a path or a URL at this point because we've inherited that property
2003 // from importPathList(). cleanFilePath() however, wants only paths, not URLs. It may
2004 // also be empty here if an interceptor redirected it to a non-local URL above.
2005 qmldirCleanFilePath = cleanFilePath(localPathForUrlOrPath(qmldirPath));
2006
2007 if (!qmldirCleanFilePath.isEmpty()) {
2008 QString url = pathToUrl(qmldirCleanFilePath);
2009 if (url.startsWith(QStringLiteral("file:")))
2010 sanitizeUNCPath(&qmldirCleanFilePath);
2011
2012 QQmlTypeLoaderThreadData::QmldirInfo *cache = new QQmlTypeLoaderThreadData::QmldirInfo;
2013 cache->version = import->searchVersion;
2014 cache->qmldirFilePath = qmldirCleanFilePath;
2015 cache->qmldirPathUrl = url;
2016 cache->next = nullptr;
2017 if (cacheTail)
2018 cacheTail->next = cache;
2019 else
2020 threadData->qmldirInfo.insert(import->uri, cache);
2021 cacheTail = cache;
2022
2023 if (result != QmldirFound) {
2024 result = blob->handleLocalQmldirForImport(
2025 import, qmldirCleanFilePath, url, errors)
2026 ? QmldirFound
2027 : QmldirRejected;
2028 }
2029
2030 // Do not return here. Rather, construct the complete cache for this URI.
2031 }
2032 }
2033
2034 // Nothing found? Add an empty cache entry to signal that for further requests.
2035 if (result == QmldirNotFound || result == QmldirInterceptedToRemote) {
2036 QQmlTypeLoaderThreadData::QmldirInfo *cache = new QQmlTypeLoaderThreadData::QmldirInfo;
2037 cache->version = import->searchVersion;
2038 cache->next = cacheHead;
2039 if (result == QmldirInterceptedToRemote) {
2040 // The actual value doesn't matter as long as it's not empty.
2041 // We only use it to discern QmldirInterceptedToRemote from QmldirNotFound above.
2042 cache->qmldirPathUrl = QStringLiteral("intercepted");
2043 }
2044 threadData->qmldirInfo.insert(import->uri, cache);
2045
2046 if (result == QmldirNotFound) {
2047 qCDebug(lcQmlImport)
2048 << "locateLocalQmldir:" << qPrintable(import->uri)
2049 << "module's qmldir file not found";
2050 }
2051 } else {
2052 qCDebug(lcQmlImport)
2053 << "locateLocalQmldir:" << qPrintable(import->uri) << "module's qmldir found at"
2054 << qmldirCleanFilePath;
2055 }
2056
2057 return result;
2058}
2059
2060QT_END_NAMESPACE
#define ASSERT_ENGINETHREAD()
#define ASSERT_LOADTHREAD()
static QString pathToUrl(const QString &path)
static bool isPathAbsolute(const QString &path)
static QString localPathForUrlOrPath(const QString &urlOrPath)
static void initializeConfiguredData(const QQmlTypeLoaderConfiguredDataPtr &data, QV4::ExecutionEngine *engine)
static void addDependencyImportError(const QQmlTypeLoader::Blob::PendingImportPtr &import, QList< QQmlError > *errors)
static QQmlTypeLoaderConfiguredDataConstPtr configuredData(QQmlTypeLoaderLockedData *m_data)
#define ERROR(description)
#define NOT_READABLE_ERROR
static bool isModuleUrl(const QUrl &url)
void clearBlobs(QHash< QUrl, QQmlRefPointer< Blob > > *blobs)
void doInitializeEngine(Interface *iface, QQmlTypeLoaderThread *thread, QQmlTypeLoaderLockedData *data, const char *uri)
#define NOT_FOUND_ERROR
static QStringList parseEnvPath(const QString &envImportPath)
static bool isPathQrcOrAbsolute(const QString &path)
void postProcessQmldir(QQmlTypeLoader::Blob *self, const QQmlTypeLoader::Blob::PendingImportPtr &import, const QString &qmldirFilePath, const URL &qmldirUrl)
QQmlRefPointer< Blob > handleExisting(const QQmlTypeLoaderSharedDataPtr &data, QQmlRefPointer< Blob > &&blob, QQmlTypeLoader::Mode mode)
static QString stripTrailingSlashes(const QString &path)
const QQmlPrivate::CachedQmlUnit * unit
CachedLoader(const QQmlPrivate::CachedQmlUnit *unit)
void loadThread(QQmlTypeLoader *loader, const QQmlDataBlob::Ptr &blob) const
void loadAsync(QQmlTypeLoader *loader, const QQmlDataBlob::Ptr &blob) const
void load(QQmlTypeLoader *loader, const QQmlDataBlob::Ptr &blob) const
void load(QQmlTypeLoader *loader, const QQmlDataBlob::Ptr &blob) const
StaticLoader(const QByteArray &data)
void loadThread(QQmlTypeLoader *loader, const QQmlDataBlob::Ptr &blob) const
void loadAsync(QQmlTypeLoader *loader, const QQmlDataBlob::Ptr &blob) const
const QByteArray & data