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
qlibrary.cpp
Go to the documentation of this file.
1// Copyright (C) 2020 The Qt Company Ltd.
2// Copyright (C) 2021 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
6#include "qlibrary.h"
7#include "qlibrary_p.h"
8
9#include <q20algorithm.h>
10#include <qbytearraymatcher.h>
11#include <qdebug.h>
12#include <qendian.h>
13#include <qfile.h>
14#include <qfileinfo.h>
15#include <qjsondocument.h>
16#include <qmutex.h>
17#include <qoperatingsystemversion.h>
18#include <qstringlist.h>
19
20#ifdef Q_OS_DARWIN
21# include <private/qcore_mac_p.h>
22#endif
23#include <private/qcoreapplication_p.h>
24#include <private/qloggingregistry_p.h>
25#include <private/qsystemerror_p.h>
26
28#include "qelfparser_p.h"
30#include "qmachparser_p.h"
31
32#include <qtcore_tracepoints_p.h>
33
34#include <QtCore/q20map.h>
35
36QT_BEGIN_NAMESPACE
37
38using namespace Qt::StringLiterals;
39
42
43// On Unix systema and on Windows with MinGW, we can mix and match debug and
44// release plugins without problems. (unless compiled in debug-and-release mode
45// - why?)
46static constexpr bool PluginMustMatchQtDebug =
48#if defined(Q_CC_MINGW)
49 && QT_CONFIG(debug_and_release)
50#endif
51 ;
52
53#ifdef QT_NO_DEBUG
54static constexpr bool QtBuildIsDebug = false;
55#else
56static constexpr bool QtBuildIsDebug = true;
57#endif
58
59Q_LOGGING_CATEGORY_WITH_ENV_OVERRIDE(qt_lcDebugPlugins, "QT_DEBUG_PLUGINS", "qt.core.plugin.loader")
60Q_STATIC_LOGGING_CATEGORY_WITH_ENV_OVERRIDE(lcDebugLibrary, "QT_DEBUG_PLUGINS", "qt.core.library")
61
62/*!
63 \class QLibrary
64 \inmodule QtCore
65 \reentrant
66 \brief The QLibrary class loads shared libraries at runtime.
67
68
69 \ingroup plugins
70
71 An instance of a QLibrary object operates on a single shared
72 object file (which we call a "library", but is also known as a
73 "DLL"). A QLibrary provides access to the functionality in the
74 library in a platform independent way. You can either pass a file
75 name in the constructor, or set it explicitly with setFileName().
76 When loading the library, QLibrary searches in all the
77 system-specific library locations (e.g. \c LD_LIBRARY_PATH on
78 Unix), unless the file name has an absolute path.
79
80 If the file name is an absolute path then an attempt is made to
81 load this path first. If the file cannot be found, QLibrary tries
82 the name with different platform-specific file prefixes, like
83 "lib" on Unix and Mac, and suffixes, like ".so" on Unix, ".dylib"
84 on the Mac, or ".dll" on Windows.
85
86 If the file path is not absolute then QLibrary modifies the search
87 order to try the system-specific prefixes and suffixes first,
88 followed by the file path specified.
89
90 This makes it possible to specify shared libraries that are only
91 identified by their basename (i.e. without their suffix), so the
92 same code will work on different operating systems yet still
93 minimise the number of attempts to find the library.
94
95 The most important functions are load() to dynamically load the
96 library file, isLoaded() to check whether loading was successful,
97 and resolve() to resolve a symbol in the library. The resolve()
98 function implicitly tries to load the library if it has not been
99 loaded yet. Multiple instances of QLibrary can be used to access
100 the same physical library. Once loaded, libraries remain in memory
101 until the application terminates. You can attempt to unload a
102 library using unload(), but if other instances of QLibrary are
103 using the same library, the call will fail, and unloading will
104 only happen when every instance has called unload().
105
106 A typical use of QLibrary is to resolve an exported symbol in a
107 library, and to call the C function that this symbol represents.
108 This is called "explicit linking" in contrast to "implicit
109 linking", which is done by the link step in the build process when
110 linking an executable against a library.
111
112 The following code snippet loads a library, resolves the symbol
113 "mysymbol", and calls the function if everything succeeded. If
114 something goes wrong, e.g. the library file does not exist or the
115 symbol is not defined, the function pointer will be \nullptr and
116 won't be called.
117
118 \snippet code/src_corelib_plugin_qlibrary.cpp 0
119
120 The symbol must be exported as a C function from the library for
121 resolve() to work. This means that the function must be wrapped in
122 an \c{extern "C"} block if the library is compiled with a C++
123 compiler. On Windows, this also requires the use of a \c dllexport
124 macro; see resolve() for the details of how this is done. For
125 convenience, there is a static resolve() function which you can
126 use if you just want to call a function in a library without
127 explicitly loading the library first:
128
129 \snippet code/src_corelib_plugin_qlibrary.cpp 1
130
131 \section1 Security considerations
132
133 Qt treats libraries loaded with QLibrary as trusted content: loading a
134 library executes its code with the privileges of the application. It is
135 therefore the responsibility of the application developer, and of whoever
136 deploys the application, to ensure that no malicious library can be placed
137 in a location from which it may be loaded.
138
139 Whenever possible, specify the absolute path to the library. This avoids
140 searching the system-specific library locations, so that the library can
141 only be loaded from the intended location. Note that QLibrary may still try
142 the platform-specific prefixes and suffixes described above in that
143 location.
144
145 Libraries that the loaded library depends on are resolved by the operating
146 system's dynamic loader, and are subject to the platform's library search
147 rules even if the library itself is loaded using an absolute path.
148
149 Make sure that library files, and the directories that contain them, can
150 only be modified by trusted accounts, and that they are not changed while
151 the application is running.
152
153 \sa QPluginLoader
154*/
155
156/*!
157 \enum QLibrary::LoadHint
158
159 This enum describes the possible hints that can be used to change the way
160 libraries are handled when they are loaded. These values indicate how
161 symbols are resolved when libraries are loaded, and are specified using
162 the setLoadHints() function.
163
164 \value ResolveAllSymbolsHint
165 Causes all symbols in a library to be resolved when it is loaded, not
166 simply when resolve() is called.
167 \value ExportExternalSymbolsHint
168 Exports unresolved and external symbols in the library so that they can be
169 resolved in other dynamically-loaded libraries loaded later.
170 \value LoadArchiveMemberHint
171 Allows the file name of the library to specify a particular object file
172 within an archive file.
173 If this hint is given, the filename of the library consists of
174 a path, which is a reference to an archive file, followed by
175 a reference to the archive member.
176 \value PreventUnloadHint
177 Prevents the library from being unloaded from the address space if close()
178 is called. The library's static variables are not reinitialized if open()
179 is called at a later time.
180 \value DeepBindHint
181 Instructs the linker to prefer definitions in the loaded library
182 over exported definitions in the loading application when resolving
183 external symbols in the loaded library. This option is only supported
184 on Linux.
185
186 \sa loadHints
187*/
188
189static QLibraryScanResult qt_find_pattern(const char *s, qsizetype s_len, QString *errMsg)
190{
191 /*
192 We used to search from the end of the file so we'd skip the code and find
193 the read-only data that usually follows. Unfortunately, in debug builds,
194 the debug sections come after and are usually much bigger than everything
195 else, making this process slower than necessary with debug plugins.
196
197 More importantly, the pattern string may exist in the debug information due
198 to it being used in the plugin in the first place.
199 */
200#if defined(Q_OF_ELF)
201 return QElfParser::parse({s, s_len}, errMsg);
202#elif defined(Q_OF_MACH_O)
203 return QMachOParser::parse(s, s_len, errMsg);
204#elif defined(Q_OS_WIN) || defined(Q_OS_CYGWIN)
205 return QCoffPeParser::parse({s, s_len}, errMsg);
206#else
207# warning "Qt does not know how to efficiently parse your platform's binary format; using slow fall-back."
208#endif
209 static constexpr auto matcher = [] {
210 // QPluginMetaData::MagicString is not NUL-terminated, but
211 // qMakeStaticByteArrayMatcher requires its argument to be, so
212 // duplicate here, but statically check we didn't mess up:
213 constexpr auto &pattern = "QTMETADATA !";
214 constexpr auto magic = std::string_view(QPluginMetaData::MagicString,
215 sizeof(QPluginMetaData::MagicString));
216 static_assert(pattern == magic);
217 return qMakeStaticByteArrayMatcher(pattern);
218 }();
219 qsizetype i = matcher.indexIn({s, s_len});
220 if (i < 0) {
221 *errMsg = QLibrary::tr("'%1' is not a Qt plugin").arg(*errMsg);
222 return QLibraryScanResult{};
223 }
224 i += sizeof(QPluginMetaData::MagicString);
225 return { i, s_len - i };
226}
227
228/*
229 This opens the specified library, mmaps it into memory, and searches
230 for the QT_PLUGIN_VERIFICATION_DATA. The advantage of this approach is that
231 we can get the verification data without have to actually load the library.
232 This lets us detect mismatches more safely.
233
234 Returns \c false if version information is not present, or if the
235 information could not be read.
236 Returns true if version information is present and successfully read.
237*/
238static QLibraryScanResult findPatternUnloaded(const QString &library, QLibraryPrivate *lib)
239{
240 QFile file(library);
241 if (!file.open(QIODevice::ReadOnly)) {
242 if (lib)
243 lib->errorString = file.errorString();
244 qCWarning(qt_lcDebugPlugins, "%ls: cannot open: %ls", qUtf16Printable(library),
245 qUtf16Printable(file.errorString()));
246 return {};
247 }
248
249 // Files can be bigger than the virtual memory size on 32-bit systems, so
250 // we limit to 512 MB there. For 64-bit, we allow up to 2^40 bytes.
251 constexpr qint64 MaxMemoryMapSize =
252 Q_INT64_C(1) << (sizeof(qsizetype) > 4 ? 40 : 29);
253
254 qsizetype fdlen = qMin(file.size(), MaxMemoryMapSize);
255 const char *filedata = reinterpret_cast<char *>(file.map(0, fdlen));
256
257#ifdef Q_OS_UNIX
258 if (filedata == nullptr) {
259 // If we can't mmap(), then the dynamic loader won't be able to either.
260 // This can't be used as a plugin.
261 qCWarning(qt_lcDebugPlugins, "%ls: failed to map to memory: %ls",
262 qUtf16Printable(library), qUtf16Printable(file.errorString()));
263 return {};
264 }
265#else
266 QByteArray data;
267 if (filedata == nullptr) {
268 // It's unknown at this point whether Windows supports LoadLibrary() on
269 // files that fail to CreateFileMapping / MapViewOfFile, so we err on
270 // the side of doing a regular read into memory (up to 64 MB).
271 data = file.read(qMin(file.size(), Q_INT64_C(64) * 1024 * 1024));
272 filedata = data.constData();
273 fdlen = data.size();
274 }
275#endif
276
277 QString errMsg = library;
278 QLibraryScanResult r = qt_find_pattern(filedata, fdlen, &errMsg);
279 if (r.length) {
280#if defined(Q_OF_MACH_O)
281 if (r.isEncrypted)
282 return r;
283#endif
284 if (!lib->metaData.parse(QByteArrayView(filedata + r.pos, r.length))) {
285 errMsg = lib->metaData.errorString();
286 qCDebug(qt_lcDebugPlugins, "Found invalid metadata in lib %ls: %ls",
287 qUtf16Printable(library), qUtf16Printable(errMsg));
288 } else {
289 qCDebug(qt_lcDebugPlugins, "Found metadata in lib %ls, metadata=\n%s\n",
290 qUtf16Printable(library),
291 QJsonDocument(lib->metaData.toJson()).toJson().constData());
292 return r;
293 }
294 } else {
295 qCDebug(qt_lcDebugPlugins, "Failed to find metadata in lib %ls: %ls",
296 qUtf16Printable(library), qUtf16Printable(errMsg));
297 }
298
299 lib->errorString = QLibrary::tr("Failed to extract plugin meta data from '%1': %2")
300 .arg(library, errMsg);
301 return {};
302}
303
304static void installCoverageTool(QLibraryPrivate *libPrivate)
305{
306#ifdef __COVERAGESCANNER__
307 /*
308 __COVERAGESCANNER__ is defined when Qt has been instrumented for code
309 coverage by TestCocoon. CoverageScanner is the name of the tool that
310 generates the code instrumentation.
311 This code is required here when code coverage analysis with TestCocoon
312 is enabled in order to allow the loading application to register the plugin
313 and then store its execution report. The execution report gathers information
314 about each part of the plugin's code that has been used when
315 the plugin was loaded by the launching application.
316 The execution report for the plugin will go to the same execution report
317 as the one defined for the application loading it.
318 */
319
320 int ret = __coveragescanner_register_library(libPrivate->fileName.toLocal8Bit());
321
322 if (ret >= 0) {
323 qDebug("coverage data for %ls registered",
324 qUtf16Printable(libPrivate->fileName));
325 } else {
326 qWarning("could not register %ls: error %d; coverage data may be incomplete",
327 qUtf16Printable(libPrivate->fileName),
328 ret);
329 }
330 }
331#else
332 Q_UNUSED(libPrivate);
333#endif
334}
335
337{
338public:
339 inline ~QLibraryStore();
340 static inline QLibraryPrivate *findOrCreate(const QString &fileName, const QString &version, QLibrary::LoadHints loadHints);
341 static inline void releaseLibrary(QLibraryPrivate *lib);
342
343 static inline void cleanup();
344
345private:
346 static inline QLibraryStore *instance();
347
348 // all members and instance() are protected by qt_library_mutex
349 typedef std::map<QString, QLibraryPrivate *> LibraryMap;
350 LibraryMap libraryMap;
351};
352
353Q_CONSTINIT static QBasicMutex qt_library_mutex;
354Q_CONSTINIT static QLibraryStore *qt_library_data = nullptr;
356
358{
359 qt_library_data = nullptr;
360}
361
362inline void QLibraryStore::cleanup()
363{
364 QLibraryStore *data = qt_library_data;
365 if (!data)
366 return;
367
368 // find any libraries that are still loaded but have a no one attached to them
369 for (auto &[_, lib] : data->libraryMap) {
370 if (lib->libraryRefCount.loadRelaxed() == 1) {
371 if (lib->libraryUnloadCount.loadRelaxed() > 0) {
372 Q_ASSERT(lib->pHnd.loadRelaxed());
373 lib->libraryUnloadCount.storeRelaxed(1);
374#if defined(Q_OS_DARWIN)
375 // We cannot fully unload libraries, as we don't know if there are
376 // lingering references (in system threads e.g.) to Objective-C classes
377 // defined in the library.
378 lib->unload(QLibraryPrivate::NoUnloadSys);
379#else
380 lib->unload();
381#endif
382 }
383 delete std::exchange(lib, nullptr);
384 }
385 }
386
387 // dump all objects that remain
388 if (lcDebugLibrary().isDebugEnabled()) {
389 for (auto &[_, lib] : data->libraryMap) {
390 if (lib)
391 qCDebug(lcDebugLibrary)
392 << "On QtCore unload," << lib->fileName << "was leaked, with"
393 << lib->libraryRefCount.loadRelaxed() << "users";
394 }
395 }
396
397 delete data;
398}
399
400static void qlibraryCleanup()
401{
403}
404Q_DESTRUCTOR_FUNCTION(qlibraryCleanup)
405
406// must be called with a locked mutex
407QLibraryStore *QLibraryStore::instance()
408{
409 if (Q_UNLIKELY(!qt_library_data_once && !qt_library_data)) {
410 // only create once per process lifetime
411 qt_library_data = new QLibraryStore;
413 }
414 return qt_library_data;
415}
416
417inline QLibraryPrivate *QLibraryStore::findOrCreate(const QString &fileName, const QString &version,
418 QLibrary::LoadHints loadHints)
419{
420 auto lazyNewLib = [&] {
421 auto result = new QLibraryPrivate(fileName, version, loadHints);
422 result->libraryRefCount.ref();
423 return result;
424 };
425
426 if (fileName.isEmpty()) // request for empty d-pointer in QLibrary::setLoadHints();
427 return lazyNewLib(); // must return an independent (new) object
428
429 QMutexLocker locker(&qt_library_mutex);
430 QLibraryStore *data = instance();
431
432 if (Q_UNLIKELY(!data)) {
433 locker.unlock();
434 return lazyNewLib();
435 }
436
437 QString mapName = version.isEmpty() ? fileName : fileName + u'\0' + version;
438
439 QLibraryPrivate *&lib = data->libraryMap[std::move(mapName)];
440 if (lib) {
441 // already loaded
442 lib->libraryRefCount.ref();
443 lib->mergeLoadHints(loadHints);
444 } else {
445 lib = lazyNewLib();
446 }
447
448 return lib;
449}
450
452{
453 QMutexLocker locker(&qt_library_mutex);
454 QLibraryStore *data = instance();
455
456 if (lib->libraryRefCount.deref()) {
457 // still in use
458 return;
459 }
460
461 // no one else is using
462 Q_ASSERT(lib->libraryUnloadCount.loadRelaxed() == 0);
463
464 if (Q_LIKELY(data) && !lib->fileName.isEmpty()) {
465 using q20::erase_if;
466 const auto n = erase_if(data->libraryMap, [lib](const auto &e) {
467 return e.second == lib;
468 });
469 Q_ASSERT_X(n, "~QLibrary", "Did not find this library in the library map");
470 Q_UNUSED(n);
471 }
472 delete lib;
473}
474
475QLibraryPrivate::QLibraryPrivate(const QString &canonicalFileName, const QString &version, QLibrary::LoadHints loadHints)
476 : fileName(canonicalFileName), fullVersion(version), pluginState(MightBeAPlugin)
477{
478 loadHintsInt.storeRelaxed(loadHints.toInt());
479 if (canonicalFileName.isEmpty())
480 errorString = QLibrary::tr("The shared library was not found.");
481}
482
483QLibraryPrivate *QLibraryPrivate::findOrCreate(const QString &fileName, const QString &version,
484 QLibrary::LoadHints loadHints)
485{
486 return QLibraryStore::findOrCreate(fileName, version, loadHints);
487}
488
489QLibraryPrivate::~QLibraryPrivate()
490{
491}
492
493void QLibraryPrivate::mergeLoadHints(QLibrary::LoadHints lh)
494{
495 // if the library is already loaded, we can't change the load hints
496 if (pHnd.loadRelaxed())
497 return;
498
499 loadHintsInt.fetchAndOrRelaxed(lh.toInt());
500}
501
503{
504 if (!pHnd.loadRelaxed())
505 return nullptr;
506 return resolve_sys(symbol);
507}
508
509void QLibraryPrivate::setLoadHints(QLibrary::LoadHints lh)
510{
511 // Set the load hints directly for a dummy if this object is not associated
512 // with a file. Such object is not shared between multiple instances.
513 if (fileName.isEmpty()) {
514 loadHintsInt.storeRelaxed(lh.toInt());
515 return;
516 }
517
518 // this locks a global mutex
519 QMutexLocker lock(&qt_library_mutex);
520 mergeLoadHints(lh);
521}
522
524{
525 // first, check if the instance is cached and hasn't been deleted
526 QObject *obj = [&](){ QMutexLocker locker(&mutex); return inst.data(); }();
527 if (obj)
528 return obj;
529
530 // We need to call the plugin's factory function. Is that cached?
531 // skip increasing the reference count (why? -Thiago)
532 QtPluginInstanceFunction factory = instanceFactory.loadAcquire();
533 if (!factory)
534 factory = loadPlugin();
535
536 if (!factory)
537 return nullptr;
538
539 obj = factory();
540
541 // cache again
542 QMutexLocker locker(&mutex);
543 if (inst)
544 obj = inst;
545 else
546 inst = obj;
547 return obj;
548}
549
551{
552 if (pHnd.loadRelaxed()) {
553 libraryUnloadCount.ref();
554 return true;
555 }
556 if (fileName.isEmpty())
557 return false;
558
559 Q_TRACE(QLibraryPrivate_load_entry, fileName);
560
561 bool ret = load_sys();
562 qCDebug(lcDebugLibrary)
563 << fileName
564 << (ret ? "loaded library" : qUtf8Printable(u"cannot load: " + errorString));
565 if (ret) {
566 //when loading a library we add a reference to it so that the QLibraryPrivate won't get deleted
567 //this allows to unload the library at a later time
568 libraryUnloadCount.ref();
569 libraryRefCount.ref();
571 }
572
573 Q_TRACE(QLibraryPrivate_load_exit, ret);
574
575 return ret;
576}
577
579{
580 if (!pHnd.loadRelaxed())
581 return false;
582 if (libraryUnloadCount.loadRelaxed() > 0 && !libraryUnloadCount.deref()) { // only unload if ALL QLibrary instance wanted to
583 QMutexLocker locker(&mutex);
584 delete inst.data();
585 if (flag == NoUnloadSys || unload_sys()) {
586 qCDebug(lcDebugLibrary) << fileName << "unloaded library"
587 << (flag == NoUnloadSys ? "(faked)" : "");
588 // when the library is unloaded, we release the reference on it so that 'this'
589 // can get deleted
590 libraryRefCount.deref();
591 pHnd.storeRelaxed(nullptr);
592 instanceFactory.storeRelaxed(nullptr);
593 return true;
594 }
595 }
596
597 return false;
598}
599
604
606{
607 if (auto ptr = instanceFactory.loadAcquire()) {
608 libraryUnloadCount.ref();
609 return ptr;
610 }
611 if (pluginState == IsNotAPlugin)
612 return nullptr;
613 if (load()) {
614 auto ptr = reinterpret_cast<QtPluginInstanceFunction>(resolve("qt_plugin_instance"));
615 instanceFactory.storeRelease(ptr); // two threads may store the same value
616 if (Q_LIKELY(ptr))
617 return ptr;
618 errorString = QLibrary::tr("Could not resolve 'qt_plugin_instance' function");
619 }
620 qCDebug(qt_lcDebugPlugins) << "QLibraryPrivate::loadPlugin failed on" << fileName << ":" << errorString;
621 pluginState = IsNotAPlugin;
622 return nullptr;
623}
624
625/*!
626 Returns \c true if \a fileName has a valid suffix for a loadable
627 library; otherwise returns \c false.
628
629 \table
630 \header \li Platform \li Valid suffixes
631 \row \li Windows \li \c .dll, \c .DLL
632 \row \li Unix/Linux \li \c .so
633 \row \li AIX \li \c .a
634 \row \li HP-UX \li \c .sl, \c .so (HP-UXi)
635 \row \li \macos and iOS \li \c .dylib, \c .bundle, \c .so
636 \endtable
637
638 Trailing versioning numbers on Unix are ignored.
639 */
640bool QLibrary::isLibrary(const QString &fileName)
641{
642#if defined(Q_OS_WIN) || defined(Q_OS_CYGWIN)
643 return fileName.endsWith(".dll"_L1, Qt::CaseInsensitive);
644#else // Generic Unix
645# if defined(Q_OS_DARWIN)
646 // On Apple platforms, dylib look like libmylib.1.0.0.dylib
647 if (fileName.endsWith(".dylib"_L1))
648 return true;
649# endif
650 QString completeSuffix = QFileInfo(fileName).completeSuffix();
651 if (completeSuffix.isEmpty())
652 return false;
653
654 // if this throws an empty-array error, you need to fix the #ifdef's:
655 const QLatin1StringView candidates[] = {
656# if defined(Q_OS_HPUX)
657/*
658 See "HP-UX Linker and Libraries User's Guide", section "Link-time Differences between PA-RISC and IPF":
659 "In PA-RISC (PA-32 and PA-64) shared libraries are suffixed with .sl. In IPF (32-bit and 64-bit),
660 the shared libraries are suffixed with .so. For compatibility, the IPF linker also supports the .sl suffix."
661*/
662 "sl"_L1,
663# if defined __ia64
664 "so"_L1,
665# endif
666# elif defined(Q_OS_AIX)
667 "a"_L1,
668 "so"_L1,
669# elif defined(Q_OS_DARWIN)
670 "so"_L1,
671 "bundle"_L1,
672# elif defined(Q_OS_UNIX)
673 "so"_L1,
674# endif
675 }; // candidates
676
677 auto isValidSuffix = [&candidates](QStringView s) {
678 return std::find(std::begin(candidates), std::end(candidates), s) != std::end(candidates);
679 };
680
681 // Examples of valid library names:
682 // libfoo.so
683 // libfoo.so.0
684 // libfoo.so.0.3
685 // libfoo-0.3.so
686 // libfoo-0.3.so.0.3.0
687
688 auto suffixes = qTokenize(completeSuffix, u'.');
689 auto it = suffixes.begin();
690 const auto end = suffixes.end();
691
692 auto isNumeric = [](QStringView s) { bool ok; (void)s.toInt(&ok); return ok; };
693
694 while (it != end) {
695 if (isValidSuffix(*it++))
696 return q20::ranges::all_of(it, end, isNumeric);
697 }
698 return false; // no valid suffix found
699#endif
700}
701
702static bool qt_get_metadata(QLibraryPrivate *priv, QString *errMsg)
703{
704 auto error = [=](QString &&explanation) {
705 *errMsg = QLibrary::tr("'%1' is not a Qt plugin (%2)").arg(priv->fileName, explanation);
706 return false;
707 };
708
709 QPluginMetaData metaData;
710 QFunctionPointer pfn = priv->resolve("qt_plugin_query_metadata_v2");
711 if (pfn) {
712 metaData = reinterpret_cast<QPluginMetaData (*)()>(pfn)();
713#if QT_VERSION <= QT_VERSION_CHECK(7, 0, 0)
714 } else if ((pfn = priv->resolve("qt_plugin_query_metadata"))) {
715 metaData = reinterpret_cast<QPluginMetaData (*)()>(pfn)();
716 if (metaData.size < sizeof(QPluginMetaData::MagicHeader))
717 return error(QLibrary::tr("metadata too small"));
718
719 // adjust the meta data to point to the header
720 auto data = reinterpret_cast<const char *>(metaData.data);
721 data += sizeof(QPluginMetaData::MagicString);
722 metaData.data = data;
723 metaData.size -= sizeof(QPluginMetaData::MagicString);
724#endif
725 } else {
726 return error(QLibrary::tr("entrypoint to query the plugin meta data not found"));
727 }
728
729 if (metaData.size < sizeof(QPluginMetaData::Header))
730 return error(QLibrary::tr("metadata too small"));
731
732 if (priv->metaData.parse(metaData))
733 return true;
734 *errMsg = priv->metaData.errorString();
735 return false;
736}
737
739{
740 if (pluginState == MightBeAPlugin)
742
743 return pluginState == IsAPlugin;
744}
745
747{
748 QMutexLocker locker(&mutex);
749 errorString.clear();
750 if (pluginState != MightBeAPlugin)
751 return;
752
753 bool success = false;
754
755#if defined(Q_OS_UNIX) && !defined(Q_OS_DARWIN)
756 if (fileName.endsWith(".debug"_L1)) {
757 // refuse to load a file that ends in .debug
758 // these are the debug symbols from the libraries
759 // the problem is that they are valid shared library files
760 // and dlopen is known to crash while opening them
761
762 // pretend we didn't see the file
763 errorString = QLibrary::tr("The shared library was not found.");
764 pluginState = IsNotAPlugin;
765 return;
766 }
767#endif
768
769 if (!pHnd.loadRelaxed()) {
770 // scan for the plugin metadata without loading
771 QLibraryScanResult result = findPatternUnloaded(fileName, this);
772#if defined(Q_OF_MACH_O)
773 if (result.length && result.isEncrypted) {
774 // We found the .qtmetadata section, but since the library is encrypted
775 // we need to dlopen() it before we can parse the metadata for further
776 // validation.
777 qCDebug(qt_lcDebugPlugins, "Library is encrypted. Doing prospective load before parsing metadata");
778 locker.unlock();
779 load();
780 locker.relock();
781 success = qt_get_metadata(this, &errorString);
782 } else
783#endif
784 {
785 success = result.length != 0;
786 }
787 } else {
788 // library is already loaded (probably via QLibrary)
789 // simply get the target function and call it.
790 success = qt_get_metadata(this, &errorString);
791 }
792
793 if (!success) {
794 if (errorString.isEmpty()) {
795 if (fileName.isEmpty())
796 errorString = QLibrary::tr("The shared library was not found.");
797 else
798 errorString = QLibrary::tr("The file '%1' is not a valid Qt plugin.").arg(fileName);
799 }
800 pluginState = IsNotAPlugin;
801 return;
802 }
803
804 pluginState = IsNotAPlugin; // be pessimistic
805
806 uint qt_version = uint(metaData.value(QtPluginMetaDataKeys::QtVersion).toInteger());
807 bool debug = metaData.value(QtPluginMetaDataKeys::IsDebug).toBool();
808 if ((qt_version & 0x00ff00) > (QT_VERSION & 0x00ff00) || (qt_version & 0xff0000) != (QT_VERSION & 0xff0000)) {
809 qCDebug(qt_lcDebugPlugins, "In %s:\n"
810 " Plugin uses incompatible Qt library (%d.%d.%d) [%s]",
811 QFile::encodeName(fileName).constData(),
812 (qt_version&0xff0000) >> 16, (qt_version&0xff00) >> 8, qt_version&0xff,
813 debug ? "debug" : "release");
814 errorString = QLibrary::tr("The plugin '%1' uses incompatible Qt library. (%2.%3.%4) [%5]")
815 .arg(fileName,
816 QString::number((qt_version & 0xff0000) >> 16),
817 QString::number((qt_version & 0xff00) >> 8),
818 QString::number(qt_version & 0xff),
819 debug ? "debug"_L1 : "release"_L1);
820 } else if (PluginMustMatchQtDebug && debug != QtBuildIsDebug) {
821 //don't issue a qWarning since we will hopefully find a non-debug? --Sam
822 errorString = QLibrary::tr("The plugin '%1' uses incompatible Qt library."
823 " (Cannot mix debug and release libraries.)").arg(fileName);
824 } else {
825 pluginState = IsAPlugin;
826 }
827}
828
829/*!
830 Loads the library and returns \c true if the library was loaded
831 successfully; otherwise returns \c false. Since resolve() always
832 calls this function before resolving any symbols it is not
833 necessary to call it explicitly. In some situations you might want
834 the library loaded in advance, in which case you would use this
835 function.
836
837 \sa unload()
838*/
839bool QLibrary::load()
840{
841 if (!d)
842 return false;
843 if (d.tag() == Loaded)
844 return d->pHnd.loadRelaxed();
845 if (d->load()) {
846 d.setTag(Loaded);
847 return true;
848 }
849 return false;
850}
851
852/*!
853 Unloads the library and returns \c true if the library could be
854 unloaded; otherwise returns \c false.
855
856 This happens automatically on application termination, so you
857 shouldn't normally need to call this function.
858
859 If other instances of QLibrary are using the same library, the
860 call will fail, and unloading will only happen when every instance
861 has called unload().
862
863 Note that on \macos, dynamic libraries cannot be unloaded.
864 QLibrary::unload() will return \c true, but the library will remain
865 loaded into the process.
866
867 \sa resolve(), load()
868*/
869bool QLibrary::unload()
870{
871 if (d.tag() == Loaded) {
872 d.setTag(NotLoaded);
873 return d->unload();
874 }
875 return false;
876}
877
878/*!
879 Returns \c true if load() succeeded; otherwise returns \c false.
880
881 \note Prior to Qt 6.6, this function would return \c true even without a
882 call to load() if another QLibrary object on the same library had caused it
883 to be loaded.
884
885 \sa load()
886 */
887bool QLibrary::isLoaded() const
888{
889 return d.tag() == Loaded;
890}
891
892
893/*!
894 Constructs a library with the given \a parent.
895 */
896QLibrary::QLibrary(QObject *parent) : QObject(parent)
897{
898}
899
900
901/*!
902 Constructs a library object with the given \a parent that will
903 load the library specified by \a fileName.
904
905 We recommend omitting the file's suffix in \a fileName, since
906 QLibrary will automatically look for the file with the appropriate
907 suffix in accordance with the platform, e.g. ".so" on Unix,
908 ".dylib" on \macos and iOS, and ".dll" on Windows. (See \l{fileName}.)
909 */
910QLibrary::QLibrary(const QString &fileName, QObject *parent) : QObject(parent)
911{
912 setFileName(fileName);
913}
914
915/*!
916 Constructs a library object with the given \a parent that will
917 load the library specified by \a fileName and major version number \a verNum.
918 Currently, the version number is ignored on Windows.
919
920 We recommend omitting the file's suffix in \a fileName, since
921 QLibrary will automatically look for the file with the appropriate
922 suffix in accordance with the platform, e.g. ".so" on Unix,
923 ".dylib" on \macos and iOS, and ".dll" on Windows. (See \l{fileName}.)
924*/
925QLibrary::QLibrary(const QString &fileName, int verNum, QObject *parent) : QObject(parent)
926{
927 setFileNameAndVersion(fileName, verNum);
928}
929
930/*!
931 Constructs a library object with the given \a parent that will
932 load the library specified by \a fileName and full version number \a version.
933 Currently, the version number is ignored on Windows.
934
935 We recommend omitting the file's suffix in \a fileName, since
936 QLibrary will automatically look for the file with the appropriate
937 suffix in accordance with the platform, e.g. ".so" on Unix,
938 ".dylib" on \macos and iOS, and ".dll" on Windows. (See \l{fileName}.)
939 */
940QLibrary::QLibrary(const QString &fileName, const QString &version, QObject *parent)
941 : QObject(parent)
942{
943 setFileNameAndVersion(fileName, version);
944}
945
946/*!
947 Destroys the QLibrary object.
948
949 Unless unload() was called explicitly, the library stays in memory
950 until the application terminates.
951
952 \sa isLoaded(), unload()
953*/
954QLibrary::~QLibrary()
955{
956 if (d)
957 d->release();
958}
959
960/*!
961 \property QLibrary::fileName
962 \brief the file name of the library
963
964 We recommend omitting the file's suffix in the file name, since
965 QLibrary will automatically look for the file with the appropriate
966 suffix (see isLibrary()).
967
968 When loading the library, QLibrary searches in all system-specific
969 library locations (for example, \c LD_LIBRARY_PATH on Unix), unless the
970 file name has an absolute path. After loading the library
971 successfully, fileName() returns the fully-qualified file name of
972 the library, including the full path to the library if one was given
973 in the constructor or passed to setFileName().
974
975 For example, after successfully loading the "GL" library on Unix
976 platforms, fileName() will return "libGL.so". If the file name was
977 originally passed as "/usr/lib/libGL", fileName() will return
978 "/usr/lib/libGL.so".
979*/
980
981void QLibrary::setFileName(const QString &fileName)
982{
983 setFileNameAndVersion(fileName, QString());
984}
985
986QString QLibrary::fileName() const
987{
988 if (d) {
989 QMutexLocker locker(&d->mutex);
990 return d->qualifiedFileName.isEmpty() ? d->fileName : d->qualifiedFileName;
991 }
992 return QString();
993}
994
995/*!
996 \fn void QLibrary::setFileNameAndVersion(const QString &fileName, int versionNumber)
997
998 Sets the fileName property and major version number to \a fileName
999 and \a versionNumber respectively.
1000 The \a versionNumber is ignored on Windows.
1001
1002 \sa setFileName()
1003*/
1004void QLibrary::setFileNameAndVersion(const QString &fileName, int verNum)
1005{
1006 setFileNameAndVersion(fileName, verNum >= 0 ? QString::number(verNum) : QString());
1007}
1008
1009/*!
1010 \since 4.4
1011
1012 Sets the fileName property and full version number to \a fileName
1013 and \a version respectively.
1014 The \a version parameter is ignored on Windows.
1015
1016 \sa setFileName()
1017*/
1018void QLibrary::setFileNameAndVersion(const QString &fileName, const QString &version)
1019{
1020 QLibrary::LoadHints lh;
1021 if (d) {
1022 lh = d->loadHints();
1023 d->release();
1024 }
1025 QLibraryPrivate *dd = QLibraryPrivate::findOrCreate(fileName, version, lh);
1026 d = QTaggedPointer(dd, NotLoaded); // we haven't load()ed
1027}
1028
1029/*!
1030 Returns the address of the exported symbol \a symbol. The library is
1031 loaded if necessary. The function returns \nullptr if the symbol could
1032 not be resolved or if the library could not be loaded.
1033
1034 Example:
1035 \snippet code/src_corelib_plugin_qlibrary.cpp 2
1036
1037 The symbol must be exported as a C function from the library. This
1038 means that the function must be wrapped in an \c{extern "C"} if
1039 the library is compiled with a C++ compiler. On Windows you must
1040 also explicitly export the function from the DLL using the
1041 \c{__declspec(dllexport)} compiler directive, for example:
1042
1043 \snippet code/src_corelib_plugin_qlibrary.cpp 3
1044
1045 with \c MY_EXPORT defined as
1046
1047 \snippet code/src_corelib_plugin_qlibrary.cpp 4
1048*/
1049QFunctionPointer QLibrary::resolve(const char *symbol)
1050{
1051 if (!isLoaded() && !load())
1052 return nullptr;
1053 return d->resolve(symbol);
1054}
1055
1056/*!
1057 \overload
1058
1059 Loads the library \a fileName and returns the address of the
1060 exported symbol \a symbol. Note that \a fileName should not
1061 include the platform-specific file suffix; (see \l{fileName}). The
1062 library remains loaded until the application exits.
1063
1064 The function returns \nullptr if the symbol could not be resolved or if
1065 the library could not be loaded.
1066
1067 \sa resolve()
1068*/
1069QFunctionPointer QLibrary::resolve(const QString &fileName, const char *symbol)
1070{
1071 QLibrary library(fileName);
1072 return library.resolve(symbol);
1073}
1074
1075/*!
1076 \overload
1077
1078 Loads the library \a fileName with major version number \a verNum and
1079 returns the address of the exported symbol \a symbol.
1080 Note that \a fileName should not include the platform-specific file suffix;
1081 (see \l{fileName}). The library remains loaded until the application exits.
1082 \a verNum is ignored on Windows.
1083
1084 The function returns \nullptr if the symbol could not be resolved or if
1085 the library could not be loaded.
1086
1087 \sa resolve()
1088*/
1089QFunctionPointer QLibrary::resolve(const QString &fileName, int verNum, const char *symbol)
1090{
1091 QLibrary library(fileName, verNum);
1092 return library.resolve(symbol);
1093}
1094
1095/*!
1096 \overload
1097 \since 4.4
1098
1099 Loads the library \a fileName with full version number \a version and
1100 returns the address of the exported symbol \a symbol.
1101 Note that \a fileName should not include the platform-specific file suffix;
1102 (see \l{fileName}). The library remains loaded until the application exits.
1103 \a version is ignored on Windows.
1104
1105 The function returns \nullptr if the symbol could not be resolved or if
1106 the library could not be loaded.
1107
1108 \sa resolve()
1109*/
1110QFunctionPointer QLibrary::resolve(const QString &fileName, const QString &version, const char *symbol)
1111{
1112 QLibrary library(fileName, version);
1113 return library.resolve(symbol);
1114}
1115
1116/*!
1117 \since 4.2
1118
1119 Returns a text string with the description of the last error that occurred.
1120 Currently, errorString will only be set if load(), unload() or resolve() for some reason fails.
1121*/
1122QString QLibrary::errorString() const
1123{
1124 QString str;
1125 if (d) {
1126 QMutexLocker locker(&d->mutex);
1127 str = d->errorString;
1128 }
1129 return str.isEmpty() ? tr("Unknown error") : str;
1130}
1131
1132/*!
1133 \property QLibrary::loadHints
1134 \brief Give the load() function some hints on how it should behave.
1135
1136 You can give some hints on how the symbols are resolved. Usually,
1137 the symbols are not resolved at load time, but resolved lazily,
1138 (that is, when resolve() is called). If you set the loadHints to
1139 ResolveAllSymbolsHint, then all symbols will be resolved at load time
1140 if the platform supports it.
1141
1142 Setting ExportExternalSymbolsHint will make the external symbols in the
1143 library available for resolution in subsequent loaded libraries.
1144
1145 If LoadArchiveMemberHint is set, the file name
1146 is composed of two components: A path which is a reference to an
1147 archive file followed by the second component which is the reference to
1148 the archive member. For instance, the fileName \c libGL.a(shr_64.o) will refer
1149 to the library \c shr_64.o in the archive file named \c libGL.a. This
1150 is only supported on the AIX platform.
1151
1152 The interpretation of the load hints is platform dependent, and if
1153 you use it you are probably making some assumptions on which platform
1154 you are compiling for, so use them only if you understand the consequences
1155 of them.
1156
1157 By default, none of these flags are set, so libraries will be loaded with
1158 lazy symbol resolution, and will not export external symbols for resolution
1159 in other dynamically-loaded libraries.
1160
1161 \note Hints can only be cleared when this object is not associated with a
1162 file. Hints can only be added once the file name is set (\a hints will
1163 be or'ed with the old hints).
1164
1165 \note Setting this property after the library has been loaded has no effect
1166 and loadHints() will not reflect those changes.
1167
1168 \note This property is shared among all QLibrary instances that refer to
1169 the same library.
1170*/
1171void QLibrary::setLoadHints(LoadHints hints)
1172{
1173 if (!d) {
1174 d = QLibraryPrivate::findOrCreate(QString()); // ugly, but we need a d-ptr
1175 d->errorString.clear();
1176 }
1177 d->setLoadHints(hints);
1178}
1179
1180QLibrary::LoadHints QLibrary::loadHints() const
1181{
1182 return d ? d->loadHints() : QLibrary::LoadHints();
1183}
1184
1185/* Internal, for debugging */
1187{
1188 static int debug_env = QT_PREPEND_NAMESPACE(qEnvironmentVariableIntValue)("QT_DEBUG_PLUGINS");
1189 return debug_env != 0;
1190}
1191
1192QT_END_NAMESPACE
1193
1194#include "moc_qlibrary.cpp"
Definition qfile.h:71
Q_AUTOTEST_EXPORT bool unload(UnloadFlag flag=UnloadSys)
Definition qlibrary.cpp:578
QtPluginInstanceFunction loadPlugin()
Definition qlibrary.cpp:605
void setLoadHints(QLibrary::LoadHints lh)
Definition qlibrary.cpp:509
void updatePluginState()
Definition qlibrary.cpp:746
QFunctionPointer resolve(const char *)
Definition qlibrary.cpp:502
QObject * pluginInstance()
Definition qlibrary.cpp:523
static void cleanup()
Definition qlibrary.cpp:362
static void releaseLibrary(QLibraryPrivate *lib)
Definition qlibrary.cpp:451
static QLibraryPrivate * findOrCreate(const QString &fileName, const QString &version, QLibrary::LoadHints loadHints)
Definition qlibrary.cpp:417
\inmodule QtCore
Definition qmutex.h:347
Q_TRACE_POINT(qtcore, QLibraryPrivate_load_exit, bool success)
static void installCoverageTool(QLibraryPrivate *libPrivate)
Definition qlibrary.cpp:304
static constexpr bool PluginMustMatchQtDebug
Definition qlibrary.cpp:46
bool qt_debug_component()
Q_TRACE_POINT(qtcore, QLibraryPrivate_load_entry, const QString &fileName)
static bool qt_get_metadata(QLibraryPrivate *priv, QString *errMsg)
Definition qlibrary.cpp:702
static Q_CONSTINIT bool qt_library_data_once
Definition qlibrary.cpp:355
static QLibraryScanResult findPatternUnloaded(const QString &library, QLibraryPrivate *lib)
Definition qlibrary.cpp:238
static constexpr bool QtBuildIsDebug
Definition qlibrary.cpp:56
static void qlibraryCleanup()
Definition qlibrary.cpp:400