LIMA
Libre Multilingual Analyzer — C++ API
Loading...
Searching...
No Matches
DynamicLibrariesManager.cpp
Go to the documentation of this file.
1// Copyright 2002-2019 CEA LIST
2// SPDX-FileCopyrightText: 2022 CEA LIST <gael.de-chalendar@cea.fr>
3//
4// SPDX-License-Identifier: MIT
5
10
12#include "common/LimaCommon.h"
13
14#include <boost/filesystem.hpp>
15
16#ifdef WIN32
17#include <windows.h>
18#include <tlhelp32.h>
19#include <tchar.h>
20#elif __APPLE__
21#include <dlfcn.h>
22#else
23#include <link.h>
24#endif
25
26#include <iostream>
27#include <QtGlobal>
28#include <QString>
29#include <QStringList>
30#include <QRegularExpression>
31using namespace std;
32
33namespace Lima {
34namespace Common {
35
36class DynamicLibrariesManagerPrivate
37{
39 DynamicLibrariesManagerPrivate();
40
41 bool isSomethingSimilarLoaded(const std::string& libName) const;
42
43 std::map<std::string, std::shared_ptr< QLibrary > > m_handles;
44 // at load time, will try to load the libraries
45 // from these paths before the default ones
46 std::vector<std::string> m_supplementarySearchPath;
47};
48
49#if defined(__APPLE__)
50// Directory of the library containing this code (liblima-common-factory).
51static std::string ownLibraryDirectory()
52{
53 Dl_info info;
54 if (dladdr(reinterpret_cast<const void*>(&ownLibraryDirectory), &info) == 0
55 || info.dli_fname == nullptr)
56 return std::string();
57 return boost::filesystem::path(info.dli_fname).parent_path().string();
58}
59#endif
60
61#ifdef WIN32
62// Directory of the DLL containing this code (lima-common-factory.dll).
63static std::string ownLibraryDirectory()
64{
65 HMODULE module = nullptr;
66 if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
67 | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
68 reinterpret_cast<LPCWSTR>(&ownLibraryDirectory),
69 &module))
70 return std::string();
71 wchar_t path[4096];
72 auto length = GetModuleFileNameW(module, path, sizeof(path) / sizeof(path[0]));
73 if (length == 0 || length >= sizeof(path) / sizeof(path[0]))
74 return std::string();
75 return boost::filesystem::path(std::wstring(path, length)).parent_path().string();
76}
77#endif
78
79DynamicLibrariesManagerPrivate::DynamicLibrariesManagerPrivate() :
80 m_handles(),
81 m_supplementarySearchPath()
82{
83#ifdef WIN32
84 // Windows has no RPATH, and plain LoadLibrary does not search the
85 // directories added with AddDllDirectory (e.g. by Python): look for the
86 // plugins next to the LIMA libraries (bin/ of an install, aymara.libs/ of
87 // the Python wheel). Loaded by absolute path, their own dependencies are
88 // then also searched in that directory.
89 auto dir = ownLibraryDirectory();
90 if (!dir.empty())
91 m_supplementarySearchPath.push_back(dir);
92#elif defined(__APPLE__)
93 // dlopen of a bare library name does not search the rpaths of the
94 // executable on macOS (as the ELF RUNPATH does on Linux): look for the
95 // plugins next to the LIMA libraries (lib/ of the build tree or install)
96 auto dir = ownLibraryDirectory();
97 if (!dir.empty())
98 m_supplementarySearchPath.push_back(dir);
99#endif
100}
101
102bool DynamicLibrariesManagerPrivate::isSomethingSimilarLoaded(const std::string& libName) const
103{
104 bool alreadyLoaded = false;
105
106#ifdef WIN32
107 HANDLE hModuleSnap = INVALID_HANDLE_VALUE;
108 MODULEENTRY32 me32;
109
110 hModuleSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId());
111 if (hModuleSnap == INVALID_HANDLE_VALUE)
112 throw LimaException("CreateToolhelp32Snapshoot returned INVALID_HANDLE_VALUE.");
113
114 me32.dwSize = sizeof(MODULEENTRY32);
115
116 if (!Module32First(hModuleSnap, &me32))
117 {
118 CloseHandle(hModuleSnap);
119 throw LimaException("Module32First failed.");
120 }
121
122 do
123 {
124 //std::cerr << me32.szModule << std::endl;
125 // szModule is a TCHAR array (wide when UNICODE is defined, as with Qt):
126 // let boost::filesystem::path do the conversion in both cases.
127 boost::filesystem::path p(me32.szModule);
128 if (p.empty())
129 {
130 CloseHandle(hModuleSnap);
131 return false;
132 }
133
134 std::string fn = p.filename().string();
135 if (fn.find(libName, 0) == 0) // [plugin-name]
136 {
137 //std::cerr << "An attempt to load same lib twice detected" << std::endl;
138 CloseHandle(hModuleSnap);
139 return true;
140 }
141
142 } while (Module32Next(hModuleSnap, &me32));
143
144 CloseHandle(hModuleSnap);
145#elif __APPLE__
146//
147#else
148 std::pair<bool&, const std::string&> data(alreadyLoaded, libName);
149
150 dl_iterate_phdr([](dl_phdr_info *info, size_t size, void* data) -> int {
151 LIMA_UNUSED(size);
152
153 if (data == nullptr)
154 throw LimaException("Callback passed to dl_iterate_phdr unexpectedly got NULL in \"data\" argument.");
155
156 auto& d = *((std::pair<bool&, const std::string&>*)data);
157
158 //std::cerr << info->dlpi_name << std::endl;
159
160 if (info == nullptr || info->dlpi_name == nullptr)
161 throw LimaException("Callback passed to dl_iterate_phdr unexpectedly got NULL in \"info\" argument.");
162
163 std::string s(info->dlpi_name);
164 if (s.size() == 0)
165 return 0;
166
167 boost::filesystem::path p(info->dlpi_name);
168 std::string fn = p.filename().string();
169 if (fn.find(d.second, 0) == 3) // lib[plugin-name]
170 {
171 d.first = true;
172 return 1;
173 }
174
175 return 0;
176 }, &data);
177#endif
178
179 return alreadyLoaded;
180}
181
182DynamicLibrariesManager::DynamicLibrariesManager() :
184{
185}
186
190
191bool DynamicLibrariesManager::isLoaded(const std::string& libName)
192{
193 m_d->isSomethingSimilarLoaded(libName);
194 auto it = m_d->m_handles.find(libName);
195 return (it != m_d->m_handles.end());
196}
197
198bool DynamicLibrariesManager::loadLibrary(const std::string& libName)
199{
201 LDEBUG << "DynamicLibrariesManager::loadLibrary() -- libName=" << libName;
202
203 if (m_d->isSomethingSimilarLoaded(libName))
204 {
205 LTRACE << "DynamicLibrariesManager::loadLibrary trying to reload dynamic library " << libName;
206 LTRACE << "DynamicLibrariesManager::loadLibrary this is not an error, silently ignoring.";
207 return true;
208 }
209
210 auto it = m_d->m_handles.find(libName);
211 if (it != m_d->m_handles.end())
212 {
213 LTRACE << "DynamicLibrariesManager::loadLibrary trying to reload dynamic library." << libName;
214 LTRACE << "DynamicLibrariesManager::loadLibrary this is not an error, silently ignoring.";
215 return true;
216 }
217
218 std::shared_ptr< QLibrary > libhandle;
219 std::vector< std::pair< std::string, std::string> > triedPaths;
220 // try supplementary search path
221 for (const auto& path: m_d->m_supplementarySearchPath)
222 {
223 LDEBUG << "Trying supplementary " << (path+"/"+libName).c_str();
224#ifdef WIN32
225 // QLibrary uses LoadLibrary, which searches the dependencies of the
226 // plugin in the standard directories only (executable's, system, PATH).
227 // Load it first so that they are also searched next to it and in the
228 // directories added with AddDllDirectory (e.g. by Python's
229 // os.add_dll_directory); QLibrary then gets the already loaded module.
230 {
231 auto dllPath = boost::filesystem::path(path) / (libName + ".dll");
232 if (boost::filesystem::exists(dllPath))
233 {
234 if (LoadLibraryExW(dllPath.wstring().c_str(), nullptr,
235 LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
236 | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS) == nullptr)
237 {
239 LERROR << "DynamicLibrariesManager::loadLibrary() -- LoadLibraryExW"
240 << dllPath.string() << "failed with error" << GetLastError();
241 }
242 }
243 }
244#endif
245 auto candidate = path + "/" + libName;
246#ifdef __APPLE__
247 // Without the unversioned symlink (e.g. in a Python wheel, which cannot
248 // contain symlinks), load the versioned library (lib<name>.<N>.dylib):
249 // the name that the libraries linked with it reference, so that it is
250 // loaded only once
251 if (!boost::filesystem::exists(path + "/lib" + libName + ".dylib")
252 && boost::filesystem::is_directory(path))
253 {
254 for (const auto& entry: boost::filesystem::directory_iterator(path))
255 {
256 auto name = entry.path().filename().string();
257 if (name.rfind("lib" + libName + ".", 0) == 0
258 && name.size() > 6 && name.substr(name.size() - 6) == ".dylib")
259 {
260 candidate = entry.path().string();
261 break;
262 }
263 }
264 }
265#endif
266 libhandle = std::make_shared<QLibrary>(candidate.c_str());
267
268 libhandle->setLoadHints(QLibrary::ResolveAllSymbolsHint
269 | QLibrary::ExportExternalSymbolsHint);
270 if (libhandle->load())
271 {
272 m_d->m_handles.insert(std::make_pair(libName,libhandle));
273 LDEBUG << "the library " << libName.c_str()
274 << " was loaded from supplementary search path";
275 LDEBUG << "the library fully-qualified name: " << libhandle->fileName();
276 return true;
277 }
278 else
279 {
281 LDEBUG << "DynamicLibrariesManager::loadLibrary() -- "
282 << "Failed to open supplementary lib " << libhandle->errorString();
283 triedPaths.emplace_back( path, libhandle->errorString().toStdString() );
284 libhandle.reset();
285
286 }
287 }
288 // now try system default search path
289 if (!libhandle)
290 {
291 LDEBUG << "Trying " << libName;
292 libhandle = std::make_shared<QLibrary>( libName.c_str() );
293 libhandle->setLoadHints(QLibrary::ResolveAllSymbolsHint
294 | QLibrary::ExportExternalSymbolsHint);
295 if (libhandle->load())
296 {
297 m_d->m_handles.insert(std::make_pair(libName,libhandle));
298 LDEBUG << "the library " << libName
299 << " was loaded from system default search path";
300 LDEBUG << "the library fully-qualified name: " << libhandle->fileName();
301 return true;
302 }
303 else
304 {
306 for (const auto& pathErr: triedPaths)
307 {
308 LERROR << "Failed to load library " << libName << "from " << pathErr.first << " due to " << pathErr.second;
309 }
310 LERROR << "Failed to load library " << libName << "also from system paths";
311 LERROR << "DynamicLibrariesManager::loadLibrary() -- "
312 << "Failed to open system lib " << libhandle->errorString();
313 return false;
314 }
315 }
316 else
317 {
318 m_d->m_handles[libName] = libhandle;
319 LDEBUG << "the library " << libName << " was loaded";
320 return true;
321 }
322}
323
324void DynamicLibrariesManager::addSearchPath(const std::string& searchPath)
325{
326 if( std::find(
327 m_d->m_supplementarySearchPath.begin(),
328 m_d->m_supplementarySearchPath.end(), searchPath)
329 != m_d->m_supplementarySearchPath.end())
330 {
331 return;
332 }
333#ifdef DEBUG_CD
335 LINFO << "adding search path '" << searchPath.c_str() << "'";
336// std::cerr << "adding search path '" <<searchPath.c_str() << "'" << std::endl;
337#endif
338 m_d->m_supplementarySearchPath.push_back(searchPath);
339}
340
342{
343#ifdef DEBUG_CD
345#endif
346
347#ifdef WIN32
348#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
349 auto list = searchPathes.replace("\\","/").split(QRegularExpression("[;]"),
350 QString::SkipEmptyParts);
351#else
352 auto list = searchPathes.replace("\\","/").split(QRegularExpression("[;]"),
353 Qt::SkipEmptyParts);
354#endif
355#else
356#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
357 auto list = searchPathes.replace("\\","/").split(QRegularExpression("[:;]"),
358 QString::SkipEmptyParts);
359#else
360 auto list = searchPathes.replace("\\","/").split(QRegularExpression("[:;]"),
361 Qt::SkipEmptyParts);
362#endif
363#endif
364
365 for(const auto& searchPath: list)
366 {
367#ifdef DEBUG_CD
368 LINFO << "DynamicLibrariesManager::addSearchPathes() adding:" << searchPath;
369#endif
370 this->addSearchPath(searchPath.toStdString());
371 }
372}
373
374
375} // end namespace
376} // end namespace
handle dynamic library opening (wrapper around QLibrary)
#define LTRACE
Definition LimaCommon.h:156
#define LIMA_UNUSED(x)
Definition LimaCommon.h:224
#define LDEBUG
Definition LimaCommon.h:157
#define LINFO
Definition LimaCommon.h:158
#define LERROR
Definition LimaCommon.h:161
#define ABSTRACTFACTORYPATTERNLOGINIT
Definition LimaCommon.h:198
bool loadLibrary(const std::string &libName)
void addSearchPath(const std::string &searchPath)
bool isLoaded(const std::string &libName)
NAUTITIA.
STL namespace.