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
qpluginloader.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// Copyright (C) 2018 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// Qt-Security score:critical reason:execute-external-code
5
7
9#include "qdebug.h"
10#include "qdir.h"
12#include "qfileinfo.h"
13#include "qjsondocument.h"
14
15#if QT_CONFIG(library)
16# include "qlibrary_p.h"
17#endif
18
20
21using namespace Qt::StringLiterals;
22
23#if QT_CONFIG(library)
24
25/*!
26 \class QPluginLoader
27 \inmodule QtCore
28 \reentrant
29 \brief The QPluginLoader class loads a plugin at run-time.
30
31
32 \ingroup plugins
33
34 QPluginLoader provides access to a \l{How to Create Qt
35 Plugins}{Qt plugin}. A Qt plugin is stored in a shared library (a
36 DLL) and offers these benefits over shared libraries accessed
37 using QLibrary:
38
39 \list
40 \li QPluginLoader checks that a plugin is linked against the same
41 version of Qt as the application.
42 \li QPluginLoader provides direct access to a root component object
43 (instance()), instead of forcing you to resolve a C function manually.
44 \endlist
45
46 An instance of a QPluginLoader object operates on a single shared
47 library file, which we call a plugin. It provides access to the
48 functionality in the plugin in a platform-independent way. To
49 specify which plugin to load, either pass a file name in
50 the constructor or set it with setFileName().
51
52 The most important functions are load() to dynamically load the
53 plugin file, isLoaded() to check whether loading was successful,
54 and instance() to access the root component in the plugin. The
55 instance() function implicitly tries to load the plugin if it has
56 not been loaded yet. Multiple instances of QPluginLoader can be
57 used to access the same physical plugin.
58
59 Once loaded, plugins remain in memory until all instances of
60 QPluginLoader has been unloaded, or until the application
61 terminates. You can attempt to unload a plugin using unload(),
62 but if other instances of QPluginLoader are using the same
63 library, the call will fail, and unloading will only happen when
64 every instance has called unload(). Right before the unloading
65 happens, the root component will also be deleted.
66
67 See \l{How to Create Qt Plugins} for more information about
68 how to make your application extensible through plugins.
69
70 Note that the QPluginLoader cannot be used if your application is
71 statically linked against Qt. In this case, you will also have to
72 link to plugins statically. You can use QLibrary if you need to
73 load dynamic libraries in a statically linked application.
74
75 \section1 Security considerations
76
77 \section2 Plugin lookup
78
79 Qt treats plugins as trusted content: loading a plugin executes its
80 code with the privileges of the application. It is therefore the
81 responsibility of the application developer, and of whoever deploys
82 the application, to ensure that no malicious plugin can be placed in
83 a location from which it may be loaded.
84
85 If the file name passed to QPluginLoader is not an absolute path, the
86 plugin is searched for in the directories returned by
87 \l QCoreApplication::libraryPaths(). By default, this list contains
88 the entries of the \c QT_PLUGIN_PATH environment variable, the plugin
89 installation directory, which can be changed in \l{Using qt.conf}{qt.conf},
90 and the directory of the application executable. The application can modify
91 the list with \l QCoreApplication::setLibraryPaths() and
92 \l QCoreApplication::addLibraryPath().
93
94 Libraries that a plugin depends on are resolved by the operating
95 system's dynamic loader, and are therefore subject to the platform's
96 library search rules, for example the \c PATH environment variable on
97 Windows, or \c LD_LIBRARY_PATH on Linux.
98
99 \section2 Plugin validation
100
101 On most platforms, Qt parses the plugin file before loading it, to
102 verify that it contains Qt plugin metadata and that it was built
103 against a compatible version of Qt. This is a compatibility check,
104 not a security measure: the metadata is provided by the plugin
105 itself, and Qt does not verify the plugin's origin or integrity.
106
107 Validation and loading do not happen atomically. The plugin is
108 validated when its file name is set, but it is only loaded when
109 load() or instance() is called, which may happen much later. If the
110 file, or a directory or symbolic link in its path, is replaced in the
111 meantime, whether intentionally or unintentionally (for example, by
112 an automatic update while the application is running), a different
113 binary than the one that was validated may be loaded.
114
115 Make sure that plugin files, and the directories that contain them,
116 can only be modified by trusted accounts, and that they are not
117 changed while the application is running.
118
119 \sa QLibrary
120*/
121
122static constexpr QLibrary::LoadHints defaultLoadHints = QLibrary::PreventUnloadHint;
123
124/*!
125 Constructs a plugin loader with the given \a parent.
126*/
127QPluginLoader::QPluginLoader(QObject *parent)
128 : QObject(parent), d(nullptr), did_load(false)
129{
130}
131
132/*!
133 Constructs a plugin loader with the given \a parent that will
134 load the plugin specified by \a fileName.
135
136 To be loadable, the file's suffix must be a valid suffix for a
137 loadable library in accordance with the platform, e.g. \c .so on
138 Unix, - \c .dylib on \macos and iOS, and \c .dll on Windows. The suffix
139 can be verified with QLibrary::isLibrary().
140
141 \sa setFileName()
142*/
143QPluginLoader::QPluginLoader(const QString &fileName, QObject *parent)
144 : QObject(parent), d(nullptr), did_load(false)
145{
146 setFileName(fileName);
147 setLoadHints(defaultLoadHints);
148}
149
150/*!
151 Destroys the QPluginLoader object.
152
153 Unless unload() was called explicitly, the plugin stays in memory
154 until the application terminates.
155
156 \sa isLoaded(), unload()
157*/
158QPluginLoader::~QPluginLoader()
159{
160 if (d)
161 d->release();
162}
163
164/*!
165 Returns the root component object of the plugin. The plugin is
166 loaded if necessary. The function returns \nullptr if the plugin could
167 not be loaded or if the root component object could not be
168 instantiated.
169
170 If the root component object was destroyed, calling this function
171 creates a new instance.
172
173 The root component, returned by this function, is not deleted when
174 the QPluginLoader is destroyed. If you want to ensure that the root
175 component is deleted, you should call unload() as soon you don't
176 need to access the core component anymore. When the library is
177 finally unloaded, the root component will automatically be deleted.
178
179 The component object is a QObject. Use qobject_cast() to access
180 interfaces you are interested in.
181
182 \sa load()
183*/
184QObject *QPluginLoader::instance()
185{
186 if (!isLoaded() && !load())
187 return nullptr;
188 return d->pluginInstance();
189}
190
191/*!
192 Returns the meta data for this plugin. The meta data is data specified
193 in a json format using the Q_PLUGIN_METADATA() macro when compiling
194 the plugin.
195
196 The meta data can be queried in a fast and inexpensive way without
197 actually loading the plugin. This makes it possible to e.g. store
198 capabilities of the plugin in there, and make the decision whether to
199 load the plugin dependent on this meta data.
200 */
201QJsonObject QPluginLoader::metaData() const
202{
203 if (!d)
204 return QJsonObject();
205 return d->metaData.toJson();
206}
207
208/*!
209 Loads the plugin and returns \c true if the plugin was loaded
210 successfully; otherwise returns \c false. Since instance() always
211 calls this function before resolving any symbols it is not
212 necessary to call it explicitly. In some situations you might want
213 the plugin loaded in advance, in which case you would use this
214 function.
215
216 \sa unload()
217*/
218bool QPluginLoader::load()
219{
220 if (!d || d->fileName.isEmpty())
221 return false;
222 if (did_load)
223 return d->pHnd && d->instanceFactory.loadAcquire();
224#if !defined(Q_OS_WASM)
225 // On wasm, plugins are fetched over HTTP by emscripten_dlopen() and may
226 // not exist on the file system. Skip the isPlugin() check which probes the
227 // filesystem; the metadata is read from the loaded module instead.
228 if (!d->isPlugin())
229 return false;
230#endif
231 did_load = true;
232 return d->loadPlugin();
233}
234
235/*!
236 Unloads the plugin and returns \c true if the plugin could be
237 unloaded; otherwise returns \c false.
238
239 This happens automatically on application termination, so you
240 shouldn't normally need to call this function.
241
242 If other instances of QPluginLoader are using the same plugin, the
243 call will fail, and unloading will only happen when every instance
244 has called unload().
245
246 Don't try to delete the root component. Instead rely on
247 that unload() will automatically delete it when needed.
248
249 \sa instance(), load()
250*/
251bool QPluginLoader::unload()
252{
253 if (did_load) {
254 did_load = false;
255 return d->unload();
256 }
257 if (d) // Ouch
258 d->errorString = tr("The plugin was not loaded.");
259 return false;
260}
261
262/*!
263 Returns \c true if the plugin is loaded; otherwise returns \c false.
264
265 \sa load()
266 */
267bool QPluginLoader::isLoaded() const
268{
269 return d && d->pHnd && d->instanceFactory.loadRelaxed();
270}
271
272#if defined(QT_SHARED)
273# if defined(Q_OS_WASM)
274// On wasm, plugins are fetched over HTTP by emscripten_dlopen() and may not exist
275// on the file system, so there is nothing to locate: pass the file name through
276// and let the loader resolve it.
277static QString locatePlugin(const QString &fileName)
278{
279 return fileName;
280}
281# else
282static QString locatePlugin(const QString& fileName)
283{
284 const bool isAbsolute = QDir::isAbsolutePath(fileName);
285 if (isAbsolute) {
286 QFileInfo fi(fileName);
287 if (fi.isFile()) {
288 return fi.canonicalFilePath();
289 }
290 }
291 std::array<QStringView, 2> prefixes = { QStringView(), QLibraryPrivate::prefix_sys() };
292 QStringList suffixes = QLibraryPrivate::suffixes_sys(QString());
293 suffixes.prepend(QString());
294
295 // Split up "subdir/filename"
296 const qsizetype slash = fileName.lastIndexOf(u'/');
297 const auto baseName = QStringView{fileName}.mid(slash + 1);
298 const auto basePath = isAbsolute ? QStringView() : QStringView{fileName}.left(slash + 1); // keep the '/'
299
300 QStringList paths;
301 if (isAbsolute) {
302 paths.append(fileName.left(slash)); // don't include the '/'
303 } else {
304 paths = QCoreApplication::libraryPaths();
305 }
306
307 for (const QString &path : std::as_const(paths)) {
308 for (QStringView prefix : prefixes) {
309 for (const QString &suffix : std::as_const(suffixes)) {
310#ifdef Q_OS_ANDROID
311 {
312 QString pluginPath = basePath + prefix + baseName + suffix;
313 const QString fn = path + "/lib"_L1 + pluginPath.replace(u'/', u'_');
314 qCDebug(qt_lcDebugPlugins) << "Trying..." << fn;
315 if (QFileInfo(fn).isFile())
316 return fn;
317 }
318#endif
319 const QString fn = path + u'/' + basePath + prefix + baseName + suffix;
320 qCDebug(qt_lcDebugPlugins) << "Trying..." << fn;
321 if (QFileInfo(fn).isFile())
322 return fn;
323 }
324 }
325 }
326 qCDebug(qt_lcDebugPlugins) << fileName << "not found";
327 return QString();
328}
329# endif // Q_OS_WASM
330#endif // QT_SHARED
331
332/*!
333 \property QPluginLoader::fileName
334 \brief the file name of the plugin
335
336 We recommend omitting the file's suffix in the file name, since
337 QPluginLoader will automatically look for the file with the appropriate
338 suffix (see QLibrary::isLibrary()).
339
340 When loading the plugin, QPluginLoader searches
341 in all plugin locations specified by QCoreApplication::libraryPaths(),
342 unless the file name has an absolute path. After loading the plugin
343 successfully, fileName() returns the fully-qualified file name of
344 the plugin, including the full path to the plugin if one was given
345 in the constructor or passed to setFileName().
346
347 If the file name does not exist, it will not be set. This property
348 will then contain an empty string.
349
350 By default, this property contains an empty string.
351
352 \sa load()
353*/
354void QPluginLoader::setFileName(const QString &fileName)
355{
356#if defined(QT_SHARED)
357 QLibrary::LoadHints lh = defaultLoadHints;
358 if (d) {
359 lh = d->loadHints();
360 d->release();
361 d = nullptr;
362 did_load = false;
363 }
364
365 const QString fn = locatePlugin(fileName);
366
367 d = QLibraryPrivate::findOrCreate(fn, QString(), lh);
368 if (!fn.isEmpty())
369 d->updatePluginState();
370
371#else
372 qCWarning(qt_lcDebugPlugins, "Cannot load '%ls' into a statically linked Qt library.",
373 qUtf16Printable(fileName));
374#endif
375}
376
377QString QPluginLoader::fileName() const
378{
379 if (d)
380 return d->fileName;
381 return QString();
382}
383
384/*!
385 \since 4.2
386
387 Returns a text string with the description of the last error that occurred.
388*/
389QString QPluginLoader::errorString() const
390{
391 return (!d || d->errorString.isEmpty()) ? tr("Unknown error") : d->errorString;
392}
393
394/*! \since 4.4
395
396 \property QPluginLoader::loadHints
397 \brief Give the load() function some hints on how it should behave.
398
399 You can give hints on how the symbols in the plugin are
400 resolved. By default since Qt 5.7, QLibrary::PreventUnloadHint is set.
401
402 See the documentation of QLibrary::loadHints for a complete
403 description of how this property works.
404
405 \sa QLibrary::loadHints
406*/
407
408void QPluginLoader::setLoadHints(QLibrary::LoadHints loadHints)
409{
410 if (!d) {
411 d = QLibraryPrivate::findOrCreate({}, {}, loadHints); // ugly, but we need a d-ptr
412 d->errorString.clear();
413 } else {
414 d->setLoadHints(loadHints);
415 }
416}
417
418QLibrary::LoadHints QPluginLoader::loadHints() const
419{
420 // Not having a d-pointer means that the user hasn't called
421 // setLoadHints() / setFileName() yet. In setFileName() we will
422 // then force defaultLoadHints on loading, so we must return them
423 // from here as well.
424
425 return d ? d->loadHints() : defaultLoadHints;
426}
427
428#endif // QT_CONFIG(library)
429
432
433/*!
434 \relates QPluginLoader
435 \since 5.0
436
437 Registers the \a plugin specified with the plugin loader, and is used
438 by Q_IMPORT_PLUGIN().
439*/
440void Q_CORE_EXPORT qRegisterStaticPluginFunction(QStaticPlugin plugin)
441{
442 // using operator* because we shouldn't be registering plugins while
443 // unloading the application!
444 StaticPluginList &plugins = *staticPluginList;
445
446 // insert the plugin in the list, sorted by address, so we can detect
447 // duplicate registrations
448 auto comparator = [=](const QStaticPlugin &p1, const QStaticPlugin &p2) {
449 using Less = std::less<decltype(plugin.instance)>;
450 return Less{}(p1.instance, p2.instance);
451 };
452 auto pos = std::lower_bound(plugins.constBegin(), plugins.constEnd(), plugin, comparator);
453 if (pos == plugins.constEnd() || pos->instance != plugin.instance)
454 plugins.insert(pos, plugin);
455}
456
457/*!
458 Returns a list of static plugin instances (root components) held
459 by the plugin loader.
460 \sa staticPlugins()
461*/
462QObjectList QPluginLoader::staticInstances()
463{
464 QObjectList instances;
465 if (staticPluginList.exists()) {
466 const StaticPluginList &plugins = *staticPluginList;
467 instances.reserve(plugins.size());
468 for (QStaticPlugin plugin : plugins)
469 instances += plugin.instance();
470 }
471 return instances;
472}
473
474/*!
475 Returns a list of QStaticPlugins held by the plugin
476 loader. The function is similar to \l staticInstances()
477 with the addition that a QStaticPlugin also contains
478 meta data information.
479 \sa staticInstances()
480*/
481QList<QStaticPlugin> QPluginLoader::staticPlugins()
482{
483 StaticPluginList *plugins = staticPluginList();
484 if (plugins)
485 return *plugins;
486 return QList<QStaticPlugin>();
487}
488
489/*!
490 \class QStaticPlugin
491 \inmodule QtCore
492 \since 5.2
493
494 \brief QStaticPlugin is a struct containing a reference to a
495 static plugin instance together with its meta data.
496
497 \sa QPluginLoader, {How to Create Qt Plugins}
498*/
499
500/*!
501 \fn QStaticPlugin::QStaticPlugin(QtPluginInstanceFunction i, QtPluginMetaDataFunction m)
502 \internal
503*/
504
505/*!
506 \variable QStaticPlugin::instance
507
508 Holds the plugin instance.
509
510 \sa QPluginLoader::staticInstances()
511*/
512
513/*!
514 Returns a the meta data for the plugin as a QJsonObject.
515
516 \sa Q_PLUGIN_METADATA()
517*/
518QJsonObject QStaticPlugin::metaData() const
519{
520 QByteArrayView data(static_cast<const char *>(rawMetaData), rawMetaDataSize);
521 QPluginParsedMetaData parsed(data);
522 Q_ASSERT(!parsed.isError());
523 return parsed.toJson();
524}
525
526QT_END_NAMESPACE
527
528#include "moc_qpluginloader.cpp"
Combined button and popup list for selecting options.
Q_GLOBAL_STATIC(QReadWriteLock, g_updateMutex)
QList< QStaticPlugin > StaticPluginList