]> granicus.if.org Git - icinga2/blob - lib/base/library.cpp
Merge pull request #7185 from Icinga/bugfix/gelfwriter-wrong-log-facility
[icinga2] / lib / base / library.cpp
1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
2
3 #include "base/library.hpp"
4 #include "base/loader.hpp"
5 #include "base/logger.hpp"
6 #include "base/exception.hpp"
7 #include "base/application.hpp"
8
9 using namespace icinga;
10
11 /**
12  * Loads the specified library.
13  *
14  * @param name The name of the library.
15  */
16 Library::Library(const String& name)
17 {
18         String path;
19 #if defined(_WIN32)
20         path = name + ".dll";
21 #elif defined(__APPLE__)
22         path = "lib" + name + "." + Application::GetAppSpecVersion() + ".dylib";
23 #else /* __APPLE__ */
24         path = "lib" + name + ".so." + Application::GetAppSpecVersion();
25 #endif /* _WIN32 */
26
27         Log(LogNotice, "Library")
28                 << "Loading library '" << path << "'";
29
30 #ifdef _WIN32
31         HMODULE hModule = LoadLibrary(path.CStr());
32
33         if (!hModule) {
34                 BOOST_THROW_EXCEPTION(win32_error()
35                         << boost::errinfo_api_function("LoadLibrary")
36                         << errinfo_win32_error(GetLastError())
37                         << boost::errinfo_file_name(path));
38         }
39 #else /* _WIN32 */
40         void *hModule = dlopen(path.CStr(), RTLD_NOW | RTLD_GLOBAL);
41
42         if (!hModule) {
43                 BOOST_THROW_EXCEPTION(std::runtime_error("Could not load library '" + path + "': " + dlerror()));
44         }
45 #endif /* _WIN32 */
46
47         Loader::ExecuteDeferredInitializers();
48
49         m_Handle.reset(new LibraryHandle(hModule), [](LibraryHandle *handle) {
50 #ifdef _WIN32
51                 FreeLibrary(*handle);
52 #else /* _WIN32 */
53                 dlclose(*handle);
54 #endif /* _WIN32 */
55         });
56 }
57
58 void *Library::GetSymbolAddress(const String& name) const
59 {
60         if (!m_Handle)
61                 BOOST_THROW_EXCEPTION(std::runtime_error("Invalid library handle"));
62
63 #ifdef _WIN32
64         return GetProcAddress(*m_Handle.get(), name.CStr());
65 #else /* _WIN32 */
66         return dlsym(*m_Handle.get(), name.CStr());
67 #endif /* _WIN32 */
68 }