PluginManager.cxx
Go to the documentation of this file.
3 
4 #include <string>
5 #include <dlfcn.h>
6 
7 using namespace WireCell;
8 using namespace std;
9 
10 Plugin::Plugin(void* lib) : m_lib(lib) {}
11 Plugin::~Plugin() { dlclose(m_lib); }
12 
13 void* Plugin::raw(const std::string& symbol_name)
14 {
15  void* ret= dlsym(m_lib, symbol_name.c_str());
16  return ret;
17 }
18 
19 bool Plugin::contains(const std::string& symbol_name)
20 {
21  return nullptr != raw(symbol_name);
22 }
23 
24 
25 
27 {
28  static PluginManager inst;
29  return inst;
30 }
31 
33  const std::string& libname)
34 {
35  Plugin* plugin = get(plugin_name);
36  if (plugin) {
37  l->debug("already have plugin {}", plugin_name);
38  return plugin;
39  }
40 
41  std::string exts[2] = {".so",".dylib"};
42  for (int ind=0; ind<2; ++ind) {
43  std::string ext = exts[ind];
44  string lname = "";
45  if (libname == "") {
46  lname = "lib";
47  lname += plugin_name;
48  lname += ext;
49  }
50  else {
51  lname = libname;
52  }
53  void* lib = dlopen(lname.c_str(), RTLD_NOW);
54  if (!lib) {
55  l->error("Failed to load {}: {}", lname, dlerror());
56  continue;
57  }
58 
59  m_plugins[plugin_name] = new Plugin(lib);
60  l->debug("loaded plugin #{} \"{}\" from library \"{}\": {}",
61  m_plugins.size(), plugin_name, lname,
62  (void*)m_plugins[plugin_name]);
63  return m_plugins[plugin_name];
64 
65  }
66  l->critical("no such plugin: \"{}\"", plugin_name);
67  THROW(IOError() << errmsg{"no such plugin: " + plugin_name});
68  return nullptr;
69 }
70 
72 {
73  auto pit = m_plugins.find(plugin_name);
74  if (pit == m_plugins.end()) {
75  return nullptr;
76  }
77  return pit->second;
78 }
79 
81 {
82  for (auto pit : m_plugins) {
83  Plugin* maybe = pit.second;
84  if (maybe->contains(symbol_name)) {
85  return maybe;
86  }
87  }
88  return nullptr;
89 }
90 
92  : l(Log::logger("sys"))
93 {
94 }
96 {
97  for (auto pit : m_plugins) {
98  delete pit.second;
99  pit.second = nullptr;
100  }
101 }
Thrown when an error involving accessing input or output has occurred.
Definition: Exceptions.h:46
bool contains(const std::string &symbol_name)
std::string string
Definition: nybbler.cc:12
boost::error_info< struct tag_errmsg, std::string > errmsg
Definition: Exceptions.h:54
STL namespace.
static PluginManager & instance()
static QStrList * l
Definition: config.cpp:1044
Plugin * get(const std::string &plugin_name)
Plugin * find(const std::string &symbol_name)
std::map< std::string, Plugin * > m_plugins
Definition: PluginManager.h:46
#define THROW(e)
Definition: Exceptions.h:25
logptr_t logger(std::string name)
Definition: Logging.cxx:71
Definition: Main.h:22
Plugin * add(const std::string &plugin_name, const std::string &libname="")
Add a plugin. If libname is not given, try to derive it.
void * raw(const std::string &symbol_name)