CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_5_3_0/src/FWCore/RootAutoLibraryLoader/src/RootAutoLibraryLoader.cc

Go to the documentation of this file.
00001 // -*- C++ -*-
00002 //
00003 // Package:     LibraryLoader
00004 // Class  :     RootAutoLibraryLoader
00005 //
00006 // Implementation:
00007 //     <Notes on implementation>
00008 //
00009 // Original Author:
00010 //         Created:  Wed Nov 30 14:55:01 EST 2005
00011 //
00012 
00013 // system include files
00014 #include <string>
00015 #include <iostream>
00016 #include <map>
00017 #include "TROOT.h"
00018 #include "G__ci.h"
00019 #include "boost/regex.hpp"
00020 
00021 // user include files
00022 #include "FWCore/RootAutoLibraryLoader/interface/RootAutoLibraryLoader.h"
00023 #include "FWCore/RootAutoLibraryLoader/src/stdNamespaceAdder.h"
00024 
00025 #include "FWCore/PluginManager/interface/PluginManager.h"
00026 #include "FWCore/Utilities/interface/Exception.h"
00027 #include "FWCore/PluginManager/interface/ProblemTracker.h"
00028 #include "FWCore/PluginManager/interface/PluginCapabilities.h"
00029 
00030 #include "Reflex/Type.h"
00031 #include "Cintex/Cintex.h"
00032 #include "TClass.h"
00033 
00034 // We cannot use the MessageLogger here because this is also used by standalones that do not have the logger.
00035 
00036 //
00037 // constants, enums and typedefs
00038 //
00039 namespace {
00040   //Based on https://root.cern.ch/lxr/source/cintex/src/CINTSourceFile.h
00041   // If a Cint dictionary is accidently loaded as a side effect of loading a CMS
00042   // library Cint must have a file name assigned to that dictionary else Cint may crash
00043   class RootLoadFileSentry {
00044   public:
00045     RootLoadFileSentry() {
00046        G__setfilecontext("{CMS auto library loader}", &oldIFile_);
00047     }
00048 
00049     ~RootLoadFileSentry() {
00050       G__input_file* ifile = G__get_ifile();
00051       if (ifile) {
00052         *ifile = oldIFile_;
00053       }
00054     }
00055 
00056   private:
00057       G__input_file oldIFile_;
00058   };
00059 }
00060 
00061 //
00062 // static data member definitions
00063 //
00064 //hold onto the previous autolibrary loader
00065 typedef int (*CallbackPtr)(char*, char*);
00066 static CallbackPtr gPrevious = 0;
00067 static char const* kDummyLibName = "*dummy";
00068 
00069 //This is actually defined within ROOT's v6_struct.cxx file but is not declared static
00070 // I want to use it so that if the autoloading is already turned on, I can call the previously declared routine
00071 extern CallbackPtr G__p_class_autoloading;
00072 
00073 namespace edm {
00074    namespace {
00075 
00076       std::map<std::string, std::string>&
00077       cintToReflexSpecialCasesMap() {
00078          static std::map<std::string, std::string> s_map;
00079          return s_map;
00080       }
00081 
00082       void
00083       addWrapperOfVectorOfBuiltin(std::map<std::string, std::string>& iMap, char const* iBuiltin) {
00084          static std::string sReflexPrefix("edm::Wrapper<std::vector<");
00085          static std::string sReflexPostfix("> >");
00086 
00087          //Wrapper<vector<float, allocator<float> > >
00088          static std::string sCintPrefix("Wrapper<vector<");
00089          static std::string sCintMiddle(",allocator<");
00090          static std::string sCintPostfix("> > >");
00091 
00092          std::string type(iBuiltin);
00093          iMap.insert(make_pair(sCintPrefix + type + sCintMiddle + type + sCintPostfix,
00094                                sReflexPrefix + type + sReflexPostfix));
00095       }
00096 
00097       bool loadLibraryForClass(char const* classname) {
00098         //std::cout << "loadLibaryForClass" << std::endl;
00099         if(0 == classname) {
00100           return false;
00101         }
00102         //std::cout << "asking to find " << classname << std::endl;
00103         static std::string const cPrefix("LCGReflex/");
00104         //std::cout << "asking to find " << cPrefix + classname << std::endl;
00105         try {
00106           //give ROOT a name for the file we are loading
00107           RootLoadFileSentry sentry;
00108           if(edmplugin::PluginCapabilities::get()->tryToLoad(cPrefix + classname)) {
00109             Reflex::Type t = Reflex::Type::ByName(classname);
00110             if (Reflex::Type() == t) {
00111               //would be nice to issue a warning here
00112               return false;
00113             }
00114             if(!t.IsComplete()) {
00115               //would be nice to issue a warning here.  Not sure the remainder of this comment is correct.
00116               // this message happens too often (too many false positives) to be useful plus ROOT will complain about a missing dictionary
00117               //std::cerr << "Warning: Reflex knows about type '" << classname << "' but has no dictionary for it." << std::endl;
00118               return false;
00119             }
00120           } else {
00121             //see if adding a std namespace helps
00122             std::string name = root::stdNamespaceAdder(classname);
00123             //std::cout << "see if std helps" << std::endl;
00124             if (not edmplugin::PluginCapabilities::get()->tryToLoad(cPrefix + name)) {
00125               // Too many false positives on built-in types here.
00126               return false;
00127             }
00128             Reflex::Type t = Reflex::Type::ByName(name);
00129             if (Reflex::Type() == t) {
00130               t = Reflex::Type::ByName(classname);
00131               if (Reflex::Type() == t) {
00132                 //would be nice to issue a warning here
00133                 return false;
00134               }
00135             }
00136           }
00137         } catch(cms::Exception& e) {
00138           //would be nice to issue a warning here
00139           return false;
00140         }
00141         //std::cout << "loaded " << classname << std::endl;
00142         return true;
00143       }
00144 
00145       //Based on code in ROOT's TCint.cxx file
00146 
00147       int ALL_AutoLoadCallback(char* c, char* l) {
00148         //NOTE: if the library (i.e. 'l') is an empty string this means we are dealing with a namespace
00149         // These checks appear to avoid a crash of ROOT during shutdown of the application
00150         if(0 == c || 0 == l || l[0] == 0) {
00151           return 0;
00152         }
00153         ULong_t varp = G__getgvp();
00154         G__setgvp((long)G__PVOID);
00155         int result = loadLibraryForClass(c) ? 1:0;
00156         G__setgvp(varp);
00157         //NOTE: the check for the library is done since we can have a failure
00158         // if a CMS library has an incomplete set of Reflex dictionaries where
00159         // the remaining dictionaries can be found by Cint.  If the library with
00160         // the Reflex dictionaries is loaded first, then the Cint library then any
00161         // requests for a Reflex::Type from the Reflex library will fail because for
00162         // some reason the loading of the Cint library causes Reflex to forget about
00163         // what types it already loaded from the Reflex library.  This problem was
00164         // seen for libDataFormatsMath and libMathCore.  I do not print an error message
00165         // since the dictionaries are actually loaded so things work fine.
00166         if(!result && 0 != strcmp(l, kDummyLibName) && gPrevious) {
00167           result = gPrevious(c, l);
00168         }
00169         return result;
00170       }
00171 
00172       std::string
00173       classNameForRoot(std::string const& iCapName) {
00174         //need to remove any 'std::' since ROOT ignores it
00175         static boost::regex const ex("std::");
00176         std::string const to("");
00177 
00178         return regex_replace(iCapName, ex, to, boost::match_default | boost::format_sed);
00179       }
00180 
00181       //Cint requires that we register the type and library containing the type
00182       // before the autoloading will work
00183         struct CompareFirst {
00184           bool operator()(std::pair<std::string, std::string> const& iLHS,
00185                           std::pair<std::string, std::string> const& iRHS) const{
00186             return iLHS.first > iRHS.first;
00187           }
00188         };
00189 
00190       void registerTypes() {
00191         edmplugin::PluginManager* db =  edmplugin::PluginManager::get();
00192 
00193         typedef edmplugin::PluginManager::CategoryToInfos CatToInfos;
00194 
00195         CatToInfos::const_iterator itFound = db->categoryToInfos().find("Capability");
00196 
00197         if(itFound == db->categoryToInfos().end()) {
00198           return;
00199         }
00200 
00201         //in order to determine if a name is from a class or a namespace, we will order
00202         // all the classes in descending order so that embedded classes will be seen before
00203         // their containing classes, that way we can say the containing class is a namespace
00204         // before finding out it is actually a class
00205         typedef std::vector<std::pair<std::string, std::string> > ClassAndLibraries;
00206         ClassAndLibraries classes;
00207         classes.reserve(1000);
00208         std::string lastClass;
00209 
00210         //find where special cases come from
00211         std::map<std::string, std::string> specialsToLib;
00212         std::map<std::string, std::string> const& specials = cintToReflexSpecialCasesMap();
00213         for(std::map<std::string, std::string>::const_iterator itSpecial = specials.begin();
00214             itSpecial != specials.end();
00215             ++itSpecial) {
00216           specialsToLib[classNameForRoot(itSpecial->second)];
00217         }
00218         static std::string const cPrefix("LCGReflex/");
00219         for (edmplugin::PluginManager::Infos::const_iterator itInfo = itFound->second.begin(),
00220              itInfoEnd = itFound->second.end();
00221              itInfo != itInfoEnd; ++itInfo) {
00222           if (lastClass == itInfo->name_) {
00223             continue;
00224           }
00225           lastClass = itInfo->name_;
00226           if(cPrefix == lastClass.substr(0, cPrefix.size())) {
00227             std::string className = classNameForRoot(lastClass.c_str() + cPrefix.size());
00228             classes.push_back(std::pair<std::string, std::string>(className, itInfo->loadable_.string()));
00229             std::map<std::string, std::string>::iterator itFound = specialsToLib.find(className);
00230             if(itFound != specialsToLib.end()) {
00231               // std::cout << "Found " << lastClass << " : " << className << std::endl;
00232               itFound->second = itInfo->loadable_.string();
00233             }
00234           }
00235         }
00236         //sort_all(classes, std::greater<std::string>());
00237         //sort_all(classes, CompareFirst());
00238         //the values are already sorted by less, so just need to reverse to get greater
00239         for(ClassAndLibraries::reverse_iterator itClass = classes.rbegin(), itClassEnd = classes.rend();
00240             itClass != itClassEnd;
00241             ++itClass) {
00242 
00243           std::string const& className = itClass->first;
00244           std::string const& libraryName = itClass->second;
00245           //need to register namespaces and figure out if we have an embedded class
00246           static std::string const toFind(":<");
00247           std::string::size_type pos = 0;
00248           while(std::string::npos != (pos = className.find_first_of(toFind, pos))) {
00249             if (className[pos] == '<') {break;}
00250             if (className.size() <= pos + 1 || className[pos + 1] != ':') {break;}
00251             //should check to see if this is a class or not
00252             G__set_class_autoloading_table(const_cast<char*>(className.substr(0, pos).c_str()), const_cast<char*>(""));
00253             //std::cout << "namespace " << className.substr(0, pos).c_str() << std::endl;
00254             pos += 2;
00255           }
00256           G__set_class_autoloading_table(const_cast<char*>(className.c_str()), const_cast<char*>(libraryName.c_str()));
00257           //std::cout << "class " << className.c_str() << std::endl;
00258         }
00259 
00260         //now handle the special cases
00261         for(std::map<std::string, std::string>::const_iterator itSpecial = specials.begin();
00262             itSpecial != specials.end();
00263             ++itSpecial) {
00264           //std::cout << "registering special " << itSpecial->first << " " << itSpecial->second << " " << std::endl << "    " << specialsToLib[classNameForRoot(itSpecial->second)] << std::endl;
00265           //force loading of specials
00266           if(specialsToLib[classNameForRoot(itSpecial->second)].size()) {
00267             //std::cout << "&&&&& found special case " << itSpecial->first << std::endl;
00268             std::string name = itSpecial->second;
00269             Reflex::Type t = Reflex::Type::ByName(name);
00270 
00271             if((Reflex::Type() == t) and
00272                 (not edmplugin::PluginCapabilities::get()->tryToLoad(cPrefix + name))) {
00273               std::cout << "failed to load plugin for " << cPrefix + name << std::endl;
00274               continue;
00275             } else {
00276               //need to construct the Class ourselves
00277               Reflex::Type t = Reflex::Type::ByName(name);
00278               if(Reflex::Type() == t) {
00279                 std::cout << "reflex did not build " << name << std::endl;
00280                 continue;
00281               }
00282               TClass* reflexNamedClass = TClass::GetClass(t.TypeInfo());
00283               if(0 == reflexNamedClass) {
00284                 std::cout << "failed to get TClass by typeid for " << name << std::endl;
00285                 continue;
00286               }
00287               reflexNamedClass->Clone(itSpecial->first.c_str());
00288               std::string magictypedef("namespace edm { typedef ");
00289               magictypedef += classNameForRoot(name) + " " + itSpecial->first + "; }";
00290               // std::cout << "Magic typedef " << magictypedef << std::endl;
00291               gROOT->ProcessLine(magictypedef.c_str());
00292             }
00293           }
00294         }
00295       }
00296    }
00297 
00298    //
00299    // constructors and destructor
00300    //
00301    RootAutoLibraryLoader::RootAutoLibraryLoader() :
00302 #if ROOT_VERSION_CODE >= ROOT_VERSION(5,27,6)
00303      classNameAttemptingToLoad_(0),
00304      isInitializingCintex_(true) {
00305 #else
00306      classNameAttemptingToLoad_(0) {
00307 #endif
00308       AssertHandler h;
00309       gROOT->AddClassGenerator(this);
00310       ROOT::Cintex::Cintex::Enable();
00311 #if ROOT_VERSION_CODE >= ROOT_VERSION(5,27,6)
00312       isInitializingCintex_ =false;
00313 #endif
00314       //set the special cases
00315       std::map<std::string, std::string>& specials = cintToReflexSpecialCasesMap();
00316       if(specials.empty()) {
00317          addWrapperOfVectorOfBuiltin(specials,"bool");
00318 
00319          addWrapperOfVectorOfBuiltin(specials,"char");
00320          addWrapperOfVectorOfBuiltin(specials,"unsigned char");
00321          addWrapperOfVectorOfBuiltin(specials,"signed char");
00322          addWrapperOfVectorOfBuiltin(specials,"short");
00323          addWrapperOfVectorOfBuiltin(specials,"unsigned short");
00324          addWrapperOfVectorOfBuiltin(specials,"int");
00325          addWrapperOfVectorOfBuiltin(specials,"unsigned int");
00326          addWrapperOfVectorOfBuiltin(specials,"long");
00327          addWrapperOfVectorOfBuiltin(specials,"unsigned long");
00328          addWrapperOfVectorOfBuiltin(specials,"long long");
00329          addWrapperOfVectorOfBuiltin(specials,"unsigned long long");
00330 
00331          addWrapperOfVectorOfBuiltin(specials,"float");
00332          addWrapperOfVectorOfBuiltin(specials,"double");
00333       }
00334       //std::cout << "my loader" << std::endl;
00335       //remember if the callback was already set so we can chain together our results
00336       gPrevious = G__p_class_autoloading;
00337       G__set_class_autoloading_callback(&ALL_AutoLoadCallback);
00338       registerTypes();
00339    }
00340 
00341    //
00342    // member functions
00343    //
00344 
00345    TClass*
00346    RootAutoLibraryLoader::GetClass(char const* classname, Bool_t load) {
00347       TClass* returnValue = 0;
00348       if(classNameAttemptingToLoad_ != 0 && !strcmp(classname, classNameAttemptingToLoad_)) {
00349          // We can try to see if the class name contains "basic_string<char>".
00350          // If so, we replace "basic_string<char>" with "string" and try again.
00351          std::string className(classname);
00352          std::string::size_type idx = className.find("basic_string<char>");
00353          if (idx != std::string::npos) {
00354             className.replace(idx, 18, std::string("string"));
00355             //if basic_string<char> was the last argument to a templated class
00356             // then there would be an extra space to separate the two '>'
00357             if(className.size() > idx + 6 && className[idx + 6] == ' ') {
00358               className.replace(idx + 6, 1, "");
00359             }
00360             classNameAttemptingToLoad_ = className.c_str();
00361             returnValue = gROOT->GetClass(className.c_str(), kTRUE);
00362             classNameAttemptingToLoad_ = classname;
00363             return returnValue;
00364          }
00365          //NOTE: As of ROOT 5.27.06 this warning generates false positives for HepMC classes because
00366          // ROOT has special handling for them built into class.rules
00367          //std::cerr << "WARNING[RootAutoLibraryLoader]: Reflex failed to create CINT dictionary for " << classname << std::endl;
00368          return 0;
00369       }
00370       //std::cout << "looking for " << classname << " load " << (load? "T":"F") << std::endl;
00371       if (load) {
00372         //std::cout << " going to call loadLibraryForClass" << std::endl;
00373         //[ROOT 5.28] When Cintex is in its 'Enable' method it will register callbacks to build
00374         // TClasses. During this phase we do not want to actually force TClasses to have to 
00375         // come into existence.
00376 #if ROOT_VERSION_CODE >= ROOT_VERSION(5,27,6)
00377         if (not isInitializingCintex_ and loadLibraryForClass(classname)) {
00378 #else
00379          if (loadLibraryForClass(classname)) {
00380 #endif
00381           //use this to check for infinite recursion attempt
00382           classNameAttemptingToLoad_ = classname;
00383           // This next call will create the TClass object for the class.
00384           // It will also attempt to load the dictionary for the class
00385           // if the second argument is kTRUE. This is the default, so it
00386           // need not be explicitly specified.
00387           returnValue = gROOT->GetClass(classname, kTRUE);
00388           classNameAttemptingToLoad_ = 0;
00389         }
00390       }
00391       return returnValue;
00392    }
00393 
00394    TClass*
00395    RootAutoLibraryLoader::GetClass(type_info const& typeinfo, Bool_t load) {
00396      //std::cout << "looking for type " << typeinfo.name() << std::endl;
00397       TClass* returnValue = 0;
00398       if(load) {
00399          return GetClass(typeinfo.name(), load);
00400       }
00401       return returnValue;
00402    }
00403 
00404    void
00405    RootAutoLibraryLoader::enable() {
00406       //static BareRootProductGetter s_getter;
00407       //static EDProductGetter::Operate s_op(&s_getter);
00408       static RootAutoLibraryLoader s_loader;
00409    }
00410 
00411    void
00412    RootAutoLibraryLoader::loadAll() {
00413      // std::cout << "LoadAllDictionaries" << std::endl;
00414      enable();
00415 
00416      edmplugin::PluginManager* db =  edmplugin::PluginManager::get();
00417 
00418      typedef edmplugin::PluginManager::CategoryToInfos CatToInfos;
00419 
00420      CatToInfos::const_iterator itFound = db->categoryToInfos().find("Capability");
00421 
00422      if(itFound == db->categoryToInfos().end()) {
00423        return;
00424      }
00425      std::string lastClass;
00426      std::string const cPrefix("LCGReflex/");
00427 
00428      //give ROOT a name for the file we are loading
00429      RootLoadFileSentry sentry;
00430 
00431      for (edmplugin::PluginManager::Infos::const_iterator itInfo = itFound->second.begin(),
00432           itInfoEnd = itFound->second.end();
00433           itInfo != itInfoEnd; ++itInfo) {
00434        if (lastClass == itInfo->name_) {
00435          continue;
00436        }
00437 
00438        lastClass = itInfo->name_;
00439        edmplugin::PluginCapabilities::get()->load(lastClass);
00440        //NOTE: since we have the library already, we could be more efficient if we just load it ourselves
00441      }
00442    }
00443 }
00444 
00445 //ClassImp(RootAutoLibraryLoader)