RSC  0.9.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
Plugin.cpp
Go to the documentation of this file.
1 /* ============================================================
2  *
3  * This file is part of the RSB project.
4  *
5  * Copyright (C) 2012 Jan Moringen <jmoringe@techfak.uni-bielefeld.de>
6  *
7  * This file may be licensed under the terms of the
8  * GNU Lesser General Public License Version 3 (the ``LGPL''),
9  * or (at your option) any later version.
10  *
11  * Software distributed under the License is distributed
12  * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
13  * express or implied. See the LGPL for the specific language
14  * governing rights and limitations.
15  *
16  * You should have received a copy of the LGPL along with this
17  * program. If not, go to http://www.gnu.org/licenses/lgpl.html
18  * or write to the Free Software Foundation, Inc.,
19  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20  *
21  * The development of this software was supported by:
22  * CoR-Lab, Research Institute for Cognition and Robotics
23  * Bielefeld University
24  *
25  * ============================================================ */
26 
27 #include "Plugin.h"
28 
29 #include <errno.h>
30 #include <string.h>
31 
32 #if defined(_WIN32)
33 #include <windows.h>
34 #endif
35 
36 #if defined(__linux__) or defined(__APPLE__)
37 #include <dlfcn.h>
38 #endif
39 
40 #include <stdexcept>
41 
42 #include <boost/format.hpp>
43 
44 #include "../logging/Logger.h"
45 #include "../logging/LoggerFactory.h"
46 
47 using namespace std;
48 
49 using namespace boost;
50 
51 namespace rsc {
52 namespace plugins {
53 
54 const std::string PLUGIN_INIT_SYMBOL = "rsc_plugin_init";
55 const std::string PLUGIN_SHUTDOWN_SYMBOL = "rsc_plugin_shutdown";
56 
57 class Impl {
58 public:
59  Impl(const std::string& name,
60  const std::string& library)
61  : logger(logging::LoggerFactory::getInstance()
62  .getLogger(str((format("rsc.plugins.Plugin[%1%]")
63  % name)))),
64  name(name), library(library),
65  loaded(false), handle(NULL),
66  init(NULL), shutdown(NULL) {
67  }
68 
69  const string& getName() const {
70  return this->name;
71  }
72 
73  const string& getLibrary() const {
74  return this->library;
75  }
76 
77  void load(bool wrapExceptions) {
78 
79  if (this->loaded) {
80  throw runtime_error(
81  boost::str(
82  boost::format(
83  "Plugin %1% is already loaded. Cannot load it again,")
84  % this->name));
85  }
86 
87  RSCINFO(this->logger, "Trying to load library `" << this->library << "'");
88 
89  // Load the library containing the plugin.
90  loadLibrary();
91 
92  // Lookup init and shutdown functions in the plugin library.
93  this->init
94  = reinterpret_cast<InitFunction>(resolveSymbol(PLUGIN_INIT_SYMBOL));
95  this->shutdown
96  = reinterpret_cast<ShutdownFunction>(resolveSymbol(PLUGIN_SHUTDOWN_SYMBOL));
97 
98  // Initialize the plugin.
99  RSCINFO(this->logger, "Initializing");
100  if (wrapExceptions) {
101  try {
102  this->init();
103  this->loaded = true;
104  } catch (const std::exception& e) {
105  throw runtime_error(str(format("Plugin `%1%' failed to initialize: %2%")
106  % this->name
107  % e.what()));
108  } catch (...) {
109  throw runtime_error(str(format("Plugin `%1%' failed to initialize due to unknown error.")
110  % this->name));
111  }
112  } else {
113  this->init();
114  this->loaded = true;
115  }
116  }
117 
118  void unload(bool wrapExceptions) {
119 
120  if (!loaded) {
121  throw runtime_error(
122  str(format("Plugin `%1%' failed cannot be unloaded because it has not been loaded correctly.")
123  % this->name));
124  }
125 
126  // Shut the plugin down.
127  RSCINFO(this->logger, "Shutting down");
128  this->loaded = false;
129 
130  if (wrapExceptions) {
131  try {
132  this->shutdown();
133  } catch (const std::exception& e) {
134  throw runtime_error(str(format("Plugin `%1%' failed to shutdown: %2%")
135  % this->name
136  % e.what()));
137  } catch (...) {
138  throw runtime_error(str(format("Plugin `%1%' failed to shutdown due to unknown error.")
139  % this->name));
140  }
141  } else {
142  this->shutdown();
143  }
144  }
145 private:
146  typedef void (*InitFunction)();
147  typedef void (*ShutdownFunction)();
148 
150 
151  string name;
152  string library;
153 
154  bool loaded;
155 
156 #if defined(_WIN32)
157  HMODULE handle;
158 #else
159  void* handle;
160 #endif
161  InitFunction init;
162  ShutdownFunction shutdown;
163 
164  void loadLibrary() {
165 #if defined(__linux__) || defined(__APPLE__)
166  if (!(this->handle = dlopen(this->library.c_str(), RTLD_NOW))) {
167  const char* result = dlerror();
168  throw runtime_error(str(format("Failed to load plugin `%1%' from shared object `%2%': %3%.")
169  % this->name
170  % this->library
171  % (result ? result : "<unknown error>")));
172  }
173 #elif defined(_WIN32)
174  if (!(this->handle= LoadLibrary(this->library.c_str()))) {
175  throw runtime_error(str(format("Failed to load plugin `%1%' from shared object `%2%': %3%.")
176  % this->name
177  % this->library
178  % GetLastError()));
179  }
180 #else
181  throw runtime_error("Plugins are not implemented for this platform.");
182 #endif
183  }
184 
185  void* resolveSymbol(const string& name) {
186  RSCINFO(this->logger, "Resolving symbol `"
187  << name
188  << "' in library `" << this->library << "'");
189 
190  assert(this->handle);
191 
192  void *address;
193 #if defined(__linux__) || defined(__APPLE__)
194  if (!(address = dlsym(this->handle, name.c_str()))) {
195  const char* result = dlerror();
196  throw runtime_error(str(format("Plugin `%1%' failed to define function `%2%': %3%")
197  % this->name
198  % name
199  % (result ? result : "<unknown error>")));
200  }
201 #elif defined(_WIN32)
202  if (!(address = GetProcAddress(this->handle, name.c_str()))) {
203  throw runtime_error(str(format("Plugin `%1%' failed to define function `%2%': %3%")
204  % this->name
205  % name
206  % GetLastError()));
207  }
208 #else
209  throw runtime_error("Plugins are not implemented for this platform.");
210 #endif
211  return address;
212  }
213 };
214 
215 Plugin::Plugin(Impl* impl)
216  : impl(impl) {
217 }
218 
220 }
221 
222 const string& Plugin::getName() const {
223  return this->impl->getName();
224 }
225 
226 void Plugin::load(bool wrapExceptions) {
227  this->impl->load(wrapExceptions);
228 }
229 
230 void Plugin::unload(bool wrapExceptions) {
231  this->impl->unload(wrapExceptions);
232 }
233 
234 string Plugin::getLibrary() const {
235  return this->impl->getLibrary();
236 }
237 
238 PluginPtr Plugin::create(const std::string& name, const std::string& library) {
239  return PluginPtr(new Plugin(new Impl(name, library)));
240 }
241 
242 }
243 }