Botan 1.10.17

dyn_load.cpp
Go to the documentation of this file.
1 /**
2 * Dynamically Loaded Object
3 * (C) 2010 Jack Lloyd
4 *
5 * Distributed under the terms of the Botan license
6 */
7
8 #include <botan/internal/dyn_load.h>
9 #include <botan/build.h>
10 #include <stdexcept>
11
12 #if defined(BOTAN_TARGET_OS_HAS_DLOPEN)
13 #include <dlfcn.h>
14 #elif defined(BOTAN_TARGET_OS_HAS_LOADLIBRARY)
15 #include <windows.h>
16 #endif
17
18 namespace Botan {
19
20 namespace {
21
22 void raise_runtime_loader_exception(const std::string& lib_name,
23 const char* msg)
24 {
25 throw std::runtime_error("Failed to load " + lib_name + ": " +
26 (msg ? msg : "Unknown error"));
27 }
28
29 }
30
31 Dynamically_Loaded_Library::Dynamically_Loaded_Library(
32 const std::string& library) :
33 lib_name(library), lib(0)
34 {
35 #if defined(BOTAN_TARGET_OS_HAS_DLOPEN)
36 lib = ::dlopen(lib_name.c_str(), RTLD_LAZY);
37
38 if(!lib)
39 raise_runtime_loader_exception(lib_name, dlerror());
40
41 #elif defined(BOTAN_TARGET_OS_HAS_LOADLIBRARY)
42 lib = ::LoadLibraryA(lib_name.c_str());
43
44 if(!lib)
45 raise_runtime_loader_exception(lib_name, "LoadLibrary failed");
46 #endif
47
48 if(!lib)
49 raise_runtime_loader_exception(lib_name, "Dynamic load not supported");
50 }
51
52 Dynamically_Loaded_Library::~Dynamically_Loaded_Library()
53 {
54 #if defined(BOTAN_TARGET_OS_HAS_DLOPEN)
55 ::dlclose(lib);
56 #elif defined(BOTAN_TARGET_OS_HAS_LOADLIBRARY)
57 ::FreeLibrary((HMODULE)lib);
58 #endif
59 }
60
61 void* Dynamically_Loaded_Library::resolve_symbol(const std::string& symbol)
62 {
63 void* addr = 0;
64
65 #if defined(BOTAN_TARGET_OS_HAS_DLOPEN)
66 addr = ::dlsym(lib, symbol.c_str());
67 #elif defined(BOTAN_TARGET_OS_HAS_LOADLIBRARY)
68 addr = reinterpret_cast<void*>(::GetProcAddress((HMODULE)lib,
69 symbol.c_str()));
70 #endif
71
72 if(!addr)
73 throw std::runtime_error("Failed to resolve symbol " + symbol +
74 " in " + lib_name);
75
76 return addr;
77 }
78
79 }
Botan::Dynamically_Loaded_Library::Dynamically_Loaded_Library
Dynamically_Loaded_Library(const std::string &lib_name)
Definition: dyn_load.cpp:31
Botan::Dynamically_Loaded_Library::~Dynamically_Loaded_Library
~Dynamically_Loaded_Library()
Definition: dyn_load.cpp:52
Botan::Dynamically_Loaded_Library::resolve_symbol
void * resolve_symbol(const std::string &symbol)
Definition: dyn_load.cpp:61
Botan
Definition: algo_base.h:14