class_loader_core.hpp
Go to the documentation of this file.
1 /*
2  * Software License Agreement (BSD License)
3  *
4  * Copyright (c) 2012, Willow Garage, Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions are met:
9  *
10  * * Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  * * Redistributions in binary form must reproduce the above copyright
13  * notice, this list of conditions and the following disclaimer in the
14  * documentation and/or other materials provided with the distribution.
15  * * Neither the name of the copyright holders nor the names of its
16  * contributors may be used to endorse or promote products derived from
17  * this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
23  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 #ifndef CLASS_LOADER__CLASS_LOADER_CORE_HPP_
33 #define CLASS_LOADER__CLASS_LOADER_CORE_HPP_
34 
35 #include <boost/thread/recursive_mutex.hpp>
36 #include <cstdio>
37 #include <map>
38 #include <string>
39 #include <typeinfo>
40 #include <utility>
41 #include <vector>
42 
43 #include "Poco/SharedLibrary.h"
44 
47 
52 namespace class_loader
53 {
54 
55 class ClassLoader; // Forward declaration
56 
57 namespace class_loader_private
58 {
59 
60 // Typedefs
61 /*****************************************************************************/
62 typedef std::string LibraryPath;
63 typedef std::string ClassName;
64 typedef std::string BaseClassName;
65 typedef std::map<ClassName, class_loader_private::AbstractMetaObjectBase *> FactoryMap;
66 typedef std::map<BaseClassName, FactoryMap> BaseToFactoryMapMap;
67 typedef std::pair<LibraryPath, Poco::SharedLibrary *> LibraryPair;
68 typedef std::vector<LibraryPair> LibraryVector;
69 typedef std::vector<AbstractMetaObjectBase *> MetaObjectVector;
70 
71 // Debug
72 /*****************************************************************************/
74 
75 // Global storage
76 /*****************************************************************************/
77 
82 BaseToFactoryMapMap & getGlobalPluginBaseToFactoryMapMap();
83 
88 LibraryVector & getLoadedLibraryVector();
89 
94 std::string getCurrentlyLoadingLibraryName();
95 
100 void setCurrentlyLoadingLibraryName(const std::string & library_name);
101 
102 
108 
114 
115 
120 FactoryMap & getFactoryMapForBaseClass(const std::string & typeid_base_class_name);
121 
126 template<typename Base>
128 {
129  return getFactoryMapForBaseClass(typeid(Base).name());
130 }
131 
136 boost::recursive_mutex & getLoadedLibraryVectorMutex();
137 boost::recursive_mutex & getPluginBaseToFactoryMapMapMutex();
138 
144 
149 void hasANonPurePluginLibraryBeenOpened(bool hasIt);
150 
151 // Plugin Functions
152 /*****************************************************************************/
153 
161 template<typename Derived, typename Base>
162 void registerPlugin(const std::string & class_name, const std::string & base_class_name)
163 {
164  // Note: This function will be automatically invoked when a dlopen() call
165  // opens a library. Normally it will happen within the scope of loadLibrary(),
166  // but that may not be guaranteed.
168  "class_loader.class_loader_private: "
169  "Registering plugin factory for class = %s, ClassLoader* = %p and library name %s.",
170  class_name.c_str(), getCurrentlyActiveClassLoader(),
172 
173  if (NULL == getCurrentlyActiveClassLoader()) {
175  "class_loader.impl: ALERT!!! "
176  "A library containing plugins has been opened through a means other than through the "
177  "class_loader or pluginlib package. "
178  "This can happen if you build plugin libraries that contain more than just plugins "
179  "(i.e. normal code your app links against). "
180  "This inherently will trigger a dlopen() prior to main() and cause problems as class_loader "
181  "is not aware of plugin factories that autoregister under the hood. "
182  "The class_loader package can compensate, but you may run into namespace collision problems "
183  "(e.g. if you have the same plugin class in two different libraries and you load them both "
184  "at the same time). "
185  "The biggest problem is that library can now no longer be safely unloaded as the "
186  "ClassLoader does not know when non-plugin code is still in use. "
187  "In fact, no ClassLoader instance in your application will be unable to unload any library "
188  "once a non-pure one has been opened. "
189  "Please refactor your code to isolate plugins into their own libraries.");
191  }
192 
193  // Create factory
195  new class_loader_private::MetaObject<Derived, Base>(class_name, base_class_name);
198 
199 
200  // Add it to global factory map map
202  FactoryMap & factoryMap = getFactoryMapForBaseClass<Base>();
203  if (factoryMap.find(class_name) != factoryMap.end()) {
205  "class_loader.impl: SEVERE WARNING!!! "
206  "A namespace collision has occured with plugin factory for class %s. "
207  "New factory will OVERWRITE existing one. "
208  "This situation occurs when libraries containing plugins are directly linked against an "
209  "executable (the one running right now generating this message). "
210  "Please separate plugins out into their own library or just don't link against the library "
211  "and use either class_loader::ClassLoader/MultiLibraryClassLoader to open.",
212  class_name.c_str());
213  }
214  factoryMap[class_name] = new_factory;
216 
218  "class_loader.class_loader_private: "
219  "Registration of %s complete (Metaobject Address = %p)",
220  class_name.c_str(), new_factory);
221 }
222 
229 template<typename Base>
230 Base * createInstance(const std::string & derived_class_name, ClassLoader * loader)
231 {
232  AbstractMetaObject<Base> * factory = NULL;
233 
235  FactoryMap & factoryMap = getFactoryMapForBaseClass<Base>();
236  if (factoryMap.find(derived_class_name) != factoryMap.end()) {
237  factory = dynamic_cast<class_loader_private::AbstractMetaObject<Base> *>(
238  factoryMap[derived_class_name]);
239  } else {
241  "class_loader.class_loader_private: No metaobject exists for class type %s.",
242  derived_class_name.c_str());
243  }
245 
246  Base * obj = NULL;
247  if (factory != NULL && factory->isOwnedBy(loader)) {
248  obj = factory->create();
249  }
250 
251  if (NULL == obj) { // Was never created
252  if (factory && factory->isOwnedBy(NULL)) {
254  "class_loader.impl: ALERT!!! "
255  "A metaobject (i.e. factory) exists for desired class, but has no owner. "
256  "This implies that the library containing the class was dlopen()ed by means other than "
257  "through the class_loader interface. "
258  "This can happen if you build plugin libraries that contain more than just plugins "
259  "(i.e. normal code your app links against) -- that intrinsically will trigger a dlopen() "
260  "prior to main(). "
261  "You should isolate your plugins into their own library, otherwise it will not be "
262  "possible to shutdown the library!");
263 
264  obj = factory->create();
265  } else {
267  "Could not create instance of type " + derived_class_name));
268  }
269  }
270 
272  "class_loader.class_loader_private: "
273  "Created instance of type %s and object pointer = %p",
274  (typeid(obj).name()), obj);
275 
276  return obj;
277 }
278 
284 template<typename Base>
285 std::vector<std::string> getAvailableClasses(ClassLoader * loader)
286 {
287  boost::recursive_mutex::scoped_lock lock(getPluginBaseToFactoryMapMapMutex());
288 
289  FactoryMap & factory_map = getFactoryMapForBaseClass<Base>();
290  std::vector<std::string> classes;
291  std::vector<std::string> classes_with_no_owner;
292 
293  for (FactoryMap::const_iterator itr = factory_map.begin(); itr != factory_map.end(); ++itr) {
294  AbstractMetaObjectBase * factory = itr->second;
295  if (factory->isOwnedBy(loader)) {
296  classes.push_back(itr->first);
297  } else if (factory->isOwnedBy(NULL)) {
298  classes_with_no_owner.push_back(itr->first);
299  }
300  }
301 
302  // Added classes not associated with a class loader (Which can happen through
303  // an unexpected dlopen() to the library)
304  classes.insert(classes.end(), classes_with_no_owner.begin(), classes_with_no_owner.end());
305  return classes;
306 }
307 
313 std::vector<std::string> getAllLibrariesUsedByClassLoader(const ClassLoader * loader);
314 
321 bool isLibraryLoaded(const std::string & library_path, ClassLoader * loader);
322 
328 bool isLibraryLoadedByAnybody(const std::string & library_path);
329 
335 void loadLibrary(const std::string & library_path, ClassLoader * loader);
336 
342 void unloadLibrary(const std::string & library_path, ClassLoader * loader);
343 
344 
345 } // namespace class_loader_private
346 } // namespace class_loader
347 
348 #endif // CLASS_LOADER__CLASS_LOADER_CORE_HPP_
#define CONSOLE_BRIDGE_logWarn(fmt,...)
std::vector< std::string > getAllLibrariesUsedByClassLoader(const ClassLoader *loader)
This function returns the names of all libraries in use by a given class loader.
bool hasANonPurePluginLibraryBeenOpened()
Indicates if a library containing more than just plugins has been opened by the running process...
Definition: base.hpp:33
boost::recursive_mutex & getPluginBaseToFactoryMapMapMutex()
The actual factory. C The derived class (the actual plugin) B The base class interface for the plug...
std::map< BaseClassName, FactoryMap > BaseToFactoryMapMap
boost::recursive_mutex & getLoadedLibraryVectorMutex()
To provide thread safety, all exposed plugin functions can only be run serially by multiple threads...
ClassLoader * getCurrentlyActiveClassLoader()
Gets the ClassLoader currently in scope which used when a library is being loaded.
BaseToFactoryMapMap & getGlobalPluginBaseToFactoryMapMap()
Gets a handle to a global data structure that holds a map of base class names (Base class describes p...
std::string getCurrentlyLoadingLibraryName()
When a library is being loaded, in order for factories to know which library they are being associate...
A base class for MetaObjects that excludes a polymorphic type parameter. Subclasses are class templat...
Definition: meta_object.hpp:59
Base * createInstance(const std::string &derived_class_name, ClassLoader *loader)
This function creates an instance of a plugin class given the derived name of the class and returns a...
void loadLibrary(const std::string &library_path, ClassLoader *loader)
Loads a library into memory if it has not already been done so. Attempting to load an already loaded ...
#define CONSOLE_BRIDGE_logDebug(fmt,...)
void setCurrentlyLoadingLibraryName(const std::string &library_name)
When a library is being loaded, in order for factories to know which library they are being associate...
An exception class thrown when class_loader is unable to create a plugin.
Definition: exceptions.hpp:80
This class allows loading and unloading of dynamically linked libraries which contain class definitio...
void unloadLibrary(const std::string &library_path, ClassLoader *loader)
Unloads a library if it loaded in memory and cleans up its corresponding class factories. If it is not loaded, the function has no effect.
std::vector< AbstractMetaObjectBase * > MetaObjectVector
virtual B * create() const =0
Defines the factory interface that the MetaObject must implement.
LibraryVector & getLoadedLibraryVector()
Gets a handle to a list of open libraries in the form of LibraryPairs which encode the library path+n...
std::vector< std::string > getAvailableClasses(ClassLoader *loader)
This function returns all the available class_loader in the plugin system that are derived from Base ...
std::vector< LibraryPair > LibraryVector
void setCurrentlyActiveClassLoader(ClassLoader *loader)
Sets the ClassLoader currently in scope which used when a library is being loaded.
void addOwningClassLoader(ClassLoader *loader)
Associates a ClassLoader owner with this factory,.
Definition: meta_object.cpp:93
void registerPlugin(const std::string &class_name, const std::string &base_class_name)
This function is called by the CLASS_LOADER_REGISTER_CLASS macro in plugin_register_macro.h to register factories. Classes that use that macro will cause this function to be invoked when the library is loaded. The function will create a MetaObject (i.e. factory) for the corresponding Derived class and insert it into the appropriate FactoryMap in the global Base-to-FactoryMap map. Note that the passed class_name is the literal class name and not the mangled version.
bool isLibraryLoaded(const std::string &library_path, ClassLoader *loader)
Indicates if passed library loaded within scope of a ClassLoader. The library maybe loaded in memory...
bool isOwnedBy(const ClassLoader *loader)
Indicates if the factory is within the usable scope of a ClassLoader.
FactoryMap & getFactoryMapForBaseClass(const std::string &typeid_base_class_name)
This function extracts a reference to the FactoryMap for appropriate base class out of the global plu...
std::pair< LibraryPath, Poco::SharedLibrary * > LibraryPair
#define CONSOLE_BRIDGE_logError(fmt,...)
bool isLibraryLoadedByAnybody(const std::string &library_path)
Indicates if passed library has been loaded by ANY ClassLoader.
void setAssociatedLibraryPath(std::string library_path)
Sets the path to the library associated with this factory.
Definition: meta_object.cpp:87
std::map< ClassName, class_loader_private::AbstractMetaObjectBase * > FactoryMap
Abstract base class for factories where polymorphic type variable indicates base class for plugin int...


class_loader
Author(s): Mirza Shah
autogenerated on Wed Jun 5 2019 22:08:15