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
qqmldatablob.cpp
Go to the documentation of this file.
1// Copyright (C) 2019 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/qqmldatablob_p.h>
6#include <private/qqmlglobal_p.h>
7#include <private/qqmlprofiler_p.h>
8#include <private/qqmlsourcecoordinate_p.h>
9#include <private/qqmltypedata_p.h>
10#include <private/qqmltypeloader_p.h>
11#include <private/qqmltypeloaderthread_p.h>
12
13#include <QtQml/qqmlengine.h>
14
15#include <QtCore/qcryptographichash.h>
16
17#include <qtqml_tracepoints_p.h>
18
20
21QT_BEGIN_NAMESPACE
22
23/*!
24\class QQmlDataBlob
25\brief The QQmlDataBlob encapsulates a data request that can be issued to a QQmlTypeLoader.
26\internal
27
28QQmlDataBlob's are loaded by a QQmlTypeLoader. The user creates the QQmlDataBlob
29and then calls QQmlTypeLoader::load() or QQmlTypeLoader::loadWithStaticData() to load it.
30The QQmlTypeLoader invokes callbacks on the QQmlDataBlob as data becomes available.
31*/
32
33/*!
34\enum QQmlDataBlob::Status
35
36This enum describes the status of the data blob.
37
38\value Null The blob has not yet been loaded by a QQmlTypeLoader
39\value Loading The blob is loading network data. The QQmlDataBlob::setData() callback has
40 not yet been invoked or has not yet returned.
41\value WaitingForDependencies The blob is waiting for dependencies to be done before continuing.
42 This status only occurs after the QQmlDataBlob::setData() callback has been made,
43 and when the blob has outstanding dependencies.
44\value Complete The blob's data has been loaded and all dependencies are done.
45\value Error An error has been set on this blob.
46*/
47
48/*!
49\enum QQmlDataBlob::Type
50
51This enum describes the type of the data blob.
52
53\value QmlFile This is a QQmlTypeData
54\value JavaScriptFile This is a QQmlScriptData
55\value QmldirFile This is a QQmlQmldirData
56*/
57
58/*!
59Create a new QQmlDataBlob for \a url and of the provided \a type.
60*/
61QQmlDataBlob::QQmlDataBlob(const QUrl &url, Type type, QQmlTypeLoader *manager)
62 : m_typeLoader(manager)
63 , m_type(type)
64
65 // The URL can't be cached at this point
66 // since we're creating the blob to be inserted into the cache.
67 // We also may be holding the lock already.
68 , m_url(manager->interceptUncachedUrl(url, (QQmlAbstractUrlInterceptor::DataType)type))
69
70 , m_finalUrl(url)
71 , m_redirectCount(0)
72 , m_inCallback(false)
73 , m_isDone(false)
74{
75}
76
77/*! \internal */
78QQmlDataBlob::~QQmlDataBlob()
79{
80 Q_ASSERT(m_waitingOnMe.isEmpty());
81
82 // Deleting a QQmlDataBlob in the engine thread is conceptually dangerous
83 // because it manipulates other blobs' m_waitingFor lists. We can guarantee
84 // that the list is empty if the blob isCompleteOrError. Therefore, in such
85 // a case, it's fine to delete it from the engine thread.
86 // Furthermore, if the type loader thread is (temporarily or permanently)
87 // shut down, we cannot run into concurrency here.
88 //
89 // Unfortunately, the typeLoader pointer itself may be dangling at this point
90 // if the QQmlDataBlob is destroyed after the engine. That can happen if you
91 // hold on to a QQmlComponent for longer than the engine it belongs to. You
92 // shouldn't do it, but the mistake is very common and harmless if you don't
93 // touch the component anymore after the engine is gone. In order to actually
94 // assert on the thread safety here, we'd have to touch the typeLoader pointer.
95 // Q_ASSERT(isCompleteOrError() || isTypeLoaderThread() || !isTypeLoaderThreadRunning());
96
97 cancelAllWaitingFor();
98}
99
100/*!
101 Must be called before loading can occur.
102*/
103void QQmlDataBlob::startLoading()
104{
105 // This can be called on either thread but since both status() and setStatus() are atomic
106 // this is fine.
107 Q_ASSERT(status() == QQmlDataBlob::Null);
108 setStatus(QQmlDataBlob::Loading);
109}
110
111/*!
112Returns the type provided to the constructor.
113*/
114QQmlDataBlob::Type QQmlDataBlob::type() const
115{
116 return m_type;
117}
118
119/*!
120Returns the blob's status.
121*/
122QQmlDataBlob::Status QQmlDataBlob::status() const
123{
124 return m_data.status();
125}
126
127/*!
128Returns true if the status is Null.
129*/
130bool QQmlDataBlob::isNull() const
131{
132 return status() == Null;
133}
134
135/*!
136Returns true if the status is Loading.
137*/
138bool QQmlDataBlob::isLoading() const
139{
140 return status() == Loading;
141}
142
143/*!
144Returns true if the status is WaitingForDependencies.
145*/
146bool QQmlDataBlob::isWaiting() const
147{
148 return status() == WaitingForDependencies ||
149 status() == ResolvingDependencies;
150}
151
152/*!
153Returns true if the status is Complete.
154*/
155bool QQmlDataBlob::isComplete() const
156{
157 return status() == Complete;
158}
159
160/*!
161Returns true if the status is Error.
162*/
163bool QQmlDataBlob::isError() const
164{
165 return status() == Error;
166}
167
168/*!
169Returns true if the status is Complete or Error.
170*/
171bool QQmlDataBlob::isCompleteOrError() const
172{
173 Status s = status();
174 return s == Error || s == Complete;
175}
176
177bool QQmlDataBlob::isAsync() const
178{
179 return m_data.isAsync();
180}
181
182/*!
183Returns the data download progress from 0 to 1.
184*/
185qreal QQmlDataBlob::progress() const
186{
187 return m_data.progress();
188}
189
190/*!
191Returns the physical url of the data. Initially this is the same as
192finalUrl(), but if a URL interceptor is set, it will work on this URL
193and leave finalUrl() alone.
194
195\sa finalUrl()
196*/
197QUrl QQmlDataBlob::url() const
198{
199 return m_url;
200}
201
202QString QQmlDataBlob::urlString() const
203{
204 // TODO: This is dangerous. It can be called from either thread.
205 if (m_urlString.isEmpty())
206 m_urlString = m_url.toString();
207
208 return m_urlString;
209}
210
211/*!
212Returns the logical URL to be used for resolving further URLs referred to in
213the code.
214
215This is the blob url passed to the constructor. If a URL interceptor rewrites
216the URL, this one stays the same. If a network redirect happens while fetching
217the data, this url is updated to reflect the new location. Therefore, if both
218an interception and a redirection happen, the final url will indirectly
219incorporate the result of the interception, potentially breaking further
220lookups.
221
222\sa url()
223*/
224QUrl QQmlDataBlob::finalUrl() const
225{
226 return m_finalUrl;
227}
228
229/*!
230Returns the finalUrl() as a string.
231*/
232QString QQmlDataBlob::finalUrlString() const
233{
234 // TODO: This is dangerous. It can be called from either thread.
235
236 if (m_finalUrlString.isEmpty())
237 m_finalUrlString = m_finalUrl.toString();
238
239 return m_finalUrlString;
240}
241
242/*!
243Return the errors on this blob.
244
245May only be called from the load thread, or after the blob isCompleteOrError().
246*/
247QList<QQmlError> QQmlDataBlob::errors() const
248{
249 Q_ASSERT(isCompleteOrError()
250 || !m_typeLoader
251 || !m_typeLoader->thread()
252 || m_typeLoader->thread()->isThisThread());
253 return m_errors;
254}
255
256/*!
257Mark this blob as having \a errors.
258
259All outstanding dependencies will be cancelled. Requests to add new dependencies
260will be ignored. Entry into the Error state is irreversable.
261
262The setError() method may only be called from within a QQmlDataBlob callback.
263*/
264void QQmlDataBlob::setError(const QQmlError &errors)
265{
266 assertTypeLoaderThread();
267
268 QList<QQmlError> l;
269 l << errors;
270 setError(l);
271}
272
273/*!
274\overload
275*/
276void QQmlDataBlob::setError(const QList<QQmlError> &errors)
277{
278 assertTypeLoaderThread();
279
280 Q_ASSERT(status() != Error);
281 Q_ASSERT(m_errors.isEmpty());
282
283 // m_errors must be set before the m_data fence
284 m_errors.reserve(errors.size());
285 for (const QQmlError &error : errors) {
286 if (error.url().isEmpty()) {
287 QQmlError mutableError = error;
288 mutableError.setUrl(url());
289 m_errors.append(mutableError);
290 } else {
291 m_errors.append(error);
292 }
293 }
294
295 cancelAllWaitingFor();
296 setStatus(Error);
297
298 if (dumpErrors()) {
299 qWarning().nospace() << "Errors for " << urlString();
300 for (int ii = 0; ii < errors.size(); ++ii)
301 qWarning().nospace() << " " << qPrintable(errors.at(ii).toString());
302 }
303
304 if (!m_inCallback)
305 tryDone();
306}
307
308void QQmlDataBlob::setError(const QQmlJS::DiagnosticMessage &error)
309{
310 assertTypeLoaderThread();
311 QQmlError e;
312 e.setColumn(qmlConvertSourceCoordinate<quint32, int>(error.loc.startColumn));
313 e.setLine(qmlConvertSourceCoordinate<quint32, int>(error.loc.startLine));
314 e.setDescription(error.message);
315 e.setUrl(url());
316 setError(e);
317}
318
319void QQmlDataBlob::setError(const QString &description)
320{
321 assertTypeLoaderThread();
322 QQmlError e;
323 e.setDescription(description);
324 e.setUrl(url());
325 setError(e);
326}
327
328/*!
329Wait for \a blob to become complete or to error. If \a blob is already
330complete or in error, or this blob is already complete, this has no effect.
331
332The setError() method may only be called from within a QQmlDataBlob callback.
333*/
334void QQmlDataBlob::addDependency(const QQmlDataBlob::Ptr &blob)
335{
336 assertTypeLoaderThread();
337
338 Q_ASSERT(status() != Null);
339
340 if (!blob ||
341 blob->status() == Error || blob->status() == Complete ||
342 status() == Error || status() == Complete || m_isDone)
343 return;
344
345 for (const auto &existingDep: std::as_const(m_waitingFor)) {
346 if (existingDep.data() == blob)
347 return;
348 }
349
350 m_waitingFor.append(blob);
351 blob->m_waitingOnMe.append(this);
352
353 setStatus(WaitingForDependencies);
354
355 // Check circular dependency
356 if (m_waitingOnMe.indexOf(blob.data()) >= 0) {
357 qCWarning(lcCycle) << "Cyclic dependency detected between" << this->url().toString()
358 << "and" << blob->url().toString();
359 QQmlError error;
360 error.setUrl(url());
361 error.setDescription(QString::fromLatin1("Cyclic dependency detected between \"%1\" and \"%2\"")
362 .arg(url().toString(), blob->url().toString()));
363 setError(error);
364 }
365}
366
367/*!
368\fn void QQmlDataBlob::dataReceived(const Data &data)
369
370Invoked when data for the blob is received. Implementors should use this callback
371to determine a blob's dependencies. Within this callback you may call setError()
372or addDependency().
373*/
374
375/*!
376Invoked once data has either been received or a network error occurred, and all
377dependencies are complete.
378
379You can set an error in this method, but you cannot add new dependencies. Implementors
380should use this callback to finalize processing of data.
381
382The default implementation does nothing.
383
384XXX Rename processData() or some such to avoid confusion between done() (processing thread)
385and completed() (main thread)
386*/
387void QQmlDataBlob::done()
388{
389 assertTypeLoaderThread();
390}
391
392#if QT_CONFIG(qml_network)
393/*!
394Invoked if there is a network error while fetching this blob.
395
396The default implementation sets an appropriate QQmlError.
397*/
398void QQmlDataBlob::networkError(QNetworkReply::NetworkError networkError)
399{
400 assertTypeLoaderThread();
401
402 Q_UNUSED(networkError);
403
404 QQmlError error;
405 error.setUrl(m_url);
406
407 const char *errorString = nullptr;
408 switch (networkError) {
409 default:
410 errorString = "Network error";
411 break;
412 case QNetworkReply::ConnectionRefusedError:
413 errorString = "Connection refused";
414 break;
415 case QNetworkReply::RemoteHostClosedError:
416 errorString = "Remote host closed the connection";
417 break;
418 case QNetworkReply::HostNotFoundError:
419 errorString = "Host not found";
420 break;
421 case QNetworkReply::TimeoutError:
422 errorString = "Timeout";
423 break;
424 case QNetworkReply::ProxyConnectionRefusedError:
425 case QNetworkReply::ProxyConnectionClosedError:
426 case QNetworkReply::ProxyNotFoundError:
427 case QNetworkReply::ProxyTimeoutError:
428 case QNetworkReply::ProxyAuthenticationRequiredError:
429 case QNetworkReply::UnknownProxyError:
430 errorString = "Proxy error";
431 break;
432 case QNetworkReply::ContentAccessDenied:
433 errorString = "Access denied";
434 break;
435 case QNetworkReply::ContentNotFoundError:
436 errorString = "File not found";
437 break;
438 case QNetworkReply::AuthenticationRequiredError:
439 errorString = "Authentication required";
440 break;
441 };
442
443 error.setDescription(QLatin1String(errorString));
444
445 setError(error);
446}
447#endif // qml_network
448
449/*!
450Called if \a blob, which was previously waited for, has an error.
451
452The default implementation does nothing.
453*/
454void QQmlDataBlob::dependencyError(const QQmlDataBlob::Ptr &blob)
455{
456 assertTypeLoaderThread();
457 Q_UNUSED(blob);
458}
459
460/*!
461Called if \a blob, which was previously waited for, has completed.
462
463The default implementation does nothing.
464*/
465void QQmlDataBlob::dependencyComplete(const QQmlDataBlob::Ptr &blob)
466{
467 assertTypeLoaderThread();
468 Q_UNUSED(blob);
469}
470
471/*!
472Called when all blobs waited for have completed. This occurs regardless of
473whether they are in error, or complete state.
474
475The default implementation does nothing.
476*/
477void QQmlDataBlob::allDependenciesDone()
478{
479 assertTypeLoaderThread();
480 setStatus(QQmlDataBlob::ResolvingDependencies);
481}
482
483/*!
484Called when the download progress of this blob changes. \a progress goes
485from 0 to 1.
486
487This callback is only invoked if an asynchronous load for this blob is
488made. An asynchronous load is one in which the Asynchronous mode is
489specified explicitly, or one that is implicitly delayed due to a network
490operation.
491
492The default implementation does nothing.
493*/
494void QQmlDataBlob::downloadProgressChanged(qreal progress)
495{
496 Q_UNUSED(progress);
497 assertEngineThread();
498}
499
500/*!
501Invoked on the main thread sometime after done() was called on the load thread.
502
503You cannot modify the blobs state at all in this callback and cannot depend on the
504order or timeliness of these callbacks. Implementors should use this callback to notify
505dependencies on the main thread that the blob is done and not a lot else.
506
507This callback is only invoked if an asynchronous load for this blob is
508made. An asynchronous load is one in which the Asynchronous mode is
509specified explicitly, or one that is implicitly delayed due to a network
510operation.
511
512The default implementation does nothing.
513*/
514void QQmlDataBlob::completed()
515{
516 assertEngineThread();
517}
518
519void QQmlDataBlob::tryDone()
520{
521 assertTypeLoaderThread();
522
523 if (status() != Loading && m_waitingFor.isEmpty() && !m_isDone) {
524 m_isDone = true;
525 addref();
526
527#ifdef DATABLOB_DEBUG
528 qWarning("QQmlDataBlob::done() %s", qPrintable(urlString()));
529#endif
530 done();
531
532 if (status() != Error)
533 setStatus(Complete);
534
535 notifyAllWaitingOnMe();
536
537 // Locking is not required here, as anyone expecting callbacks must
538 // already be protected against the blob being completed (as set above);
539#ifdef DATABLOB_DEBUG
540 qWarning("QQmlDataBlob: Dispatching completed");
541#endif
542 m_typeLoader->thread()->callCompleted(this);
543
544 release();
545 }
546}
547
548void QQmlDataBlob::cancelAllWaitingFor()
549{
550 while (m_waitingFor.size()) {
551
552 // We can assert here since we are sure that m_waitingFor is either empty whenever
553 // we delete a QQmlDataBlob from outside the type loader thread, or the type loader
554 // thread has been suspended before.
555 assertTypeLoaderThreadIfRunning();
556
557 QQmlRefPointer<QQmlDataBlob> blob = m_waitingFor.takeLast();
558
559 Q_ASSERT(blob->m_waitingOnMe.contains(this));
560
561 blob->m_waitingOnMe.removeOne(this);
562 }
563}
564
565void QQmlDataBlob::notifyAllWaitingOnMe()
566{
567 assertTypeLoaderThread();
568
569 while (m_waitingOnMe.size()) {
570 QQmlDataBlob::Ptr blob = m_waitingOnMe.takeLast();
571
572 Q_ASSERT(std::any_of(blob->m_waitingFor.constBegin(), blob->m_waitingFor.constEnd(),
573 [this](const QQmlRefPointer<QQmlDataBlob> &waiting) { return waiting.data() == this; }));
574
575 blob->notifyComplete(this);
576 }
577}
578
579void QQmlDataBlob::notifyComplete(const QQmlDataBlob::Ptr &blob)
580{
581 assertTypeLoaderThread();
582
583 Q_ASSERT(blob->status() == Error || blob->status() == Complete);
584 Q_TRACE_SCOPE(QQmlCompiling, blob->url());
585 QQmlCompilingProfiler prof(typeLoader()->profiler(), blob.data());
586
587 m_inCallback = true;
588
589 QQmlRefPointer<QQmlDataBlob> blobRef;
590 for (int i = 0; i < m_waitingFor.size(); ++i) {
591 if (m_waitingFor.at(i).data() == blob) {
592 blobRef = m_waitingFor.takeAt(i);
593 break;
594 }
595 }
596 Q_ASSERT(blobRef);
597
598 if (blob->status() == Error) {
599 dependencyError(blob);
600 } else if (blob->status() == Complete) {
601 dependencyComplete(blob);
602 }
603
604 if (!isError() && m_waitingFor.isEmpty())
605 allDependenciesDone();
606
607 m_inCallback = false;
608
609 tryDone();
610}
611
612QString QQmlDataBlob::SourceCodeData::readAll(QString *error) const
613{
614 error->clear();
615 if (hasInlineSourceCode)
616 return inlineSourceCode;
617
618 QFile f(fileInfo.filePath());
619 if (!f.open(QIODevice::ReadOnly)) {
620 *error = f.errorString();
621 return QString();
622 }
623
624 const qint64 fileSize = f.size();
625
626 if (uchar *mappedData = f.map(0, fileSize)) {
627 QString source = QString::fromUtf8(reinterpret_cast<const char *>(mappedData), fileSize);
628 f.unmap(mappedData);
629 return source;
630 }
631
632 QByteArray data(fileSize, Qt::Uninitialized);
633 if (f.read(data.data(), data.size()) != data.size()) {
634 *error = f.errorString();
635 return QString();
636 }
637 return QString::fromUtf8(data);
638}
639
640QDateTime QQmlDataBlob::SourceCodeData::sourceTimeStamp() const
641{
642 if (hasInlineSourceCode)
643 return QDateTime();
644
645 // If the file is from the resource file system we're never
646 // interested in the timestamp. Either it's content-hashed anyway
647 // (if we're checking against a .qmlc file), or we use the
648 // application timestamp because we don't trust qrc timestamps.
649 // So don't query the file system here.
650 if (QQmlTypeLoader::isResource(fileInfo.path()))
651 return QDateTime();
652
653 return fileInfo.lastModified();
654}
655
656QByteArray QQmlDataBlob::SourceCodeData::checksum() const
657{
658 QCryptographicHash hash(QCryptographicHash::Md5);
659 if (hasInlineSourceCode) {
660 hash.addData(inlineSourceCode.toUtf8());
661 return hash.result();
662 }
663
664 QFile f(fileInfo.filePath());
665 if (!f.open(QIODevice::ReadOnly))
666 return QByteArray();
667 if (!hash.addData(&f))
668 return QByteArray();
669 return hash.result();
670}
671
672bool QQmlDataBlob::setStatus(Status status)
673{
674 switch (status) {
675 case Loading:
676 break;
677 case WaitingForDependencies:
678 Q_ASSERT(!m_waitingFor.isEmpty());
679 break;
680 case Null:
681 case ResolvingDependencies:
682 case Complete:
683 case Error:
684 Q_ASSERT(m_waitingFor.isEmpty());
685 break;
686 }
687
688 return m_data.setStatus(status);
689}
690
691QT_END_NAMESPACE
DEFINE_BOOL_CONFIG_OPTION(forceDiskCache, QML_FORCE_DISK_CACHE)