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
qfactoryloader.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// Copyright (C) 2022 Intel Corporation.
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
4
6
7#ifndef QT_NO_QOBJECT
8#include "private/qcoreapplication_p.h"
9#include "private/qduplicatetracker_p.h"
10#include "private/qloggingregistry_p.h"
11#include "private/qobject_p.h"
12#include "qcborarray.h"
13#include "qcbormap.h"
15#include "qcborvalue.h"
16#include "qdirlisting.h"
17#include "qfileinfo.h"
18#include "qjsonarray.h"
19#include "qjsondocument.h"
20#include "qjsonobject.h"
21#include "qmutex.h"
22#include "qplugin.h"
23#include "qplugin_p.h"
24#include "qpluginloader.h"
25
26#if QT_CONFIG(library)
27# include "qlibrary_p.h"
28#endif
29
30#include <qtcore_tracepoints_p.h>
31
32#include <map>
33#include <vector>
34
35QT_BEGIN_NAMESPACE
36
37using namespace Qt::StringLiterals;
38
39Q_TRACE_POINT(qtcore, QFactoryLoader_update, const QString &fileName);
40
41namespace {
42struct IterationResult
43{
44 enum Result {
45 FinishedSearch = 0,
46 ContinueSearch,
47
48 // parse errors
49 ParsingError = -1,
50 InvalidMetaDataVersion = -2,
51 InvalidTopLevelItem = -3,
52 InvalidHeaderItem = -4,
53 };
54 Result result;
55 QCborError error = { QCborError::NoError };
56
57 Q_IMPLICIT IterationResult(Result r) : result(r) {}
58 Q_IMPLICIT IterationResult(QCborError e) : result(ParsingError), error(e) {}
59};
60
61struct QFactoryLoaderIidSearch
62{
63 QLatin1StringView iid;
64 bool matchesIid = false;
65 QFactoryLoaderIidSearch(QLatin1StringView iid) : iid(iid)
66 { Q_ASSERT(!iid.isEmpty()); }
67
68 static IterationResult::Result skip(QCborStreamReader &reader)
69 {
70 // skip this, whatever it is
71 reader.next();
72 return IterationResult::ContinueSearch;
73 }
74
75 IterationResult::Result operator()(QtPluginMetaDataKeys key, QCborStreamReader &reader)
76 {
78 return skip(reader);
79 matchesIid = (reader.readAllString() == iid);
80 return IterationResult::FinishedSearch;
81 }
82 IterationResult::Result operator()(QUtf8StringView, QCborStreamReader &reader)
83 {
84 return skip(reader);
85 }
86};
87
88struct QFactoryLoaderMetaDataKeysExtractor : QFactoryLoaderIidSearch
89{
90 QCborArray keys;
91 QFactoryLoaderMetaDataKeysExtractor(QLatin1StringView iid)
92 : QFactoryLoaderIidSearch(iid)
93 {}
94
95 IterationResult::Result operator()(QtPluginMetaDataKeys key, QCborStreamReader &reader)
96 {
97 if (key == QtPluginMetaDataKeys::IID) {
98 QFactoryLoaderIidSearch::operator()(key, reader);
99 return IterationResult::ContinueSearch;
100 }
102 return skip(reader);
103
104 if (!matchesIid)
105 return IterationResult::FinishedSearch;
106 if (!reader.isMap() || !reader.isLengthKnown())
107 return IterationResult::InvalidHeaderItem;
108 if (!reader.enterContainer())
109 return IterationResult::ParsingError;
110 while (reader.isValid()) {
111 // the metadata is JSON, so keys are all strings
112 QByteArray key = reader.readAllUtf8String();
113 if (key == "Keys") {
114 if (!reader.isArray() || !reader.isLengthKnown())
115 return IterationResult::InvalidHeaderItem;
116 keys = QCborValue::fromCbor(reader).toArray();
117 break;
118 }
119 skip(reader);
120 }
121 // warning: we may not have finished iterating over the header
122 return IterationResult::FinishedSearch;
123 }
124 using QFactoryLoaderIidSearch::operator();
125};
126} // unnamed namespace
127
128template <typename F> static IterationResult iterateInPluginMetaData(QByteArrayView raw, F &&f)
129{
130 QPluginMetaData::Header header;
131 Q_ASSERT(raw.size() >= qsizetype(sizeof(header)));
132 memcpy(&header, raw.data(), sizeof(header));
133 if (Q_UNLIKELY(header.version > QPluginMetaData::CurrentMetaDataVersion))
134 return IterationResult::InvalidMetaDataVersion;
135
136 // use fromRawData to keep QCborStreamReader from copying
137 raw = raw.sliced(sizeof(header));
138 QByteArray ba = QByteArray::fromRawData(raw.data(), raw.size());
139 QCborStreamReader reader(ba);
140 if (reader.isInvalid())
141 return reader.lastError();
142 if (!reader.isMap())
143 return IterationResult::InvalidTopLevelItem;
144 if (!reader.enterContainer())
145 return reader.lastError();
146 while (reader.isValid()) {
147 IterationResult::Result r;
148 if (reader.isInteger()) {
149 // integer key, one of ours
150 qint64 value = reader.toInteger();
151 auto key = QtPluginMetaDataKeys(value);
152 if (qint64(key) != value)
153 return IterationResult::InvalidHeaderItem;
154 if (!reader.next())
155 return reader.lastError();
156 r = f(key, reader);
157 } else if (reader.isString()) {
158 QByteArray key = reader.readAllUtf8String();
159 if (key.isNull())
160 return reader.lastError();
161 r = f(QUtf8StringView(key), reader);
162 } else {
163 return IterationResult::InvalidTopLevelItem;
164 }
165
166 if (QCborError e = reader.lastError())
167 return e;
168 if (r != IterationResult::ContinueSearch)
169 return r;
170 }
171
172 if (!reader.leaveContainer())
173 return reader.lastError();
174 return IterationResult::FinishedSearch;
175}
176
177static bool isIidMatch(QByteArrayView raw, QLatin1StringView iid)
178{
179 QFactoryLoaderIidSearch search(iid);
180 iterateInPluginMetaData(raw, search);
181 return search.matchesIid;
182}
183
184bool QPluginParsedMetaData::parse(QByteArrayView raw)
185{
186 QCborMap map;
187 auto r = iterateInPluginMetaData(raw, [&](const auto &key, QCborStreamReader &reader) {
188 QCborValue item = QCborValue::fromCbor(reader);
189 if (item.isInvalid())
190 return IterationResult::ParsingError;
191 if constexpr (std::is_enum_v<std::decay_t<decltype(key)>>)
192 map[int(key)] = item;
193 else
194 map[QString::fromUtf8(key)] = item;
195 return IterationResult::ContinueSearch;
196 });
197
198 switch (r.result) {
199 case IterationResult::FinishedSearch:
200 case IterationResult::ContinueSearch:
201 break;
202
203 // parse errors
204 case IterationResult::ParsingError:
205 return setError(QFactoryLoader::tr("Metadata parsing error: %1").arg(r.error.toString()));
206 case IterationResult::InvalidMetaDataVersion:
207 return setError(QFactoryLoader::tr("Invalid metadata version"));
208 case IterationResult::InvalidTopLevelItem:
209 case IterationResult::InvalidHeaderItem:
210 return setError(QFactoryLoader::tr("Unexpected metadata contents"));
211 }
212
213 // header was validated
214 auto header = qFromUnaligned<QPluginMetaData::Header>(raw.data());
215
216 DecodedArchRequirements archReq =
217 header.version == 0 ? decodeVersion0ArchRequirements(header.plugin_arch_requirements)
218 : decodeVersion1ArchRequirements(header.plugin_arch_requirements);
219
220 // insert the keys not stored in the top-level CBOR map
222 QT_VERSION_CHECK(header.qt_major_version, header.qt_minor_version, 0);
223 map[int(QtPluginMetaDataKeys::IsDebug)] = archReq.isDebug;
224 map[int(QtPluginMetaDataKeys::Requirements)] = archReq.level;
225
226 data = std::move(map);
227 return true;
228}
229
230QJsonObject QPluginParsedMetaData::toJson() const
231{
232 // convert from the internal CBOR representation to an external JSON one
233 QJsonObject o;
234 for (auto it : data.toMap()) {
235 QString key;
236 if (it.first.isInteger()) {
237 switch (it.first.toInteger()) {
238#define CONVERT_TO_STRING(IntKey, StringKey, Description)
239 case int(IntKey): key = QStringLiteral(StringKey); break;
240 QT_PLUGIN_FOREACH_METADATA(CONVERT_TO_STRING)
241 }
242 } else {
243 key = it.first.toString();
244 }
245
246 if (!key.isEmpty())
247 o.insert(key, it.second.toJsonValue());
248 }
249 return o;
250}
251
253{
254 Q_DECLARE_PUBLIC(QFactoryLoader)
256public:
259#if QT_CONFIG(library)
261 mutable QMutex mutex;
268
270#endif
271};
272
273#if QT_CONFIG(library)
274
275Q_STATIC_LOGGING_CATEGORY_WITH_ENV_OVERRIDE(lcFactoryLoader, "QT_DEBUG_PLUGINS",
276 "qt.core.plugin.factoryloader")
277
278namespace {
279struct QFactoryLoaderGlobals
280{
281 // needs to be recursive because loading one plugin could cause another
282 // factory to be initialized
283 QRecursiveMutex mutex;
284 QList<QFactoryLoader *> loaders;
285};
286}
287
288Q_GLOBAL_STATIC(QFactoryLoaderGlobals, qt_factoryloader_global)
289
290QFactoryLoaderPrivate::~QFactoryLoaderPrivate()
291 = default;
292
293inline void QFactoryLoaderPrivate::updateSinglePath(const QString &path)
294{
295 struct LibraryReleaser {
296 void operator()(QLibraryPrivate *library)
297 { if (library) library->release(); }
298 };
299
300 // If we've already loaded, skip it...
301 if (loadedPaths.hasSeen(path))
302 return;
303
304 qCDebug(lcFactoryLoader) << "checking directory path" << path << "...";
305
306 QDirListing plugins(path,
307#if defined(Q_OS_WIN)
308 QStringList(QStringLiteral("*.dll")),
309#elif defined(Q_OS_ANDROID)
310 QStringList("libplugins_%1_*.so"_L1.arg(suffix)),
311#endif
312 QDirListing::IteratorFlag::FilesOnly | QDirListing::IteratorFlag::ResolveSymlinks);
313
314 for (const auto &dirEntry : plugins) {
315 const QString &fileName = dirEntry.fileName();
316#if defined(Q_PROCESSOR_X86)
317 if (fileName.endsWith(".avx2"_L1) || fileName.endsWith(".avx512"_L1)) {
318 // ignore AVX2-optimized file, we'll do a bait-and-switch to it later
319 continue;
320 }
321#endif
322 qCDebug(lcFactoryLoader) << "looking at" << fileName;
323
324 Q_TRACE(QFactoryLoader_update, fileName);
325
326 QLibraryPrivate::UniquePtr library;
327 library.reset(QLibraryPrivate::findOrCreate(dirEntry.canonicalFilePath()));
328 if (!library->isPlugin()) {
329 qCDebug(lcFactoryLoader) << library->errorString << Qt::endl
330 << " not a plugin";
331 continue;
332 }
333
334 QStringList keys;
335 bool metaDataOk = false;
336
337 QString iid = library->metaData.value(QtPluginMetaDataKeys::IID).toString();
338 if (iid == QLatin1StringView(this->iid.constData(), this->iid.size())) {
339 QCborMap object = library->metaData.value(QtPluginMetaDataKeys::MetaData).toMap();
340 metaDataOk = true;
341
342 const QCborArray k = object.value("Keys"_L1).toArray();
343 for (QCborValueConstRef v : k)
344 keys += cs ? v.toString() : v.toString().toLower();
345 }
346 qCDebug(lcFactoryLoader) << "Got keys from plugin meta data" << keys;
347
348 if (!metaDataOk)
349 continue;
350
351 static constexpr qint64 QtVersionNoPatch = QT_VERSION_CHECK(QT_VERSION_MAJOR, QT_VERSION_MINOR, 0);
352 int thisVersion = library->metaData.value(QtPluginMetaDataKeys::QtVersion).toInteger();
353 if (iid.startsWith(QStringLiteral("org.qt-project.Qt.QPA"))) {
354 // QPA plugins must match Qt Major.Minor
355 if (thisVersion != QtVersionNoPatch) {
356 qCDebug(lcFactoryLoader) << "Ignoring QPA plugin due to mismatching Qt versions" << QtVersionNoPatch << thisVersion;
357 continue;
358 }
359 }
360
361 int keyUsageCount = 0;
362 for (const QString &key : std::as_const(keys)) {
363 QLibraryPrivate *&keyMapEntry = keyMap[key];
364 if (QLibraryPrivate *existingLibrary = keyMapEntry) {
365 static constexpr bool QtBuildIsDebug = QT_CONFIG(debug);
366 bool existingIsDebug = existingLibrary->metaData.value(QtPluginMetaDataKeys::IsDebug).toBool();
367 bool thisIsDebug = library->metaData.value(QtPluginMetaDataKeys::IsDebug).toBool();
368 bool configsAreDifferent = thisIsDebug != existingIsDebug;
369 bool thisConfigDoesNotMatchQt = thisIsDebug != QtBuildIsDebug;
370 if (configsAreDifferent && thisConfigDoesNotMatchQt)
371 continue; // Existing library matches Qt's build config
372
373 // If the existing library was built with a future Qt version,
374 // whereas the one we're considering has a Qt version that fits
375 // better, we prioritize the better match.
376 int existingVersion = existingLibrary->metaData.value(QtPluginMetaDataKeys::QtVersion).toInteger();
377 if (existingVersion == QtVersionNoPatch)
378 continue; // Prefer exact Qt version match
379 if (existingVersion < QtVersionNoPatch && thisVersion > QtVersionNoPatch)
380 continue; // Better too old than too new
381 if (existingVersion < QtVersionNoPatch && thisVersion < existingVersion)
382 continue; // Otherwise prefer newest
383 }
384
385 keyMapEntry = library.get();
386 ++keyUsageCount;
387 }
388 if (keyUsageCount || keys.isEmpty()) {
389 library->setLoadHints(QLibrary::PreventUnloadHint); // once loaded, don't unload
390 QMutexLocker locker(&mutex);
391 libraries.push_back(std::move(library));
392 }
393 };
394}
395
396void QFactoryLoader::update()
397{
398#ifdef QT_SHARED
399 Q_D(QFactoryLoader);
400
401 const QStringList paths = QCoreApplication::libraryPaths();
402 for (const QString &pluginDir : paths) {
403#ifdef Q_OS_ANDROID
404 QString path = pluginDir;
405#else
406 QString path = pluginDir + d->suffix;
407#endif
408
409 d->updateSinglePath(path);
410 }
411 if (!d->extraSearchPath.isEmpty())
412 d->updateSinglePath(d->extraSearchPath);
413#else
414 Q_D(QFactoryLoader);
415 qCDebug(lcFactoryLoader) << "ignoring" << d->iid
416 << "since plugins are disabled in static builds";
417#endif
418}
419
420QFactoryLoader::~QFactoryLoader()
421{
422 if (!qt_factoryloader_global.isDestroyed()) {
423 QMutexLocker locker(&qt_factoryloader_global->mutex);
424 qt_factoryloader_global->loaders.removeOne(this);
425 }
426}
427
428#if defined(Q_OS_UNIX) && !defined (Q_OS_DARWIN)
429QLibraryPrivate *QFactoryLoader::library(const QString &key) const
430{
431 Q_D(const QFactoryLoader);
432 const auto it = d->keyMap.find(d->cs ? key : key.toLower());
433 if (it == d->keyMap.cend())
434 return nullptr;
435 return it->second;
436}
437#endif
438
439void QFactoryLoader::refreshAll()
440{
441 if (qt_factoryloader_global.exists()) {
442 QMutexLocker locker(&qt_factoryloader_global->mutex);
443 for (QFactoryLoader *loader : std::as_const(qt_factoryloader_global->loaders))
444 loader->update();
445 }
446}
447
448#endif // QT_CONFIG(library)
449
450QFactoryLoader::QFactoryLoader(const char *iid,
451 const QString &suffix,
452 Qt::CaseSensitivity cs)
453 : QObject(*new QFactoryLoaderPrivate)
454{
455 Q_ASSERT_X(suffix.startsWith(u'/'), "QFactoryLoader",
456 "For historical reasons, the suffix must start with '/' (and it can't be empty)");
457
458 moveToThread(QCoreApplicationPrivate::mainThread());
459 Q_D(QFactoryLoader);
460 d->iid = iid;
461#if QT_CONFIG(library)
462 d->cs = cs;
463 d->suffix = suffix;
464# ifdef Q_OS_ANDROID
465 if (!d->suffix.isEmpty() && d->suffix.at(0) == u'/')
466 d->suffix.remove(0, 1);
467# endif
468
469 QMutexLocker locker(&qt_factoryloader_global->mutex);
470 update();
471 qt_factoryloader_global->loaders.append(this);
472#else
473 Q_UNUSED(suffix);
474 Q_UNUSED(cs);
475#endif
476}
477
478void QFactoryLoader::setExtraSearchPath(const QString &path)
479{
480#if QT_CONFIG(library)
481 Q_D(QFactoryLoader);
482 if (d->extraSearchPath == path)
483 return; // nothing to do
484
485 QMutexLocker locker(&qt_factoryloader_global->mutex);
486 QString oldPath = std::exchange(d->extraSearchPath, path);
487 if (oldPath.isEmpty()) {
488 // easy case, just update this directory
489 d->updateSinglePath(d->extraSearchPath);
490 } else {
491 // must re-scan everything
492 d->loadedPaths.clear();
493 d->libraries.clear();
494 d->keyMap.clear();
495 update();
496 }
497#else
498 Q_UNUSED(path);
499#endif
500}
501
502QFactoryLoader::MetaDataList QFactoryLoader::metaData() const
503{
504 Q_D(const QFactoryLoader);
505 QList<QPluginParsedMetaData> metaData;
506#if QT_CONFIG(library)
507 QMutexLocker locker(&d->mutex);
508 for (const auto &library : d->libraries)
509 metaData.append(library->metaData);
510#endif
511
512 QLatin1StringView iid(d->iid.constData(), d->iid.size());
513 const auto staticPlugins = QPluginLoader::staticPlugins();
514 for (const QStaticPlugin &plugin : staticPlugins) {
515 QByteArrayView pluginData(static_cast<const char *>(plugin.rawMetaData), plugin.rawMetaDataSize);
516 QPluginParsedMetaData parsed(pluginData);
517 if (parsed.isError() || parsed.value(QtPluginMetaDataKeys::IID) != iid)
518 continue;
519 metaData.append(std::move(parsed));
520 }
521
522 // other portions of the code will cast to int (e.g., keyMap())
523 Q_ASSERT(metaData.size() <= std::numeric_limits<int>::max());
524 return metaData;
525}
526
527QList<QCborArray> QFactoryLoader::metaDataKeys() const
528{
529 Q_D(const QFactoryLoader);
530 QList<QCborArray> metaData;
531#if QT_CONFIG(library)
532 QMutexLocker locker(&d->mutex);
533 for (const auto &library : d->libraries) {
534 const QCborValue md = library->metaData.value(QtPluginMetaDataKeys::MetaData);
535 metaData.append(md["Keys"_L1].toArray());
536 }
537#endif
538
539 QLatin1StringView iid(d->iid.constData(), d->iid.size());
540 const auto staticPlugins = QPluginLoader::staticPlugins();
541 for (const QStaticPlugin &plugin : staticPlugins) {
542 QByteArrayView pluginData(static_cast<const char *>(plugin.rawMetaData),
543 plugin.rawMetaDataSize);
544 QFactoryLoaderMetaDataKeysExtractor extractor{ iid };
545 iterateInPluginMetaData(pluginData, extractor);
546 if (extractor.matchesIid)
547 metaData += std::move(extractor.keys);
548 }
549
550 // other portions of the code will cast to int (e.g., keyMap())
551 Q_ASSERT(metaData.size() <= std::numeric_limits<int>::max());
552 return metaData;
553}
554
555QObject *QFactoryLoader::instance(int index) const
556{
557 Q_D(const QFactoryLoader);
558 if (index < 0)
559 return nullptr;
560
561#if QT_CONFIG(library)
562 QMutexLocker lock(&d->mutex);
563 if (size_t(index) < d->libraries.size()) {
564 QLibraryPrivate *library = d->libraries[index].get();
565 if (QObject *obj = library->pluginInstance()) {
566 if (!obj->parent())
567 obj->moveToThread(QCoreApplicationPrivate::mainThread());
568 return obj;
569 }
570 return nullptr;
571 }
572 // we know d->libraries.size() <= index <= numeric_limits<decltype(index)>::max() → no overflow
573 index -= static_cast<int>(d->libraries.size());
574 lock.unlock();
575#endif
576
577 QLatin1StringView iid(d->iid.constData(), d->iid.size());
578 const QList<QStaticPlugin> staticPlugins = QPluginLoader::staticPlugins();
579 for (QStaticPlugin plugin : staticPlugins) {
580 QByteArrayView pluginData(static_cast<const char *>(plugin.rawMetaData), plugin.rawMetaDataSize);
581 if (!isIidMatch(pluginData, iid))
582 continue;
583
584 if (index == 0)
585 return plugin.instance();
586 --index;
587 }
588
589 return nullptr;
590}
591
592QMultiMap<int, QString> QFactoryLoader::keyMap() const
593{
594 QMultiMap<int, QString> result;
595 const QList<QCborArray> metaDataList = metaDataKeys();
596 for (int i = 0; i < int(metaDataList.size()); ++i) {
597 const QCborArray &keys = metaDataList[i];
598 for (QCborValueConstRef key : keys)
599 result.insert(i, key.toString());
600 }
601 return result;
602}
603
604int QFactoryLoader::indexOf(const QString &needle) const
605{
606 const QList<QCborArray> metaDataList = metaDataKeys();
607 for (int i = 0; i < int(metaDataList.size()); ++i) {
608 const QCborArray &keys = metaDataList[i];
609 for (QCborValueConstRef key : keys) {
610 if (key.toString().compare(needle, Qt::CaseInsensitive) == 0)
611 return i;
612 }
613 }
614 return -1;
615}
616
617QT_END_NAMESPACE
618
619#include "moc_qfactoryloader_p.cpp"
620
621#endif // QT_NO_QOBJECT
bool parse(QByteArrayView input)
QJsonObject toJson() const
Q_TRACE_POINT(qtcore, QFactoryLoader_update, const QString &fileName)
static bool isIidMatch(QByteArrayView raw, QLatin1StringView iid)
static IterationResult iterateInPluginMetaData(QByteArrayView raw, F &&f)
QtPluginMetaDataKeys
Definition qplugin_p.h:22
#define QT_PLUGIN_FOREACH_METADATA(F)
Definition qplugin_p.h:34