CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
RootAutoLibraryLoader.cc
Go to the documentation of this file.
1 // -*- C++ -*-
2 //
3 // Package: LibraryLoader
4 // Class : RootAutoLibraryLoader
5 //
6 // Implementation:
7 // <Notes on implementation>
8 //
9 // Original Author:
10 // Created: Wed Nov 30 14:55:01 EST 2005
11 //
12 
13 // system include files
14 #include <string>
15 #include <iostream>
16 #include <map>
17 #include "TROOT.h"
18 #include "G__ci.h"
19 #include "boost/regex.hpp"
20 
21 // user include files
24 
29 
30 #include "Reflex/Type.h"
31 #include "Cintex/Cintex.h"
32 #include "TClass.h"
33 
34 // We cannot use the MessageLogger here because this is also used by standalones that do not have the logger.
35 
36 //
37 // constants, enums and typedefs
38 //
39 namespace {
40  //Based on http://root.cern.ch/lxr/source/cintex/src/CINTSourceFile.h
41  // If a Cint dictionary is accidently loaded as a side effect of loading a CMS
42  // library Cint must have a file name assigned to that dictionary else Cint may crash
43  class RootLoadFileSentry {
44  public:
45  RootLoadFileSentry() {
46  G__setfilecontext("{CMS auto library loader}", &oldIFile_);
47  }
48 
49  ~RootLoadFileSentry() {
50  G__input_file* ifile = G__get_ifile();
51  if (ifile) {
52  *ifile = oldIFile_;
53  }
54  }
55 
56  private:
57  G__input_file oldIFile_;
58  };
59 }
60 
61 //
62 // static data member definitions
63 //
64 //hold onto the previous autolibrary loader
65 typedef int (*CallbackPtr)(char*, char*);
67 static char const* kDummyLibName = "*dummy";
68 
69 //This is actually defined within ROOT's v6_struct.cxx file but is not declared static
70 // I want to use it so that if the autoloading is already turned on, I can call the previously declared routine
72 
73 namespace edm {
74  namespace {
75 
76  std::map<std::string, std::string>&
77  cintToReflexSpecialCasesMap() {
78  static std::map<std::string, std::string> s_map;
79  return s_map;
80  }
81 
82  void
83  addWrapperOfVectorOfBuiltin(std::map<std::string, std::string>& iMap, char const* iBuiltin) {
84  static std::string sReflexPrefix("edm::Wrapper<std::vector<");
85  static std::string sReflexPostfix("> >");
86 
87  //Wrapper<vector<float, allocator<float> > >
88  static std::string sCintPrefix("Wrapper<vector<");
89  static std::string sCintMiddle(",allocator<");
90  static std::string sCintPostfix("> > >");
91 
92  std::string type(iBuiltin);
93  iMap.insert(make_pair(sCintPrefix + type + sCintMiddle + type + sCintPostfix,
94  sReflexPrefix + type + sReflexPostfix));
95  }
96 
97  bool loadLibraryForClass(char const* classname) {
98  //std::cout << "loadLibaryForClass" << std::endl;
99  if(0 == classname) {
100  return false;
101  }
102  //std::cout << "asking to find " << classname << std::endl;
103  static std::string const cPrefix("LCGReflex/");
104  //std::cout << "asking to find " << cPrefix + classname << std::endl;
105  try {
106  //give ROOT a name for the file we are loading
107  RootLoadFileSentry sentry;
108  if(edmplugin::PluginCapabilities::get()->tryToLoad(cPrefix + classname)) {
109  Reflex::Type t = Reflex::Type::ByName(classname);
110  if (Reflex::Type() == t) {
111  //would be nice to issue a warning here
112  return false;
113  }
114  if(!t.IsComplete()) {
115  //would be nice to issue a warning here. Not sure the remainder of this comment is correct.
116  // this message happens too often (too many false positives) to be useful plus ROOT will complain about a missing dictionary
117  //std::cerr << "Warning: Reflex knows about type '" << classname << "' but has no dictionary for it." << std::endl;
118  return false;
119  }
120  } else {
121  //see if adding a std namespace helps
122  std::string name = root::stdNamespaceAdder(classname);
123  //std::cout << "see if std helps" << std::endl;
124  if (not edmplugin::PluginCapabilities::get()->tryToLoad(cPrefix + name)) {
125  // Too many false positives on built-in types here.
126  return false;
127  }
128  Reflex::Type t = Reflex::Type::ByName(name);
129  if (Reflex::Type() == t) {
130  t = Reflex::Type::ByName(classname);
131  if (Reflex::Type() == t) {
132  //would be nice to issue a warning here
133  return false;
134  }
135  }
136  }
137  } catch(cms::Exception& e) {
138  //would be nice to issue a warning here
139  return false;
140  }
141  //std::cout << "loaded " << classname << std::endl;
142  return true;
143  }
144 
145  //Based on code in ROOT's TCint.cxx file
146 
147  int ALL_AutoLoadCallback(char* c, char* l) {
148  //NOTE: if the library (i.e. 'l') is an empty string this means we are dealing with a namespace
149  // These checks appear to avoid a crash of ROOT during shutdown of the application
150  if(0 == c || 0 == l || l[0] == 0) {
151  return 0;
152  }
153  ULong_t varp = G__getgvp();
154  G__setgvp((long)G__PVOID);
155  int result = loadLibraryForClass(c) ? 1:0;
156  G__setgvp(varp);
157  //NOTE: the check for the library is done since we can have a failure
158  // if a CMS library has an incomplete set of Reflex dictionaries where
159  // the remaining dictionaries can be found by Cint. If the library with
160  // the Reflex dictionaries is loaded first, then the Cint library then any
161  // requests for a Reflex::Type from the Reflex library will fail because for
162  // some reason the loading of the Cint library causes Reflex to forget about
163  // what types it already loaded from the Reflex library. This problem was
164  // seen for libDataFormatsMath and libMathCore. I do not print an error message
165  // since the dictionaries are actually loaded so things work fine.
166  if(!result && 0 != strcmp(l, kDummyLibName) && gPrevious) {
167  result = gPrevious(c, l);
168  }
169  return result;
170  }
171 
172  std::string
173  classNameForRoot(std::string const& iCapName) {
174  //need to remove any 'std::' since ROOT ignores it
175  static boost::regex const ex("std::");
176  std::string const to("");
177 
178  return regex_replace(iCapName, ex, to, boost::match_default | boost::format_sed);
179  }
180 
181  //Cint requires that we register the type and library containing the type
182  // before the autoloading will work
183  struct CompareFirst {
184  bool operator()(std::pair<std::string, std::string> const& iLHS,
185  std::pair<std::string, std::string> const& iRHS) const{
186  return iLHS.first > iRHS.first;
187  }
188  };
189 
190  void registerTypes() {
192 
194 
195  CatToInfos::const_iterator itFound = db->categoryToInfos().find("Capability");
196 
197  if(itFound == db->categoryToInfos().end()) {
198  return;
199  }
200 
201  //in order to determine if a name is from a class or a namespace, we will order
202  // all the classes in descending order so that embedded classes will be seen before
203  // their containing classes, that way we can say the containing class is a namespace
204  // before finding out it is actually a class
205  typedef std::vector<std::pair<std::string, std::string> > ClassAndLibraries;
206  ClassAndLibraries classes;
207  classes.reserve(1000);
208  std::string lastClass;
209 
210  //find where special cases come from
211  std::map<std::string, std::string> specialsToLib;
212  std::map<std::string, std::string> const& specials = cintToReflexSpecialCasesMap();
213  for(std::map<std::string, std::string>::const_iterator itSpecial = specials.begin();
214  itSpecial != specials.end();
215  ++itSpecial) {
216  specialsToLib[classNameForRoot(itSpecial->second)];
217  }
218  static std::string const cPrefix("LCGReflex/");
219  for (edmplugin::PluginManager::Infos::const_iterator itInfo = itFound->second.begin(),
220  itInfoEnd = itFound->second.end();
221  itInfo != itInfoEnd; ++itInfo) {
222  if (lastClass == itInfo->name_) {
223  continue;
224  }
225  lastClass = itInfo->name_;
226  if(cPrefix == lastClass.substr(0, cPrefix.size())) {
227  std::string className = classNameForRoot(lastClass.c_str() + cPrefix.size());
228  classes.push_back(std::pair<std::string, std::string>(className, itInfo->loadable_.string()));
229  std::map<std::string, std::string>::iterator itFound = specialsToLib.find(className);
230  if(itFound != specialsToLib.end()) {
231  // std::cout << "Found " << lastClass << " : " << className << std::endl;
232  itFound->second = itInfo->loadable_.string();
233  }
234  }
235  }
236  //sort_all(classes, std::greater<std::string>());
237  //sort_all(classes, CompareFirst());
238  //the values are already sorted by less, so just need to reverse to get greater
239  for(ClassAndLibraries::reverse_iterator itClass = classes.rbegin(), itClassEnd = classes.rend();
240  itClass != itClassEnd;
241  ++itClass) {
242 
243  std::string const& className = itClass->first;
244  std::string const& libraryName = itClass->second;
245  //need to register namespaces and figure out if we have an embedded class
246  static std::string const toFind(":<");
248  while(std::string::npos != (pos = className.find_first_of(toFind, pos))) {
249  if (className[pos] == '<') {break;}
250  if (className.size() <= pos + 1 || className[pos + 1] != ':') {break;}
251  //should check to see if this is a class or not
252  G__set_class_autoloading_table(const_cast<char*>(className.substr(0, pos).c_str()), const_cast<char*>(""));
253  //std::cout << "namespace " << className.substr(0, pos).c_str() << std::endl;
254  pos += 2;
255  }
256  G__set_class_autoloading_table(const_cast<char*>(className.c_str()), const_cast<char*>(libraryName.c_str()));
257  //std::cout << "class " << className.c_str() << std::endl;
258  }
259 
260  //now handle the special cases
261  for(std::map<std::string, std::string>::const_iterator itSpecial = specials.begin();
262  itSpecial != specials.end();
263  ++itSpecial) {
264  //std::cout << "registering special " << itSpecial->first << " " << itSpecial->second << " " << std::endl << " " << specialsToLib[classNameForRoot(itSpecial->second)] << std::endl;
265  //force loading of specials
266  if(specialsToLib[classNameForRoot(itSpecial->second)].size()) {
267  //std::cout << "&&&&& found special case " << itSpecial->first << std::endl;
268  std::string name = itSpecial->second;
269  Reflex::Type t = Reflex::Type::ByName(name);
270 
271  if((Reflex::Type() == t) and
272  (not edmplugin::PluginCapabilities::get()->tryToLoad(cPrefix + name))) {
273  std::cout << "failed to load plugin for " << cPrefix + name << std::endl;
274  continue;
275  } else {
276  //need to construct the Class ourselves
277  Reflex::Type t = Reflex::Type::ByName(name);
278  if(Reflex::Type() == t) {
279  std::cout << "reflex did not build " << name << std::endl;
280  continue;
281  }
282  TClass* reflexNamedClass = TClass::GetClass(t.TypeInfo());
283  if(0 == reflexNamedClass) {
284  std::cout << "failed to get TClass by typeid for " << name << std::endl;
285  continue;
286  }
287  reflexNamedClass->Clone(itSpecial->first.c_str());
288  std::string magictypedef("namespace edm { typedef ");
289  magictypedef += classNameForRoot(name) + " " + itSpecial->first + "; }";
290  // std::cout << "Magic typedef " << magictypedef << std::endl;
291  gROOT->ProcessLine(magictypedef.c_str());
292  }
293  }
294  }
295  }
296  }
297 
298  //
299  // constructors and destructor
300  //
302 #if ROOT_VERSION_CODE >= ROOT_VERSION(5,27,6)
303  classNameAttemptingToLoad_(0),
304  isInitializingCintex_(true) {
305 #else
307 #endif
309  gROOT->AddClassGenerator(this);
310  ROOT::Cintex::Cintex::Enable();
311 #if ROOT_VERSION_CODE >= ROOT_VERSION(5,27,6)
312  isInitializingCintex_ =false;
313 #endif
314  //set the special cases
315  std::map<std::string, std::string>& specials = cintToReflexSpecialCasesMap();
316  if(specials.empty()) {
317  addWrapperOfVectorOfBuiltin(specials,"bool");
318 
319  addWrapperOfVectorOfBuiltin(specials,"char");
320  addWrapperOfVectorOfBuiltin(specials,"unsigned char");
321  addWrapperOfVectorOfBuiltin(specials,"signed char");
322  addWrapperOfVectorOfBuiltin(specials,"short");
323  addWrapperOfVectorOfBuiltin(specials,"unsigned short");
324  addWrapperOfVectorOfBuiltin(specials,"int");
325  addWrapperOfVectorOfBuiltin(specials,"unsigned int");
326  addWrapperOfVectorOfBuiltin(specials,"long");
327  addWrapperOfVectorOfBuiltin(specials,"unsigned long");
328  addWrapperOfVectorOfBuiltin(specials,"long long");
329  addWrapperOfVectorOfBuiltin(specials,"unsigned long long");
330 
331  addWrapperOfVectorOfBuiltin(specials,"float");
332  addWrapperOfVectorOfBuiltin(specials,"double");
333  }
334  //std::cout << "my loader" << std::endl;
335  //remember if the callback was already set so we can chain together our results
336  gPrevious = G__p_class_autoloading;
337  G__set_class_autoloading_callback(&ALL_AutoLoadCallback);
338  registerTypes();
339  }
340 
341  //
342  // member functions
343  //
344 
345  TClass*
346  RootAutoLibraryLoader::GetClass(char const* classname, Bool_t load) {
347  TClass* returnValue = 0;
348  if(classNameAttemptingToLoad_ != 0 && !strcmp(classname, classNameAttemptingToLoad_)) {
349  // We can try to see if the class name contains "basic_string<char>".
350  // If so, we replace "basic_string<char>" with "string" and try again.
351  std::string className(classname);
352  std::string::size_type idx = className.find("basic_string<char>");
353  if (idx != std::string::npos) {
354  className.replace(idx, 18, std::string("string"));
355  //if basic_string<char> was the last argument to a templated class
356  // then there would be an extra space to separate the two '>'
357  if(className.size() > idx + 6 && className[idx + 6] == ' ') {
358  className.replace(idx + 6, 1, "");
359  }
360  classNameAttemptingToLoad_ = className.c_str();
361  returnValue = gROOT->GetClass(className.c_str(), kTRUE);
362  classNameAttemptingToLoad_ = classname;
363  return returnValue;
364  }
365  //NOTE: As of ROOT 5.27.06 this warning generates false positives for HepMC classes because
366  // ROOT has special handling for them built into class.rules
367  //std::cerr << "WARNING[RootAutoLibraryLoader]: Reflex failed to create CINT dictionary for " << classname << std::endl;
368  return 0;
369  }
370  //std::cout << "looking for " << classname << " load " << (load? "T":"F") << std::endl;
371  if (load) {
372  //std::cout << " going to call loadLibraryForClass" << std::endl;
373  //[ROOT 5.28] When Cintex is in its 'Enable' method it will register callbacks to build
374  // TClasses. During this phase we do not want to actually force TClasses to have to
375  // come into existence.
376 #if ROOT_VERSION_CODE >= ROOT_VERSION(5,27,6)
377  if (not isInitializingCintex_ and loadLibraryForClass(classname)) {
378 #else
379  if (loadLibraryForClass(classname)) {
380 #endif
381  //use this to check for infinite recursion attempt
382  classNameAttemptingToLoad_ = classname;
383  // This next call will create the TClass object for the class.
384  // It will also attempt to load the dictionary for the class
385  // if the second argument is kTRUE. This is the default, so it
386  // need not be explicitly specified.
387  returnValue = gROOT->GetClass(classname, kTRUE);
389  }
390  }
391  return returnValue;
392  }
393 
394  TClass*
395  RootAutoLibraryLoader::GetClass(type_info const& typeinfo, Bool_t load) {
396  //std::cout << "looking for type " << typeinfo.name() << std::endl;
397  TClass* returnValue = 0;
398  if(load) {
399  return GetClass(typeinfo.name(), load);
400  }
401  return returnValue;
402  }
403 
404  void
406  //static BareRootProductGetter s_getter;
407  //static EDProductGetter::Operate s_op(&s_getter);
408  static RootAutoLibraryLoader s_loader;
409  }
410 
411  void
413  // std::cout << "LoadAllDictionaries" << std::endl;
414  enable();
415 
417 
419 
420  CatToInfos::const_iterator itFound = db->categoryToInfos().find("Capability");
421 
422  if(itFound == db->categoryToInfos().end()) {
423  return;
424  }
425  std::string lastClass;
426  std::string const cPrefix("LCGReflex/");
427 
428  //give ROOT a name for the file we are loading
429  RootLoadFileSentry sentry;
430 
431  for (edmplugin::PluginManager::Infos::const_iterator itInfo = itFound->second.begin(),
432  itInfoEnd = itFound->second.end();
433  itInfo != itInfoEnd; ++itInfo) {
434  if (lastClass == itInfo->name_) {
435  continue;
436  }
437 
438  lastClass = itInfo->name_;
440  //NOTE: since we have the library already, we could be more efficient if we just load it ourselves
441  }
442  }
443 }
444 
445 //ClassImp(RootAutoLibraryLoader)
const CategoryToInfos & categoryToInfos() const
Definition: PluginManager.h:71
type
Definition: HCALResponse.h:22
virtual TClass * GetClass(char const *classname, Bool_t load)
return class type
tuple db
Definition: EcalCondDB.py:151
uint16_t size_type
int(* CallbackPtr)(char *, char *)
std::string stdNamespaceAdder(const std::string &iClassName)
tuple result
Definition: query.py:137
def load
Definition: svgfig.py:546
std::map< std::string, Infos > CategoryToInfos
Definition: PluginManager.h:43
static PluginCapabilities * get()
CallbackPtr G__p_class_autoloading
The Signals That Services Can Subscribe To This is based on ActivityRegistry h
Helper function to determine trigger accepts.
Definition: Activities.doc:4
static void loadAll()
load all known libraries holding dictionaries
static CallbackPtr gPrevious
perl if(1 lt scalar(@::datatypes))
Definition: edlooper.cc:31
tuple cout
Definition: gather_cfg.py:121
void load(const std::string &iName)
static void enable()
interface for TClass generators
static PluginManager * get()
static char const * kDummyLibName
std::string className(const T &t)
Definition: ClassName.h:30