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 "TInterpreter.h"
19 #include "G__ci.h"
20 
21 // user include files
24 
30 
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*);
66 static CallbackPtr gPrevious = nullptr;
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 ROOT {
74  namespace Cintex {
76  }
77 }
78 
79 namespace edm {
80  namespace {
81 
82  std::map<std::string, std::string>&
83  cintToReflexSpecialCasesMap() {
84  static std::map<std::string, std::string> s_map;
85  return s_map;
86  }
87 
88  void
89  addWrapperOfVectorOfBuiltin(std::map<std::string, std::string>& iMap, char const* iBuiltin) {
90  static std::string const sReflexPrefix("edm::Wrapper<std::vector<");
91  static std::string const sReflexPostfix("> >");
92 
93  //Wrapper<vector<float, allocator<float> > >
94  static std::string const sCintPrefix("Wrapper<vector<");
95  static std::string const sCintMiddle(",allocator<");
96  static std::string const sCintPostfix("> > >");
97 
98  std::string type(iBuiltin);
99  iMap.insert(make_pair(sCintPrefix + type + sCintMiddle + type + sCintPostfix,
100  sReflexPrefix + type + sReflexPostfix));
101  }
102 
104  classNameForRoot(std::string const& classname) {
105  // Converts the name to the name known by CINT (e.g. strips out "std::")
106  return ROOT::Cintex::CintName(classname);
107  }
108 
109  bool
110  isDictionaryLoaded(std::string const& rootclassname) {
111  // This checks if the class name is known to the interpreter.
112  // In this context, this will be true if and only if the dictionary has been loaded (and converted to CINT).
113  // This code is independent of the identity of the interpreter.
114  ClassInfo_t* info = gInterpreter->ClassInfo_Factory(rootclassname.c_str());
115  return gInterpreter->ClassInfo_IsValid(info);
116  }
117 
118  bool loadLibraryForClass(char const* classname) {
119  //std::cout << "loadLibaryForClass" << std::endl;
120  if(nullptr == classname) {
121  return false;
122  }
123  //std::cout << "asking to find " << classname << std::endl;
124  std::string const& cPrefix = dictionaryPlugInPrefix();
125  //std::cout << "asking to find " << cPrefix + classname << std::endl;
126  std::string rootclassname = classNameForRoot(classname);
127  try {
128  //give ROOT a name for the file we are loading
129  RootLoadFileSentry sentry;
130  if(edmplugin::PluginCapabilities::get()->tryToLoad(cPrefix + classname)) {
131  if(!isDictionaryLoaded(rootclassname)) {
132  //would be nice to issue a warning here. Not sure the remainder of this comment is correct.
133  // this message happens too often (too many false positives) to be useful plus ROOT will complain about a missing dictionary
134  //std::cerr << "Warning: ROOT knows about type '" << classname << "' but has no dictionary for it." << std::endl;
135  return false;
136  }
137  } else {
138  //see if adding a std namespace helps
140  //std::cout << "see if std helps" << std::endl;
141  if (not edmplugin::PluginCapabilities::get()->tryToLoad(cPrefix + name)) {
142  // Too many false positives on built-in types here.
143  return false;
144  }
145  if(!isDictionaryLoaded(rootclassname)) {
146  //would be nice to issue a warning here
147  return false;
148  }
149  }
150  } catch(cms::Exception& e) {
151  //would be nice to issue a warning here
152  return false;
153  }
154  //std::cout << "loaded " << classname << std::endl;
155  return true;
156  }
157 
158  //Based on code in ROOT's TCint.cxx file
159 
160  int ALL_AutoLoadCallback(char* c, char* l) {
161  //NOTE: if the library (i.e. 'l') is an empty string this means we are dealing with a namespace
162  // These checks appear to avoid a crash of ROOT during shutdown of the application
163  if(nullptr == c || nullptr == l || l[0] == 0) {
164  return 0;
165  }
166  ULong_t varp = G__getgvp();
167  G__setgvp((long)G__PVOID);
168  int result = loadLibraryForClass(c) ? 1:0;
169  G__setgvp(varp);
170  //NOTE: the check for the library is done since we can have a failure
171  // if a CMS library has an incomplete set of reflex dictionaries where
172  // the remaining dictionaries can be found by Cint. If the library with
173  // the reflex dictionaries is loaded first, then the Cint library then any
174  // requests for a Type from the reflex library will fail because for
175  // some reason the loading of the Cint library causes reflex to forget about
176  // what types it already loaded from the reflex library. This problem was
177  // seen for libDataFormatsMath and libMathCore. I do not print an error message
178  // since the dictionaries are actually loaded so things work fine.
179  if(!result && 0 != strcmp(l, kDummyLibName) && gPrevious) {
180  result = gPrevious(c, l);
181  }
182  return result;
183  }
184 
185  //Cint requires that we register the type and library containing the type
186  // before the autoloading will work
187  struct CompareFirst {
188  bool operator()(std::pair<std::string, std::string> const& iLHS,
189  std::pair<std::string, std::string> const& iRHS) const{
190  return iLHS.first > iRHS.first;
191  }
192  };
193 
194  void registerTypes() {
196 
198 
199  CatToInfos::const_iterator itFound = db->categoryToInfos().find("Capability");
200 
201  if(itFound == db->categoryToInfos().end()) {
202  return;
203  }
204 
205  //in order to determine if a name is from a class or a namespace, we will order
206  // all the classes in descending order so that embedded classes will be seen before
207  // their containing classes, that way we can say the containing class is a namespace
208  // before finding out it is actually a class
209  typedef std::vector<std::pair<std::string, std::string> > ClassAndLibraries;
210  ClassAndLibraries classes;
211  classes.reserve(1000);
212  std::string lastClass;
213 
214  //find where special cases come from
215  std::map<std::string, std::string> specialsToLib;
216  std::map<std::string, std::string> const& specials = cintToReflexSpecialCasesMap();
217  for(auto const& special : specials) {
218  specialsToLib[classNameForRoot(special.second)];
219  }
220  std::string const& cPrefix = dictionaryPlugInPrefix();
221  for(auto const& info : itFound->second) {
222  if (lastClass == info.name_) {
223  continue;
224  }
225  lastClass = info.name_;
226  if(cPrefix == lastClass.substr(0, cPrefix.size())) {
227  std::string className = classNameForRoot(lastClass.c_str() + cPrefix.size());
228  classes.emplace_back(className, info.loadable_.string());
229  std::map<std::string, std::string>::iterator iFound = specialsToLib.find(className);
230  if(iFound != specialsToLib.end()) {
231  // std::cout << "Found " << lastClass << " : " << className << std::endl;
232  iFound->second = info.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(":<");
247  std::string::size_type pos = 0;
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(auto const& special : specials) {
262  std::string const& name = special.second;
263  std::string rootname = classNameForRoot(name);
264  //std::cout << "registering special " << itSpecial->first << " " << name << " " << std::endl << " " << specialsToLib[rootname] << std::endl;
265  //force loading of specials
266  if(specialsToLib[rootname].size()) {
267  //std::cout << "&&&&& found special case " << itSpecial->first << std::endl;
268  if(!isDictionaryLoaded(rootname) and
269  (not edmplugin::PluginCapabilities::get()->tryToLoad(cPrefix + name))) {
270  std::cout << "failed to load plugin for " << cPrefix + name << std::endl;
271  continue;
272  } else {
273  //need to construct the Class ourselves
274  if(!isDictionaryLoaded(rootname)) {
275  std::cout << "dictionary did not build " << name << std::endl;
276  continue;
277  }
278  TClass* namedClass = TClass::GetClass(rootname.c_str());
279  if(nullptr == namedClass) {
280  std::cout << "failed to get TClass for " << name << std::endl;
281  continue;
282  }
283  namedClass->Clone(special.first.c_str());
284  std::string magictypedef("namespace edm { typedef ");
285  magictypedef += rootname + " " + special.first + "; }";
286  // std::cout << "Magic typedef " << magictypedef << std::endl;
287  gROOT->ProcessLine(magictypedef.c_str());
288  }
289  }
290  }
291  }
292  }
293 
294  //
295  // constructors and destructor
296  //
298 #if ROOT_VERSION_CODE >= ROOT_VERSION(5,27,6)
299  classNameAttemptingToLoad_(nullptr),
300  isInitializingCintex_(true) {
301 #else
302  classNameAttemptingToLoad_(nullptr) {
303 #endif
305  gROOT->AddClassGenerator(this);
306  ROOT::Cintex::Cintex::Enable();
307 #if ROOT_VERSION_CODE >= ROOT_VERSION(5,27,6)
308  isInitializingCintex_ =false;
309 #endif
310  //set the special cases
311  std::map<std::string, std::string>& specials = cintToReflexSpecialCasesMap();
312  if(specials.empty()) {
313  addWrapperOfVectorOfBuiltin(specials,"bool");
314 
315  addWrapperOfVectorOfBuiltin(specials,"char");
316  addWrapperOfVectorOfBuiltin(specials,"unsigned char");
317  addWrapperOfVectorOfBuiltin(specials,"signed char");
318  addWrapperOfVectorOfBuiltin(specials,"short");
319  addWrapperOfVectorOfBuiltin(specials,"unsigned short");
320  addWrapperOfVectorOfBuiltin(specials,"int");
321  addWrapperOfVectorOfBuiltin(specials,"unsigned int");
322  addWrapperOfVectorOfBuiltin(specials,"long");
323  addWrapperOfVectorOfBuiltin(specials,"unsigned long");
324  addWrapperOfVectorOfBuiltin(specials,"long long");
325  addWrapperOfVectorOfBuiltin(specials,"unsigned long long");
326 
327  addWrapperOfVectorOfBuiltin(specials,"float");
328  addWrapperOfVectorOfBuiltin(specials,"double");
329  }
330  //std::cout << "my loader" << std::endl;
331  //remember if the callback was already set so we can chain together our results
332  gPrevious = G__p_class_autoloading;
333  G__set_class_autoloading_callback(&ALL_AutoLoadCallback);
334  registerTypes();
335  }
336 
337  //
338  // member functions
339  //
340 
341  TClass*
342  RootAutoLibraryLoader::GetClass(char const* classname, Bool_t load) {
343  TClass* returnValue = nullptr;
344  if(classNameAttemptingToLoad_ != nullptr && !strcmp(classname, classNameAttemptingToLoad_)) {
345  // We can try to see if the class name contains "basic_string<char>".
346  // If so, we replace "basic_string<char>" with "string" and try again.
347  std::string className(classname);
348  std::string::size_type idx = className.find("basic_string<char>");
349  if (idx != std::string::npos) {
350  className.replace(idx, 18, std::string("string"));
351  //if basic_string<char> was the last argument to a templated class
352  // then there would be an extra space to separate the two '>'
353  if(className.size() > idx + 6 && className[idx + 6] == ' ') {
354  className.replace(idx + 6, 1, "");
355  }
356  classNameAttemptingToLoad_ = className.c_str();
357  returnValue = gROOT->GetClass(className.c_str(), kTRUE);
358  classNameAttemptingToLoad_ = classname;
359  return returnValue;
360  }
361  //NOTE: As of ROOT 5.27.06 this warning generates false positives for HepMC classes because
362  // ROOT has special handling for them built into class.rules
363  //std::cerr << "WARNING[RootAutoLibraryLoader]: ROOT failed to create CINT dictionary for " << classname << std::endl;
364  return nullptr;
365  }
366  //std::cout << "looking for " << classname << " load " << (load? "T":"F") << std::endl;
367  if (load) {
368  //std::cout << " going to call loadLibraryForClass" << std::endl;
369  //[ROOT 5.28] When Cintex is in its 'Enable' method it will register callbacks to build
370  // TClasses. During this phase we do not want to actually force TClasses to have to
371  // come into existence.
372 #if ROOT_VERSION_CODE >= ROOT_VERSION(5,27,6)
373  if (not isInitializingCintex_ and loadLibraryForClass(classname)) {
374 #else
375  if (loadLibraryForClass(classname)) {
376 #endif
377  //use this to check for infinite recursion attempt
378  classNameAttemptingToLoad_ = classname;
379  // This next call will create the TClass object for the class.
380  // It will also attempt to load the dictionary for the class
381  // if the second argument is kTRUE. This is the default, so it
382  // need not be explicitly specified.
383  returnValue = gROOT->GetClass(classname, kTRUE);
384  classNameAttemptingToLoad_ = nullptr;
385  }
386  }
387  return returnValue;
388  }
389 
390  TClass*
391  RootAutoLibraryLoader::GetClass(type_info const& typeinfo, Bool_t load) {
392  //std::cout << "looking for type " << typeinfo.name() << std::endl;
393  TClass* returnValue = nullptr;
394  if(load) {
395  return GetClass(typeinfo.name(), load);
396  }
397  return returnValue;
398  }
399 
400  void
402  //static BareRootProductGetter s_getter;
403  //static EDProductGetter::Operate s_op(&s_getter);
404  static RootAutoLibraryLoader s_loader;
405  }
406 
407  void
409  // std::cout << "LoadAllDictionaries" << std::endl;
410  enable();
411 
413 
415 
416  CatToInfos::const_iterator itFound = db->categoryToInfos().find("Capability");
417 
418  if(itFound == db->categoryToInfos().end()) {
419  return;
420  }
421  std::string lastClass;
422 
423  //give ROOT a name for the file we are loading
424  RootLoadFileSentry sentry;
425 
426  for(auto const& info : itFound->second) {
427  if (lastClass == info.name_) {
428  continue;
429  }
430 
431  lastClass = info.name_;
433  //NOTE: since we have the library already, we could be more efficient if we just load it ourselves
434  }
435  }
436 }
437 
438 //ClassImp(RootAutoLibraryLoader)
const CategoryToInfos & categoryToInfos() const
Definition: PluginManager.h:82
type
Definition: HCALResponse.h:21
static const TGPicture * info(bool iBackgroundIsBlack)
virtual TClass * GetClass(char const *classname, Bool_t load)
return class type
#define nullptr
tuple db
Definition: EcalCondDB.py:151
std::string const & dictionaryPlugInPrefix()
uint16_t size_type
std::string CintName(std::string const &)
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:54
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
tuple idx
DEBUGGING if hasattr(process,&quot;trackMonIterativeTracking2012&quot;): print &quot;trackMonIterativeTracking2012 D...
static void loadAll()
load all known libraries holding dictionaries
if(dp >Float(M_PI)) dp-
static CallbackPtr gPrevious
tuple cout
Definition: gather_cfg.py:121
void load(const std::string &iName)
static void enable()
interface for TClass generators
static PluginManager * get()
tuple size
Write out results.
static char const * kDummyLibName
std::string className(const T &t)
Definition: ClassName.h:30