aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/utils/dyn_load/dyn_load.cpp
blob: 1f33dc7611f7fcfc2d0846a49cee7c2bd0423483 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
* Dynamically Loaded Object
* (C) 2010 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/dyn_load.h>
#include <botan/build.h>
#include <botan/exceptn.h>

#if defined(BOTAN_TARGET_OS_HAS_DLOPEN)
  #include <dlfcn.h>
#elif defined(BOTAN_TARGET_OS_HAS_LOADLIBRARY)
  #define NOMINMAX 1
  #include <windows.h>
#endif

namespace Botan {

namespace {

void raise_runtime_loader_exception(const std::string& lib_name,
                                    const char* msg)
   {
   throw Exception("Failed to load " + lib_name + ": " +
                            (msg ? msg : "Unknown error"));
   }

}

Dynamically_Loaded_Library::Dynamically_Loaded_Library(
   const std::string& library) :
   m_lib_name(library), m_lib(nullptr)
   {
#if defined(BOTAN_TARGET_OS_HAS_DLOPEN)
   m_lib = ::dlopen(m_lib_name.c_str(), RTLD_LAZY);

   if(!m_lib)
      raise_runtime_loader_exception(m_lib_name, dlerror());

#elif defined(BOTAN_TARGET_OS_HAS_LOADLIBRARY)
   m_lib = ::LoadLibraryA(m_lib_name.c_str());

   if(!m_lib)
      raise_runtime_loader_exception(m_lib_name, "LoadLibrary failed");
#endif

   if(!m_lib)
      raise_runtime_loader_exception(m_lib_name, "Dynamic load not supported");
   }

Dynamically_Loaded_Library::~Dynamically_Loaded_Library()
   {
#if defined(BOTAN_TARGET_OS_HAS_DLOPEN)
   ::dlclose(m_lib);
#elif defined(BOTAN_TARGET_OS_HAS_LOADLIBRARY)
   ::FreeLibrary((HMODULE)m_lib);
#endif
   }

void* Dynamically_Loaded_Library::resolve_symbol(const std::string& symbol)
   {
   void* addr = nullptr;

#if defined(BOTAN_TARGET_OS_HAS_DLOPEN)
   addr = ::dlsym(m_lib, symbol.c_str());
#elif defined(BOTAN_TARGET_OS_HAS_LOADLIBRARY)
   addr = reinterpret_cast<void*>(::GetProcAddress((HMODULE)m_lib,
                                                   symbol.c_str()));
#endif

   if(!addr)
      throw Exception("Failed to resolve symbol " + symbol +
                               " in " + m_lib_name);

   return addr;
   }

}