Logo ROOT   6.08/07
Reference Guide
TCling.cxx
Go to the documentation of this file.
1 // @(#)root/meta:$Id$
2 // vim: sw=3 ts=3 expandtab foldmethod=indent
3 
4 /*************************************************************************
5  * Copyright (C) 1995-2012, Rene Brun and Fons Rademakers. *
6  * All rights reserved. *
7  * *
8  * For the licensing terms see $ROOTSYS/LICENSE. *
9  * For the list of contributors see $ROOTSYS/README/CREDITS. *
10  *************************************************************************/
11 
12 /** \class TCling
13 
14 This class defines an interface to the cling C++ interpreter.
15 
16 Cling is a full ANSI compliant C++-11 interpreter based on
17 clang/LLVM technology.
18 */
19 
20 #include "TCling.h"
21 
22 #include "TClingBaseClassInfo.h"
23 #include "TClingCallFunc.h"
24 #include "TClingClassInfo.h"
25 #include "TClingDataMemberInfo.h"
26 #include "TClingMethodArgInfo.h"
27 #include "TClingMethodInfo.h"
28 #include "TClingTypedefInfo.h"
29 #include "TClingTypeInfo.h"
30 #include "TClingValue.h"
31 
32 #include "TROOT.h"
33 #include "TApplication.h"
34 #include "TGlobal.h"
35 #include "TDataType.h"
36 #include "TClass.h"
37 #include "TClassEdit.h"
38 #include "TClassTable.h"
39 #include "TClingCallbacks.h"
40 #include "TBaseClass.h"
41 #include "TDataMember.h"
42 #include "TMemberInspector.h"
43 #include "TMethod.h"
44 #include "TMethodArg.h"
45 #include "TFunctionTemplate.h"
46 #include "TObjArray.h"
47 #include "TObjString.h"
48 #include "TString.h"
49 #include "THashList.h"
50 #include "TOrdCollection.h"
51 #include "TVirtualPad.h"
52 #include "TSystem.h"
53 #include "TVirtualMutex.h"
54 #include "TError.h"
55 #include "TEnv.h"
56 #include "TEnum.h"
57 #include "TEnumConstant.h"
58 #include "THashTable.h"
59 #include "RConfigure.h"
60 #include "compiledata.h"
61 #include "TMetaUtils.h"
63 #include "TVirtualStreamerInfo.h"
64 #include "TListOfDataMembers.h"
65 #include "TListOfEnums.h"
66 #include "TListOfEnumsWithLock.h"
67 #include "TListOfFunctions.h"
69 #include "TProtoClass.h"
70 #include "TStreamerInfo.h" // This is here to avoid to use the plugin manager
71 #include "ThreadLocalStorage.h"
72 #include "TFile.h"
73 #include "TKey.h"
74 #include "ClingRAII.h"
75 
76 #include "clang/AST/ASTContext.h"
77 #include "clang/AST/Decl.h"
78 #include "clang/AST/DeclarationName.h"
79 #include "clang/AST/GlobalDecl.h"
80 #include "clang/AST/RecordLayout.h"
81 #include "clang/AST/RecursiveASTVisitor.h"
82 #include "clang/AST/Type.h"
83 #include "clang/Basic/SourceLocation.h"
84 #include "clang/Basic/Specifiers.h"
85 #include "clang/Basic/TargetInfo.h"
86 #include "clang/CodeGen/ModuleBuilder.h"
87 #include "clang/Frontend/CompilerInstance.h"
88 #include "clang/Frontend/FrontendDiagnostic.h"
89 #include "clang/Lex/HeaderSearch.h"
90 #include "clang/Lex/Preprocessor.h"
91 #include "clang/Sema/Lookup.h"
92 #include "clang/Sema/Sema.h"
93 #include "clang/Parse/Parser.h"
94 
95 #include "cling/Interpreter/ClangInternalState.h"
96 #include "cling/Interpreter/DynamicLibraryManager.h"
97 #include "cling/Interpreter/Interpreter.h"
98 #include "cling/Interpreter/LookupHelper.h"
99 #include "cling/Interpreter/Value.h"
100 #include "cling/Interpreter/Transaction.h"
101 #include "cling/MetaProcessor/MetaProcessor.h"
102 #include "cling/Utils/AST.h"
103 #include "cling/Utils/ParserStateRAII.h"
104 #include "cling/Utils/SourceNormalization.h"
105 #include "cling/Interpreter/Exception.h"
106 
107 #include "llvm/IR/GlobalValue.h"
108 #include "llvm/IR/Module.h"
109 
110 #include "llvm/Support/DynamicLibrary.h"
111 #include "llvm/Support/raw_ostream.h"
112 #include "llvm/Support/Path.h"
113 
114 #include <algorithm>
115 #include <iostream>
116 #include <cassert>
117 #include <map>
118 #include <set>
119 #include <stdexcept>
120 #include <stdint.h>
121 #include <fstream>
122 #include <sstream>
123 #include <string>
124 #include <typeinfo>
125 #include <unordered_map>
126 #include <utility>
127 #include <vector>
128 
129 #ifndef R__WIN32
130 #include <cxxabi.h>
131 #define R__DLLEXPORT
132 #endif
133 #include <limits.h>
134 #include <stdio.h>
135 
136 #ifdef __APPLE__
137 #include <dlfcn.h>
138 #include <mach-o/dyld.h>
139 #include <mach-o/loader.h>
140 #endif // __APPLE__
141 
142 #ifdef R__UNIX
143 #include <dlfcn.h>
144 #endif
145 
146 #if defined(__CYGWIN__)
147 #include <sys/cygwin.h>
148 #define HMODULE void *
149 extern "C" {
150  __declspec(dllimport) void * __stdcall GetCurrentProcess();
151  __declspec(dllimport) bool __stdcall EnumProcessModules(void *, void **, unsigned long, unsigned long *);
152  __declspec(dllimport) unsigned long __stdcall GetModuleFileNameExW(void *, void *, wchar_t *, unsigned long);
153 }
154 #endif
155 
156 // Fragment copied from LLVM's raw_ostream.cpp
157 #if defined(_MSC_VER)
158 #ifndef STDIN_FILENO
159 # define STDIN_FILENO 0
160 #endif
161 #ifndef STDOUT_FILENO
162 # define STDOUT_FILENO 1
163 #endif
164 #ifndef STDERR_FILENO
165 # define STDERR_FILENO 2
166 #endif
167 #ifndef R__WIN32
168 //#if defined(HAVE_UNISTD_H)
169 # include <unistd.h>
170 //#endif
171 #else
172 #include "Windows4Root.h"
173 #include <Psapi.h>
174 #undef GetModuleFileName
175 #define RTLD_DEFAULT ((void *)::GetModuleHandle(NULL))
176 #define dlsym(library, function_name) ::GetProcAddress((HMODULE)library, function_name)
177 #define dlopen(library_name, flags) ::LoadLibrary(library_name)
178 #define dlclose(library) ::FreeLibrary((HMODULE)library)
179 #define R__DLLEXPORT __declspec(dllexport)
180 #endif
181 #endif
182 
183 //______________________________________________________________________________
184 // Infrastructure to detect and react to libCling being teared down.
185 //
186 namespace {
187  class TCling_UnloadMarker {
188  public:
189  ~TCling_UnloadMarker() {
192  }
193  }
194  };
195  static TCling_UnloadMarker gTClingUnloadMarker;
196 }
197 
198 
199 
200 //______________________________________________________________________________
201 // These functions are helpers for debugging issues with non-LLVMDEV builds.
202 //
203 clang::DeclContext* TCling__DEBUG__getDeclContext(clang::Decl* D) {
204  return D->getDeclContext();
205 }
206 clang::NamespaceDecl* TCling__DEBUG__DCtoNamespace(clang::DeclContext* DC) {
207  return llvm::dyn_cast<clang::NamespaceDecl>(DC);
208 }
209 clang::RecordDecl* TCling__DEBUG__DCtoRecordDecl(clang::DeclContext* DC) {
210  return llvm::dyn_cast<clang::RecordDecl>(DC);
211 }
212 void TCling__DEBUG__dump(clang::DeclContext* DC) {
213  return DC->dumpDeclContext();
214 }
215 void TCling__DEBUG__dump(clang::Decl* D) {
216  return D->dump();
217 }
218 void TCling__DEBUG__dump(clang::FunctionDecl* FD) {
219  return FD->dump();
220 }
222  return ((clang::Decl*)D)->dump();
223 }
224 void TCling__DEBUG__printName(clang::Decl* D) {
225  if (clang::NamedDecl* ND = llvm::dyn_cast<clang::NamedDecl>(D)) {
226  std::string name;
227  {
228  llvm::raw_string_ostream OS(name);
229  ND->getNameForDiagnostic(OS, D->getASTContext().getPrintingPolicy(),
230  true /*Qualified*/);
231  }
232  printf("%s\n", name.c_str());
233  }
234 }
235 //______________________________________________________________________________
236 // These functions are helpers for testing issues directly rather than
237 // relying on side effects.
238 // This is used for the test for ROOT-7462/ROOT-6070
239 bool TCling__TEST_isInvalidDecl(clang::Decl* D) {
240  return D->isInvalidDecl();
241 }
242 bool TCling__TEST_isInvalidDecl(ClassInfo_t *input) {
243  TClingClassInfo *info( (TClingClassInfo*) input);
244  assert(info && info->IsValid());
245  return info->GetDecl()->isInvalidDecl();
246 }
247 
248 using namespace std;
249 using namespace clang;
250 using namespace ROOT;
251 
252 namespace {
253  static const std::string gInterpreterClassDef = R"ICF(
254 #undef ClassDef
255 #define ClassDef(name, id) \
256 _ClassDefInterp_(name,id,virtual,) \
257 static int DeclFileLine() { return __LINE__; }
258 #undef ClassDefNV
259 #define ClassDefNV(name, id) \
260 _ClassDefInterp_(name,id,,) \
261 static int DeclFileLine() { return __LINE__; }
262 #undef ClassDefOverride
263 #define ClassDefOverride(name, id) \
264 _ClassDefInterp_(name,id,,override) \
265 static int DeclFileLine() { return __LINE__; }
266 )ICF";
267 
268  static const std::string gNonInterpreterClassDef = R"ICF(
269 #define __ROOTCLING__ 1
270 #undef ClassDef
271 #define ClassDef(name,id) \
272 _ClassDef_(name,id,virtual,) \
273 static int DeclFileLine() { return __LINE__; }
274 #undef ClassDefNV
275 #define ClassDefNV(name, id)\
276 _ClassDef_(name,id,,)\
277 static int DeclFileLine() { return __LINE__; }
278 #undef ClassDefOverride
279 #define ClassDefOverride(name, id)\
280 _ClassDef_(name,id,,override)\
281 static int DeclFileLine() { return __LINE__; }
282 )ICF";
283 
284 // The macros below use ::Error, so let's ensure it is included
285  static const std::string gClassDefInterpMacro = R"ICF(
286 #ifndef ROOT_TError
287 #include "TError.h"
288 #endif
289 
290 #define _ClassDefInterp_(name,id,virtual_keyword, overrd) \
291 private: \
292 public: \
293  static TClass *Class() { static TClass* sIsA = 0; if (!sIsA) sIsA = TClass::GetClass(#name); return sIsA; } \
294  static const char *Class_Name() { return #name; } \
295  static Version_t Class_Version() { return id; } \
296  static TClass *Dictionary() { return 0; } \
297  virtual_keyword TClass *IsA() const overrd { return name::Class(); } \
298  virtual_keyword void ShowMembers(TMemberInspector&insp) const overrd { ::ROOT::Class_ShowMembers(name::Class(), this, insp); } \
299  virtual_keyword void Streamer(TBuffer&) overrd { ::Error("Streamer", "Cannot stream interpreted class."); } \
300  void StreamerNVirtual(TBuffer&ClassDef_StreamerNVirtual_b) { name::Streamer(ClassDef_StreamerNVirtual_b); } \
301  static const char *DeclFileName() { return __FILE__; } \
302  static int ImplFileLine() { return 0; } \
303  static const char *ImplFileName() { return __FILE__; }
304 )ICF";
305 }
307 
308 // The functions are used to bridge cling/clang/llvm compiled with no-rtti and
309 // ROOT (which uses rtti)
310 
311 //______________________________________________________________________________
312 
313 // Class extracting recursively every Enum type defined for a class.
314 class EnumVisitor : public RecursiveASTVisitor<EnumVisitor> {
315 private:
316  llvm::SmallVector<EnumDecl*,128> &fClassEnums;
317 public:
318  EnumVisitor(llvm::SmallVector<EnumDecl*,128> &enums) : fClassEnums(enums)
319  {}
320 
321  bool TraverseStmt(Stmt*) {
322  // Don't descend into function bodies.
323  return true;
324  }
325 
326  bool shouldVisitTemplateInstantiations() const { return true; }
327 
328  bool TraverseClassTemplateDecl(ClassTemplateDecl*) {
329  // Don't descend into templates (but only instances thereof).
330  return true; // returning false will abort the in-depth traversal.
331  }
332 
333  bool TraverseClassTemplatePartialSpecializationDecl(ClassTemplatePartialSpecializationDecl*) {
334  // Don't descend into templates partial specialization (but only instances thereof).
335  return true; // returning false will abort the in-depth traversal.
336  }
337 
338  bool VisitEnumDecl(EnumDecl *TEnumD) {
339  if (!TEnumD->getDeclContext()->isDependentContext())
340  fClassEnums.push_back(TEnumD);
341  return true; // returning false will abort the in-depth traversal.
342  }
343 };
344 
345 ////////////////////////////////////////////////////////////////////////////////
346 /// Print a StackTrace!
347 
348 extern "C"
350  gSystem->StackTrace();
351 }
352 
353 ////////////////////////////////////////////////////////////////////////////////
354 /// Update TClingClassInfo for a class (e.g. upon seeing a definition).
355 
356 static void TCling__UpdateClassInfo(const NamedDecl* TD)
357 {
358  static Bool_t entered = kFALSE;
359  static vector<const NamedDecl*> updateList;
360  Bool_t topLevel;
361 
362  if (entered) topLevel = kFALSE;
363  else {
364  entered = kTRUE;
365  topLevel = kTRUE;
366  }
367  if (topLevel) {
368  ((TCling*)gInterpreter)->UpdateClassInfoWithDecl(TD);
369  } else {
370  // If we are called indirectly from within another call to
371  // TCling::UpdateClassInfo, we delay the update until the dictionary loading
372  // is finished (i.e. when we return to the top level TCling::UpdateClassInfo).
373  // This allows for the dictionary to be fully populated when we actually
374  // update the TClass object. The updating of the TClass sometimes
375  // (STL containers and when there is an emulated class) forces the building
376  // of the TClass object's real data (which needs the dictionary info).
377  updateList.push_back(TD);
378  }
379  if (topLevel) {
380  while (!updateList.empty()) {
381  ((TCling*)gInterpreter)->UpdateClassInfoWithDecl(updateList.back());
382  updateList.pop_back();
383  }
384  entered = kFALSE;
385  }
386 }
387 
388 void TCling::UpdateEnumConstants(TEnum* enumObj, TClass* cl) const {
389  const clang::Decl* D = static_cast<const clang::Decl*>(enumObj->GetDeclId());
390  if(const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(D)) {
391  // Add the constants to the enum type.
392  for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin(),
393  EDE = ED->enumerator_end(); EDI != EDE; ++EDI) {
394  // Get name of the enum type.
395  std::string constbuf;
396  if (const NamedDecl* END = llvm::dyn_cast<NamedDecl>(*EDI)) {
397  PrintingPolicy Policy((*EDI)->getASTContext().getPrintingPolicy());
398  llvm::raw_string_ostream stream(constbuf);
399  // Don't trigger fopen of the source file to count lines:
400  Policy.AnonymousTagLocations = false;
401  (END)->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
402  }
403  const char* constantName = constbuf.c_str();
404 
405  // Get value of the constant.
406  Long64_t value;
407  const llvm::APSInt valAPSInt = (*EDI)->getInitVal();
408  if (valAPSInt.isSigned()) {
409  value = valAPSInt.getSExtValue();
410  } else {
411  value = valAPSInt.getZExtValue();
412  }
413 
414  // Create the TEnumConstant or update it if existing
415  TEnumConstant* enumConstant = nullptr;
416  TClingClassInfo* tcCInfo = (TClingClassInfo*)(cl ? cl->GetClassInfo() : 0);
417  TClingDataMemberInfo* tcDmInfo = new TClingDataMemberInfo(fInterpreter, *EDI, tcCInfo);
418  DataMemberInfo_t* dmInfo = (DataMemberInfo_t*) tcDmInfo;
419  if (TObject* encAsTObj = enumObj->GetConstants()->FindObject(constantName)){
420  ((TEnumConstant*)encAsTObj)->Update(dmInfo);
421  } else {
422  enumConstant = new TEnumConstant(dmInfo, constantName, value, enumObj);
423  }
424 
425  // Add the global constants to the list of Globals.
426  if (!cl) {
427  TCollection* globals = gROOT->GetListOfGlobals(false);
428  if (!globals->FindObject(constantName)) {
429  globals->Add(enumConstant);
430  }
431  }
432  }
433  }
434 }
435 
436 TEnum* TCling::CreateEnum(void *VD, TClass *cl) const
437 {
438  // Handle new enum declaration for either global and nested enums.
439 
440  // Create the enum type.
441  TEnum* enumType = 0;
442  const clang::Decl* D = static_cast<const clang::Decl*>(VD);
443  std::string buf;
444  if (const EnumDecl* ED = llvm::dyn_cast<EnumDecl>(D)) {
445  // Get name of the enum type.
446  PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
447  llvm::raw_string_ostream stream(buf);
448  // Don't trigger fopen of the source file to count lines:
449  Policy.AnonymousTagLocations = false;
450  ED->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
451  // If the enum is unnamed we do not add it to the list of enums i.e unusable.
452  }
453  if (buf.empty()) {
454  return 0;
455  }
456  const char* name = buf.c_str();
457  enumType = new TEnum(name, VD, cl);
458  UpdateEnumConstants(enumType, cl);
459 
460  return enumType;
461 }
462 
463 void TCling::HandleNewDecl(const void* DV, bool isDeserialized, std::set<TClass*> &modifiedTClasses) {
464  // Handle new declaration.
465  // Record the modified class, struct and namespaces in 'modifiedTClasses'.
466 
467  const clang::Decl* D = static_cast<const clang::Decl*>(DV);
468 
469  if (!D->isCanonicalDecl() && !isa<clang::NamespaceDecl>(D)
470  && !dyn_cast<clang::RecordDecl>(D)) return;
471 
472  if (isa<clang::FunctionDecl>(D->getDeclContext())
473  || isa<clang::TagDecl>(D->getDeclContext()))
474  return;
475 
476  // Don't list templates.
477  if (const clang::CXXRecordDecl* RD = dyn_cast<clang::CXXRecordDecl>(D)) {
478  if (RD->getDescribedClassTemplate())
479  return;
480  } else if (const clang::FunctionDecl* FD = dyn_cast<clang::FunctionDecl>(D)) {
481  if (FD->getDescribedFunctionTemplate())
482  return;
483  }
484 
485  if (const RecordDecl *TD = dyn_cast<RecordDecl>(D)) {
486  if (TD->isCanonicalDecl() || TD->isThisDeclarationADefinition())
488  }
489  else if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
490 
491  if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
492  // Mostly just for EnumDecl (the other TagDecl are handled
493  // by the 'RecordDecl' if statement.
495  } else if (const NamespaceDecl* NSD = dyn_cast<NamespaceDecl>(D)) {
497  }
498 
499  // While classes are read completely (except for function template instances,
500  // enum, data (and functions) can be added to namespaces at any time.
501  // [this section can be removed when both the list of data member and the list
502  // of enums has been update to be active list]
503  if (const NamespaceDecl* NCtx = dyn_cast<NamespaceDecl>(ND->getDeclContext())) {
504  if (NCtx->getIdentifier()) {
505  // No need to load the TClass: if there is something to update then
506  // it must already exist.
507  std::string NCtxName;
508  PrintingPolicy Policy(NCtx->getASTContext().getPrintingPolicy());
509  llvm::raw_string_ostream stream(NCtxName);
510  // Don't trigger fopen of the source file to count lines:
511  Policy.AnonymousTagLocations = false;
512  NCtx->getNameForDiagnostic(stream, Policy, /*Qualified=*/true);
513 
514  TClass* cl = (TClass*)gROOT->GetListOfClasses()->FindObject(NCtxName.c_str());
515  if (cl) {
516  modifiedTClasses.insert(cl);
517  }
518  }
519  return;
520  }
521 
522  // We care about declarations on the global scope.
523  if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
524  return;
525 
526  // Enums are lazyly created, thus we don not need to handle them here.
527  if (isa<EnumDecl>(ND))
528  return;
529 
530  // ROOT says that global is enum(lazylycreated)/var/field declared on the global
531  // scope.
532  if (!(isa<VarDecl>(ND)))
533  return;
534 
535  // Skip if already in the list.
536  if (gROOT->GetListOfGlobals()->FindObject(ND->getNameAsString().c_str()))
537  return;
538 
539  // Put the global constants and global enums in the corresponding lists.
540  gROOT->GetListOfGlobals()->Add(new TGlobal((DataMemberInfo_t *)
541  new TClingDataMemberInfo(fInterpreter,
542  cast<ValueDecl>(ND), 0)));
543  }
544 }
545 
546 extern "C"
548 {
549  // We are sure in this context of the type of the interpreter
550  normCtxt = &( (TCling*) gInterpreter)->GetNormalizedContext();
551 }
552 
553 extern "C"
554 void TCling__UpdateListsOnCommitted(const cling::Transaction &T, cling::Interpreter*) {
555 
556  ((TCling*)gCling)->UpdateListsOnCommitted(T);
557 }
558 
559 extern "C"
560 void TCling__UpdateListsOnUnloaded(const cling::Transaction &T) {
561 
562  ((TCling*)gCling)->UpdateListsOnUnloaded(T);
563 }
564 void TCling__TransactionRollback(const cling::Transaction &T) {
565 
566  ((TCling*)gCling)->TransactionRollback(T);
567 }
568 extern "C" void TCling__LibraryLoadedRTTI(const void* dyLibHandle,
569  const char* canonicalName) {
570 
571  ((TCling*)gCling)->LibraryLoaded(dyLibHandle, canonicalName);
572 }
573 
574 extern "C" void TCling__LibraryUnloadedRTTI(const void* dyLibHandle,
575  const char* canonicalName) {
576 
577  ((TCling*)gCling)->LibraryUnloaded(dyLibHandle, canonicalName);
578 }
579 
580 
581 extern "C"
582 TObject* TCling__GetObjectAddress(const char *Name, void *&LookupCtx) {
583  return ((TCling*)gCling)->GetObjectAddress(Name, LookupCtx);
584 }
585 
586 extern "C" const Decl* TCling__GetObjectDecl(TObject *obj) {
587  return ((TClingClassInfo*)obj->IsA()->GetClassInfo())->GetDecl();
588 }
589 
590 extern "C" R__DLLEXPORT TInterpreter *CreateInterpreter(void* interpLibHandle)
591 {
592  cling::DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(interpLibHandle);
593  return new TCling("C++", "cling C++ Interpreter");
594 }
595 
597 {
598  delete interp;
599 }
600 
601 // Load library containing specified class. Returns 0 in case of error
602 // and 1 in case if success.
603 extern "C" int TCling__AutoLoadCallback(const char* className)
604 {
605  return ((TCling*)gCling)->AutoLoad(className);
606 }
607 
608 extern "C" int TCling__AutoParseCallback(const char* className)
609 {
610  return ((TCling*)gCling)->AutoParse(className);
611 }
612 
613 extern "C" const char* TCling__GetClassSharedLibs(const char* className)
614 {
615  return ((TCling*)gCling)->GetClassSharedLibs(className);
616 }
617 
618 // // Returns 0 for failure 1 for success
619 // extern "C" int TCling__IsAutoLoadNamespaceCandidate(const char* name)
620 // {
621 // return ((TCling*)gCling)->IsAutoLoadNamespaceCandidate(name);
622 // }
623 
624 // Returns 0 for failure 1 for success
625 extern "C" int TCling__IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl* nsDecl)
626 {
627  return ((TCling*)gCling)->IsAutoLoadNamespaceCandidate(nsDecl);
628 }
629 
630 extern "C" int TCling__CompileMacro(const char *fileName, const char *options)
631 {
632  string file(fileName);
633  string opt(options);
634  return gSystem->CompileMacro(file.c_str(), opt.c_str());
635 }
636 
637 extern "C" void TCling__SplitAclicMode(const char* fileName, string &mode,
638  string &args, string &io, string &fname)
639 {
640  string file(fileName);
641  TString f, amode, arguments, aclicio;
642  f = gSystem->SplitAclicMode(file.c_str(), amode, arguments, aclicio);
643  mode = amode.Data(); args = arguments.Data();
644  io = aclicio.Data(); fname = f.Data();
645 }
646 
647 //______________________________________________________________________________
648 //
649 //
650 //
651 
652 #ifdef R__WIN32
653 extern "C" {
654  char *__unDName(char *demangled, const char *mangled, int out_len,
655  void * (* pAlloc )(size_t), void (* pFree )(void *),
656  unsigned short int flags);
657 }
658 #endif
659 
660 ////////////////////////////////////////////////////////////////////////////////
661 /// Find a template decl within N nested namespaces, 0<=N<inf
662 /// Assumes 1 and only 1 template present and 1 and only 1 entity contained
663 /// by the namespace. Example: ns1::ns2::..::nsN::myTemplate
664 /// Returns nullptr in case of error
665 
666 static clang::ClassTemplateDecl* FindTemplateInNamespace(clang::Decl* decl)
667 {
668  using namespace clang;
669  if (NamespaceDecl* nsd = llvm::dyn_cast<NamespaceDecl>(decl)){
670  return FindTemplateInNamespace(*nsd->decls_begin());
671  }
672 
673  if (ClassTemplateDecl* ctd = llvm::dyn_cast<ClassTemplateDecl>(decl)){
674  return ctd;
675  }
676 
677  return nullptr; // something went wrong.
678 }
679 
680 ////////////////////////////////////////////////////////////////////////////////
681 /// Autoload a library provided the mangled name of a missing symbol.
682 
683 void* llvmLazyFunctionCreator(const std::string& mangled_name)
684 {
685  return ((TCling*)gCling)->LazyFunctionCreatorAutoload(mangled_name);
686 }
687 
688 //______________________________________________________________________________
689 //
690 //
691 //
692 
693 int TCling_GenerateDictionary(const std::vector<std::string> &classes,
694  const std::vector<std::string> &headers,
695  const std::vector<std::string> &fwdDecls,
696  const std::vector<std::string> &unknown)
697 {
698  //This function automatically creates the "LinkDef.h" file for templated
699  //classes then executes CompileMacro on it.
700  //The name of the file depends on the class name, and it's not generated again
701  //if the file exist.
702  if (classes.empty()) {
703  return 0;
704  }
705  // Use the name of the first class as the main name.
706  const std::string& className = classes[0];
707  //(0) prepare file name
708  TString fileName = "AutoDict_";
709  std::string::const_iterator sIt;
710  for (sIt = className.begin(); sIt != className.end(); sIt++) {
711  if (*sIt == '<' || *sIt == '>' ||
712  *sIt == ' ' || *sIt == '*' ||
713  *sIt == ',' || *sIt == '&' ||
714  *sIt == ':') {
715  fileName += '_';
716  }
717  else {
718  fileName += *sIt;
719  }
720  }
721  if (classes.size() > 1) {
722  Int_t chk = 0;
723  std::vector<std::string>::const_iterator it = classes.begin();
724  while ((++it) != classes.end()) {
725  for (UInt_t cursor = 0; cursor != it->length(); ++cursor) {
726  chk = chk * 3 + it->at(cursor);
727  }
728  }
729  fileName += TString::Format("_%u", chk);
730  }
731  fileName += ".cxx";
732  if (gSystem->AccessPathName(fileName) != 0) {
733  //file does not exist
734  //(1) prepare file data
735  // If STL, also request iterators' operators.
736  // vector is special: we need to check whether
737  // vector::iterator is a typedef to pointer or a
738  // class.
739  static const std::set<std::string> sSTLTypes {
740  "vector","list","forward_list","deque","map","unordered_map","multimap",
741  "unordered_multimap","set","unordered_set","multiset","unordered_multiset",
742  "queue","priority_queue","stack","iterator"};
743  std::vector<std::string>::const_iterator it;
744  std::string fileContent("");
745  for (it = headers.begin(); it != headers.end(); ++it) {
746  fileContent += "#include \"" + *it + "\"\n";
747  }
748  for (it = unknown.begin(); it != unknown.end(); ++it) {
749  TClass* cl = TClass::GetClass(it->c_str());
750  if (cl && cl->GetDeclFileName()) {
751  TString header(gSystem->BaseName(cl->GetDeclFileName()));
752  TString dir(gSystem->DirName(cl->GetDeclFileName()));
753  TString dirbase(gSystem->BaseName(dir));
754  while (dirbase.Length() && dirbase != "."
755  && dirbase != "include" && dirbase != "inc"
756  && dirbase != "prec_stl") {
757  gSystem->PrependPathName(dirbase, header);
758  dir = gSystem->DirName(dir);
759  }
760  fileContent += TString("#include \"") + header + "\"\n";
761  }
762  }
763  for (it = fwdDecls.begin(); it != fwdDecls.end(); ++it) {
764  fileContent += "class " + *it + ";\n";
765  }
766  fileContent += "#ifdef __CINT__ \n";
767  fileContent += "#pragma link C++ nestedclasses;\n";
768  fileContent += "#pragma link C++ nestedtypedefs;\n";
769  for (it = classes.begin(); it != classes.end(); ++it) {
770  std::string n(*it);
771  size_t posTemplate = n.find('<');
772  std::set<std::string>::const_iterator iSTLType = sSTLTypes.end();
773  if (posTemplate != std::string::npos) {
774  n.erase(posTemplate, std::string::npos);
775  if (n.compare(0, 5, "std::") == 0) {
776  n.erase(0, 5);
777  }
778  iSTLType = sSTLTypes.find(n);
779  }
780  fileContent += "#pragma link C++ class ";
781  fileContent += *it + "+;\n" ;
782  fileContent += "#pragma link C++ class ";
783  if (iSTLType != sSTLTypes.end()) {
784  // STL class; we cannot (and don't need to) store iterators;
785  // their shadow and the compiler's version don't agree. So
786  // don't ask for the '+'
787  fileContent += *it + "::*;\n" ;
788  }
789  else {
790  // Not an STL class; we need to allow the I/O of contained
791  // classes (now that we have a dictionary for them).
792  fileContent += *it + "::*+;\n" ;
793  }
794  std::string oprLink("#pragma link C++ operators ");
795  oprLink += *it;
796  // Don't! Requests e.g. op<(const vector<T>&, const vector<T>&):
797  // fileContent += oprLink + ";\n";
798  if (iSTLType != sSTLTypes.end()) {
799  if (n == "vector") {
800  fileContent += "#ifdef G__VECTOR_HAS_CLASS_ITERATOR\n";
801  }
802  fileContent += oprLink + "::iterator;\n";
803  fileContent += oprLink + "::const_iterator;\n";
804  fileContent += oprLink + "::reverse_iterator;\n";
805  if (n == "vector") {
806  fileContent += "#endif\n";
807  }
808  }
809  }
810  fileContent += "#endif\n";
811  //end(1)
812  //(2) prepare the file
813  FILE* filePointer;
814  filePointer = fopen(fileName, "w");
815  if (filePointer == NULL) {
816  //can't open a file
817  return 1;
818  }
819  //end(2)
820  //write data into the file
821  fprintf(filePointer, "%s", fileContent.c_str());
822  fclose(filePointer);
823  }
824  //(3) checking if we can compile a macro, if not then cleaning
825  Int_t oldErrorIgnoreLevel = gErrorIgnoreLevel;
826  gErrorIgnoreLevel = kWarning; // no "Info: creating library..."
827  Int_t ret = gSystem->CompileMacro(fileName, "k");
828  gErrorIgnoreLevel = oldErrorIgnoreLevel;
829  if (ret == 0) { //can't compile a macro
830  return 2;
831  }
832  //end(3)
833  return 0;
834 }
835 
836 int TCling_GenerateDictionary(const std::string& className,
837  const std::vector<std::string> &headers,
838  const std::vector<std::string> &fwdDecls,
839  const std::vector<std::string> &unknown)
840 {
841  //This function automatically creates the "LinkDef.h" file for templated
842  //classes then executes CompileMacro on it.
843  //The name of the file depends on the class name, and it's not generated again
844  //if the file exist.
845  std::vector<std::string> classes;
846  classes.push_back(className);
847  return TCling_GenerateDictionary(classes, headers, fwdDecls, unknown);
848 }
849 
850 //______________________________________________________________________________
851 //
852 //
853 //
854 
855 // It is a "fantom" method to synchronize user keyboard input
856 // and ROOT prompt line (for WIN32)
857 const char* fantomline = "TRint::EndOfLineAction();";
858 
859 //______________________________________________________________________________
860 //
861 //
862 //
863 
864 void* TCling::fgSetOfSpecials = 0;
865 
866 //______________________________________________________________________________
867 //
868 // llvm error handler through exceptions; see also cling/UserInterface
869 //
870 namespace {
871  // Handle fatal llvm errors by throwing an exception.
872  // Yes, throwing exceptions in error handlers is bad.
873  // Doing nothing is pretty terrible, too.
874  void exceptionErrorHandler(void * /*user_data*/,
875  const std::string& reason,
876  bool /*gen_crash_diag*/) {
877  throw std::runtime_error(std::string(">>> Interpreter compilation error:\n") + reason);
878  }
879 }
880 
881 //______________________________________________________________________________
882 //
883 //
884 //
885 
886 ////////////////////////////////////////////////////////////////////////////////
887 
888 namespace{
889  // An instance of this class causes the diagnostics of clang to be suppressed
890  // during its lifetime
891  class clangDiagSuppr {
892  public:
893  clangDiagSuppr(clang::DiagnosticsEngine& diag): fDiagEngine(diag){
894  fOldDiagValue = fDiagEngine.getIgnoreAllWarnings();
895  fDiagEngine.setIgnoreAllWarnings(true);
896  }
897 
898  ~clangDiagSuppr() {
899  fDiagEngine.setIgnoreAllWarnings(fOldDiagValue);
900  }
901  private:
902  clang::DiagnosticsEngine& fDiagEngine;
903  bool fOldDiagValue;
904  };
905 
906 }
907 
908 ////////////////////////////////////////////////////////////////////////////////
909 /// Allow calling autoparsing from TMetaUtils
910 bool TClingLookupHelper__AutoParse(const char *cname)
911 {
912  return gCling->AutoParse(cname);
913 }
914 
915 ////////////////////////////////////////////////////////////////////////////////
916 /// Try hard to avoid looking up in the Cling database as this could enduce
917 /// an unwanted autoparsing.
918 
919 bool TClingLookupHelper__ExistingTypeCheck(const std::string &tname,
920  std::string &result)
921 {
922  result.clear();
923 
924  unsigned long offset = 0;
925  if (strncmp(tname.c_str(), "const ", 6) == 0) {
926  offset = 6;
927  }
928  unsigned long end = tname.length();
929  while( end && (tname[end-1]=='&' || tname[end-1]=='*' || tname[end-1]==']') ) {
930  if ( tname[end-1]==']' ) {
931  --end;
932  while ( end && tname[end-1]!='[' ) --end;
933  }
934  --end;
935  }
936  std::string innerbuf;
937  const char *inner;
938  if (end != tname.length()) {
939  innerbuf = tname.substr(offset,end-offset);
940  inner = innerbuf.c_str();
941  } else {
942  inner = tname.c_str()+offset;
943  }
944 
945  //if (strchr(tname.c_str(),'[')!=0) fprintf(stderr,"DEBUG: checking on %s vs %s %lu %lu\n",tname.c_str(),inner,offset,end);
946  if (gROOT->GetListOfClasses()->FindObject(inner)
947  || TClassTable::Check(inner,result) ) {
948  // This is a known class.
949  return true;
950  }
951 
952  THashTable *typeTable = dynamic_cast<THashTable*>( gROOT->GetListOfTypes() );
953  TDataType *type = (TDataType *)typeTable->THashTable::FindObject( inner );
954  if (type) {
955  // This is a raw type and an already loaded typedef.
956  const char *newname = type->GetFullTypeName();
957  if (type->GetType() == kLong64_t) {
958  newname = "Long64_t";
959  } else if (type->GetType() == kULong64_t) {
960  newname = "ULong64_t";
961  }
962  if (strcmp(inner,newname) == 0) {
963  return true;
964  }
965  if (offset) result = "const ";
966  result += newname;
967  if ( end != tname.length() ) {
968  result += tname.substr(end,tname.length()-end);
969  }
970  if (result == tname) result.clear();
971  return true;
972  }
973 
974  // Check if the name is an enumerator
975  const auto lastPos = TClassEdit::GetUnqualifiedName(inner);
976  if (lastPos != inner) // Main switch: case 1 - scoped enum, case 2 global enum
977  {
978  // We have a scope
979  // All of this C gymnastic is to avoid allocations on the heap
980  const auto enName = lastPos;
981  const auto scopeNameSize = ((Long64_t)lastPos - (Long64_t)inner) / sizeof(decltype(*lastPos)) - 2;
982  char *scopeName = new char[scopeNameSize + 1];
983  strncpy(scopeName, inner, scopeNameSize);
984  scopeName[scopeNameSize] = '\0';
985  // Check if the scope is in the list of classes
986  if (auto scope = static_cast<TClass *>(gROOT->GetListOfClasses()->FindObject(scopeName))) {
987  auto enumTable = dynamic_cast<const THashList *>(scope->GetListOfEnums(false));
988  if (enumTable && enumTable->THashList::FindObject(enName)) return true;
989  }
990  // It may still be in one of the loaded protoclasses
991  else if (auto scope = static_cast<TProtoClass *>(gClassTable->GetProtoNorm(scopeName))) {
992  auto listOfEnums = scope->GetListOfEnums();
993  if (listOfEnums) { // it could be null: no enumerators in the protoclass
994  auto enumTable = dynamic_cast<const THashList *>(listOfEnums);
995  if (enumTable && enumTable->THashList::FindObject(enName)) return true;
996  }
997  }
998  delete [] scopeName;
999  } else
1000  {
1001  // We don't have any scope: this could only be a global enum
1002  auto enumTable = dynamic_cast<const THashList *>(gROOT->GetListOfEnums());
1003  if (enumTable && enumTable->THashList::FindObject(inner)) return true;
1004  }
1005 
1006  if (gCling->GetClassSharedLibs(inner))
1007  {
1008  // This is a class name.
1009  return true;
1010  }
1011 
1012  return false;
1013 }
1014 
1015 ////////////////////////////////////////////////////////////////////////////////
1016 
1018 {
1019  fContent.reserve(size);
1020 }
1021 
1022 ////////////////////////////////////////////////////////////////////////////////
1023 
1024 inline const char *TCling::TUniqueString::Data()
1025 {
1026  return fContent.c_str();
1027 }
1028 
1029 ////////////////////////////////////////////////////////////////////////////////
1030 /// Append string to the storage if not added already.
1031 
1032 inline bool TCling::TUniqueString::Append(const std::string& str)
1033 {
1034  bool notPresent = fLinesHashSet.emplace(fHashFunc(str)).second;
1035  if (notPresent){
1036  fContent+=str;
1037  }
1038  return notPresent;
1039 }
1040 
1041 ////////////////////////////////////////////////////////////////////////////////
1042 /// Initialize the cling interpreter interface.
1043 
1044 TCling::TCling(const char *name, const char *title)
1045 : TInterpreter(name, title), fGlobalsListSerial(-1), fInterpreter(0),
1046  fMetaProcessor(0), fNormalizedCtxt(0), fPrevLoadedDynLibInfo(0),
1047  fClingCallbacks(0), fAutoLoadCallBack(0),
1048  fTransactionCount(0), fHeaderParsingOnDemand(true), fIsAutoParsingSuspended(kFALSE)
1049 {
1050  // rootcling also uses TCling for generating the dictionary ROOT files.
1051  bool fromRootCling = dlsym(RTLD_DEFAULT, "usedToIdentifyRootClingByDlSym");
1052 
1053  llvm::install_fatal_error_handler(&exceptionErrorHandler);
1054 
1055  fTemporaries = new std::vector<cling::Value>();
1056 
1057  std::vector<std::string> clingArgsStorage;
1058  clingArgsStorage.push_back("cling4root");
1059 
1060  std::string interpInclude;
1061  // rootcling sets its arguments through TROOT::GetExtraInterpreterArgs().
1062  if (!fromRootCling) {
1064 
1065  // Add -I early so ASTReader can find the headers.
1066  std::string interpInclude = ROOT::TMetaUtils::GetInterpreterExtraIncludePath(false);
1067  clingArgsStorage.push_back(interpInclude);
1068 
1069  // Add include path to etc/cling. FIXME: This is a short term solution. The
1070  // llvm/clang header files shouldn't be there at all. We have to get rid of
1071  // that dependency and avoid copying the header files.
1072  clingArgsStorage.push_back(interpInclude + "/cling");
1073 
1074  // Add the root include directory and etc/ to list searched by default.
1075  clingArgsStorage.push_back(std::string("-I") + ROOT::TMetaUtils::GetROOTIncludeDir(false));
1076 
1077  // Add the current path to the include path
1078  // TCling::AddIncludePath(".");
1079 
1080  std::string pchFilename = interpInclude.substr(2) + "/allDict.cxx.pch";
1081  if (gSystem->Getenv("ROOT_PCH")) {
1082  pchFilename = gSystem->Getenv("ROOT_PCH");
1083  }
1084  clingArgsStorage.push_back("-include-pch");
1085  clingArgsStorage.push_back(pchFilename);
1086 
1087  // clingArgsStorage.push_back("-Xclang");
1088  // clingArgsStorage.push_back("-fmodules");
1089 
1090  clingArgsStorage.push_back("-Wno-undefined-inline");
1091  clingArgsStorage.push_back("-fsigned-char");
1092  }
1093 
1094  std::vector<const char*> interpArgs;
1095  for (std::vector<std::string>::const_iterator iArg = clingArgsStorage.begin(),
1096  eArg = clingArgsStorage.end(); iArg != eArg; ++iArg)
1097  interpArgs.push_back(iArg->c_str());
1098 
1099  std::string llvmResourceDir = ROOT::TMetaUtils::GetLLVMResourceDir(false);
1100  // Add statically injected extra arguments, usually coming from rootcling.
1101  for (const char** extraArgs = TROOT::GetExtraInterpreterArgs();
1102  extraArgs && *extraArgs; ++extraArgs) {
1103  if (!strcmp(*extraArgs, "-resource-dir")) {
1104  // Take the next arg as the llvm resource directory.
1105  llvmResourceDir = *(++extraArgs);
1106  } else {
1107  interpArgs.push_back(*extraArgs);
1108  }
1109  }
1110 
1111  fInterpreter = new cling::Interpreter(interpArgs.size(),
1112  &(interpArgs[0]),
1113  llvmResourceDir.c_str());
1114 
1115  if (!fromRootCling) {
1116  fInterpreter->installLazyFunctionCreator(llvmLazyFunctionCreator);
1117  }
1118 
1119  // Don't check whether modules' files exist.
1120  fInterpreter->getCI()->getPreprocessorOpts().DisablePCHValidation = true;
1121 
1122  // Until we can disable autoloading during Sema::CorrectTypo() we have
1123  // to disable spell checking.
1124  fInterpreter->getCI()->getLangOpts().SpellChecking = false;
1125 
1126 
1127  // We need stream that doesn't close its file descriptor, thus we are not
1128  // using llvm::outs. Keeping file descriptor open we will be able to use
1129  // the results in pipes (Savannah #99234).
1130  static llvm::raw_fd_ostream fMPOuts (STDOUT_FILENO, /*ShouldClose*/false);
1131  fMetaProcessor = new cling::MetaProcessor(*fInterpreter, fMPOuts);
1132 
1133  // For the list to also include string, we have to include it now.
1134  // rootcling does parts already if needed, e.g. genreflex does not want using
1135  // namespace std.
1136  if (fromRootCling) {
1137  fInterpreter->declare("#include \"RtypesCore.h\"\n"
1138  "#include <string>\n"
1139  "using std::string;");
1140  } else {
1141  fInterpreter->declare("#include \"Rtypes.h\"\n"
1142  + gClassDefInterpMacro + "\n"
1143  + gInterpreterClassDef + "\n"
1144  + "#undef ClassImp\n"
1145  "#define ClassImp(X)\n"
1146  "#include <string>\n"
1147  "using namespace std;");
1148  }
1149 
1150  // We are now ready (enough is loaded) to init the list of opaque typedefs.
1153  TClassEdit::Init(fLookupHelper);
1154 
1155  // Initialize the cling interpreter interface.
1156  fMore = 0;
1157  fPrompt[0] = 0;
1158  fMapfile = 0;
1159 // fMapNamespaces = 0;
1160  fRootmapFiles = 0;
1162 
1163  fAllowLibLoad = !fromRootCling;
1164  // Disallow auto-parsing in rootcling
1165  fIsAutoParsingSuspended = fromRootCling;
1166  // Disable the autoloader until it is explicitly enabled.
1167  SetClassAutoloading(false);
1168 
1169  ResetAll();
1170 #ifndef R__WIN32
1171  //optind = 1; // make sure getopt() works in the main program
1172 #endif // R__WIN32
1173 
1174  // Enable dynamic lookup
1175  if (!fromRootCling) {
1176  fInterpreter->enableDynamicLookup();
1177  }
1178 
1179  // Attach cling callbacks last; they might need TROOT::fInterpreter
1180  // and should thus not be triggered during the equivalent of
1181  // TROOT::fInterpreter = new TCling;
1182  std::unique_ptr<TClingCallbacks>
1183  clingCallbacks(new TClingCallbacks(fInterpreter));
1184  fClingCallbacks = clingCallbacks.get();
1186  fInterpreter->setCallbacks(std::move(clingCallbacks));
1187 
1188 }
1189 
1190 
1191 ////////////////////////////////////////////////////////////////////////////////
1192 /// Destroy the interpreter interface.
1193 
1195 {
1196  delete fMapfile;
1197 // delete fMapNamespaces;
1198  delete fRootmapFiles;
1199  delete fMetaProcessor;
1200  delete fTemporaries;
1201  delete fNormalizedCtxt;
1202  delete fInterpreter;
1203  delete fLookupHelper;
1204  gCling = 0;
1205 #if defined(R__MUST_REVISIT)
1206 #if R__MUST_REVISIT(6,2)
1207  Warning("~TCling", "Interface not available yet.");
1208 #ifdef R__COMPLETE_MEM_TERMINATION
1209  // remove all cling objects
1210 #endif
1211 #endif
1212 #endif
1213  //--
1214 }
1215 
1216 ////////////////////////////////////////////////////////////////////////////////
1217 /// Initialize the interpreter, once TROOT::fInterpreter is set.
1218 
1220 {
1222 }
1223 
1224 ////////////////////////////////////////////////////////////////////////////////
1225 /// Wrapper around dladdr (and friends)
1226 
1227 static const char *FindLibraryName(void (*func)())
1228 {
1229 #if defined(__CYGWIN__) && defined(__GNUC__)
1230  return 0;
1231 #elif defined(G__WIN32)
1232  MEMORY_BASIC_INFORMATION mbi;
1233  if (!VirtualQuery (func, &mbi, sizeof (mbi)))
1234  {
1235  return 0;
1236  }
1237 
1238  HMODULE hMod = (HMODULE) mbi.AllocationBase;
1239  TTHREAD_TLS_ARRAY(char, MAX_PATH, moduleName);
1240 
1241  if (!GetModuleFileNameA (hMod, moduleName, sizeof (moduleName)))
1242  {
1243  return 0;
1244  }
1245  return moduleName;
1246 #else
1247  Dl_info info;
1248  if (dladdr((void*)func,&info)==0) {
1249  // Not in a known share library, let's give up
1250  return 0;
1251  } else {
1252  //fprintf(stdout,"Found address in %s\n",info.dli_fname);
1253  return info.dli_fname;
1254  }
1255 #endif
1256 
1257 }
1258 
1259 ////////////////////////////////////////////////////////////////////////////////
1260 /// Helper to initialize TVirtualStreamerInfo's factor early.
1261 /// Use static initialization to insure only one TStreamerInfo is created.
1263 {
1264  // Use lambda since SetFactory return void.
1265  auto setFactory = []() {
1267  return kTRUE;
1268  };
1269  static bool doneFactory = setFactory();
1270  return doneFactory; // avoid unused variable warning.
1271 }
1272 
1273 
1274 ////////////////////////////////////////////////////////////////////////////////
1275 /// Tries to load a PCM; returns true on success.
1276 
1277 bool TCling::LoadPCM(TString pcmFileName,
1278  const char** headers,
1279  void (*triggerFunc)()) const {
1280  // pcmFileName is an intentional copy; updated by FindFile() below.
1281 
1282  TString searchPath;
1283 
1284  if (triggerFunc) {
1285  const char *libraryName = FindLibraryName(triggerFunc);
1286  if (libraryName) {
1287  searchPath = llvm::sys::path::parent_path(libraryName);
1288 #ifdef R__WIN32
1289  searchPath += ";";
1290 #else
1291  searchPath += ":";
1292 #endif
1293  }
1294  }
1295  // Note: if we know where the library is, we probably shouldn't even
1296  // look in other places.
1297  searchPath.Append( gSystem->GetDynamicPath() );
1298 
1299  if (!gSystem->FindFile(searchPath, pcmFileName))
1300  return kFALSE;
1301 
1302  // Prevent the ROOT-PCMs hitting this during auto-load during
1303  // JITting - which will cause recursive compilation.
1304  // Avoid to call the plugin manager at all.
1306 
1307  if (gROOT->IsRootFile(pcmFileName)) {
1308  Int_t oldDebug = gDebug;
1309  if (gDebug > 5) {
1310  gDebug -= 5;
1311  ::Info("TCling::LoadPCM", "Loading ROOT PCM %s", pcmFileName.Data());
1312  } else {
1313  gDebug = 0;
1314  }
1315 
1316  TDirectory::TContext ctxt;
1317 
1318  TFile *pcmFile = new TFile(pcmFileName+"?filetype=pcm","READ");
1319 
1320  auto listOfKeys = pcmFile->GetListOfKeys();
1321 
1322  // This is an empty pcm
1323  if (
1324  listOfKeys &&
1325  (
1326  (listOfKeys->GetSize() == 0) || // Nothing here, or
1327  (
1328  (listOfKeys->GetSize() == 1) && // only one, and
1329  !strcmp(((TKey*)listOfKeys->At(0))->GetName(), "EMPTY") // name is EMPTY
1330  )
1331  )
1332  ) {
1333  delete pcmFile;
1334  gDebug = oldDebug;
1335  return kTRUE;
1336  }
1337 
1338  TObjArray *protoClasses;
1339  if (gDebug > 1)
1340  ::Info("TCling::LoadPCM","reading protoclasses for %s \n",pcmFileName.Data());
1341 
1342  pcmFile->GetObject("__ProtoClasses", protoClasses);
1343 
1344  if (protoClasses) {
1345  for (auto obj : *protoClasses) {
1346  TProtoClass * proto = (TProtoClass*)obj;
1347  TClassTable::Add(proto);
1348  }
1349  // Now that all TClass-es know how to set them up we can update
1350  // existing TClasses, which might cause the creation of e.g. TBaseClass
1351  // objects which in turn requires the creation of TClasses, that could
1352  // come from the PCH, but maybe later in the loop. Instead of resolving
1353  // a dependency graph the addition to the TClassTable above allows us
1354  // to create these dependent TClasses as needed below.
1355  for (auto proto : *protoClasses) {
1356  if (TClass* existingCl
1357  = (TClass*)gROOT->GetListOfClasses()->FindObject(proto->GetName())) {
1358  // We have an existing TClass object. It might be emulated
1359  // or interpreted; we now have more information available.
1360  // Make that available.
1361  if (existingCl->GetState() != TClass::kHasTClassInit) {
1362  DictFuncPtr_t dict = gClassTable->GetDict(proto->GetName());
1363  if (!dict) {
1364  ::Error("TCling::LoadPCM", "Inconsistent TClassTable for %s",
1365  proto->GetName());
1366  } else {
1367  // This will replace the existing TClass.
1368  TClass *ncl = (*dict)();
1369  if (ncl) ncl->PostLoadCheck();
1370 
1371  }
1372  }
1373  }
1374  }
1375 
1376  protoClasses->Clear(); // Ownership was transfered to TClassTable.
1377  delete protoClasses;
1378  }
1379 
1380  TObjArray *dataTypes;
1381  pcmFile->GetObject("__Typedefs", dataTypes);
1382  if (dataTypes) {
1383  for (auto typedf: *dataTypes)
1384  gROOT->GetListOfTypes()->Add(typedf);
1385  dataTypes->Clear(); // Ownership was transfered to TListOfTypes.
1386  delete dataTypes;
1387  }
1388 
1389  TObjArray *enums;
1390  pcmFile->GetObject("__Enums", enums);
1391  if (enums) {
1392  // Cache the pointers
1393  auto listOfGlobals = gROOT->GetListOfGlobals();
1394  auto listOfEnums = dynamic_cast<THashList*>(gROOT->GetListOfEnums());
1395  // Loop on enums and then on enum constants
1396  for (auto selEnum: *enums){
1397  const char* enumScope = selEnum->GetTitle();
1398  const char* enumName = selEnum->GetName();
1399  if (strcmp(enumScope,"") == 0){
1400  // This is a global enum and is added to the
1401  // list of enums and its constants to the list of globals
1402  if (!listOfEnums->THashList::FindObject(enumName)){
1403  ((TEnum*) selEnum)->SetClass(nullptr);
1404  listOfEnums->Add(selEnum);
1405  }
1406  for (auto enumConstant: *static_cast<TEnum*>(selEnum)->GetConstants()){
1407  if (!listOfGlobals->FindObject(enumConstant)){
1408  listOfGlobals->Add(enumConstant);
1409  }
1410  }
1411  }
1412  else {
1413  // This enum is in a namespace. A TClass entry is bootstrapped if
1414  // none exists yet and the enum is added to it
1415  TClass* nsTClassEntry = TClass::GetClass(enumScope);
1416  if (!nsTClassEntry){
1417  nsTClassEntry = new TClass(enumScope,0,TClass::kNamespaceForMeta, true);
1418  }
1419  auto listOfEnums = nsTClassEntry->fEnums.load();
1420  if (!listOfEnums) {
1421  if ( (kIsClass | kIsStruct | kIsUnion) & nsTClassEntry->Property() ) {
1422  // For this case, the list will be immutable once constructed
1423  // (i.e. in this case, by the end of this routine).
1424  listOfEnums = nsTClassEntry->fEnums = new TListOfEnums(nsTClassEntry);
1425  } else {
1426  //namespaces can have enums added to them
1427  listOfEnums = nsTClassEntry->fEnums = new TListOfEnumsWithLock(nsTClassEntry);
1428  }
1429  }
1430  if (listOfEnums && !listOfEnums->THashList::FindObject(enumName)){
1431  ((TEnum*) selEnum)->SetClass(nsTClassEntry);
1432  listOfEnums->Add(selEnum);
1433  }
1434  }
1435  }
1436  enums->Clear();
1437  delete enums;
1438  }
1439 
1440  delete pcmFile;
1441 
1442  gDebug = oldDebug;
1443  } else {
1444  if (gDebug > 5)
1445  ::Info("TCling::LoadPCM", "Loading clang PCM %s", pcmFileName.Data());
1446 
1447  }
1448  // Note: Declaring the relationship between the module (pcm) and the header
1449  // probably does not yet make sense since the pcm is 'only' a root file.
1450  // We also have to review if we still need to do this with the delay loading.
1451  // clang::CompilerInstance* CI = fInterpreter->getCI();
1452  // ROOT::TMetaUtils::declareModuleMap(CI, pcmFileName, headers);
1453  return kTRUE;
1454 }
1455 
1456 //______________________________________________________________________________
1457 
1458 namespace {
1459  using namespace clang;
1460 
1461  class ExtLexicalStorageAdder: public RecursiveASTVisitor<ExtLexicalStorageAdder>{
1462  // This class is to be considered an helper for autoparsing.
1463  // It visits the AST and marks all classes (in all of their redeclarations)
1464  // with the setHasExternalLexicalStorage method.
1465  public:
1466  bool VisitRecordDecl(clang::RecordDecl* rcd){
1467  if (gDebug > 2)
1468  Info("ExtLexicalStorageAdder",
1469  "Adding external lexical storage to class %s",
1470  rcd->getNameAsString().c_str());
1471  auto reDeclPtr = rcd->getMostRecentDecl();
1472  do {
1473  reDeclPtr->setHasExternalLexicalStorage();
1474  } while ((reDeclPtr = reDeclPtr->getPreviousDecl()));
1475 
1476  return false;
1477  }
1478  };
1479 
1480 
1481 }
1482 
1483 ////////////////////////////////////////////////////////////////////////////////
1484 /// Inject the module named "modulename" into cling; load all headers.
1485 /// headers is a 0-terminated array of header files to #include after
1486 /// loading the module. The module is searched for in all $LD_LIBRARY_PATH
1487 /// entries (or %PATH% on Windows).
1488 /// This function gets called by the static initialization of dictionary
1489 /// libraries.
1490 /// The payload code is injected "as is" in the interpreter.
1491 /// The value of 'triggerFunc' is used to find the shared library location.
1492 
1493 void TCling::RegisterModule(const char* modulename,
1494  const char** headers,
1495  const char** includePaths,
1496  const char* payloadCode,
1497  const char* fwdDeclsCode,
1498  void (*triggerFunc)(),
1499  const FwdDeclArgsToKeepCollection_t& fwdDeclsArgToSkip,
1500  const char** classesHeaders,
1501  Bool_t lateRegistration /*=false*/)
1502 {
1503  // rootcling also uses TCling for generating the dictionary ROOT files.
1504  static const bool fromRootCling = dlsym(RTLD_DEFAULT, "usedToIdentifyRootClingByDlSym");
1505  // We need the dictionary initialization but we don't want to inject the
1506  // declarations into the interpreter, except for those we really need for
1507  // I/O; see rootcling.cxx after the call to TCling__GetInterpreter().
1508  if (fromRootCling) return;
1509 
1510  // Treat Aclic Libs in a special way. Do not delay the parsing.
1511  bool hasHeaderParsingOnDemand = fHeaderParsingOnDemand;
1512  bool isACLiC = false;
1513  if (hasHeaderParsingOnDemand &&
1514  strstr(modulename, "_ACLiC_dict") != nullptr){
1515  if (gDebug>1)
1516  Info("TCling::RegisterModule",
1517  "Header parsing on demand is active but this is an Aclic library. Disabling it for this library.");
1518  hasHeaderParsingOnDemand = false;
1519  isACLiC = true;
1520  }
1521 
1522 
1523  // Make sure we relookup symbols that were search for before we loaded
1524  // their autoparse information. We could be more subtil and remove only
1525  // the failed one or only the one in this module, but for now this is
1526  // better than nothing.
1527  fLookedUpClasses.clear();
1528 
1529  // Make sure we do not set off autoloading or autoparsing during the
1530  // module registration!
1531  Int_t oldAutoloadValue = SetClassAutoloading(false);
1532 
1533  TString pcmFileName(ROOT::TMetaUtils::GetModuleFileName(modulename).c_str());
1534 
1535  for (const char** inclPath = includePaths; *inclPath; ++inclPath) {
1536  TCling::AddIncludePath(*inclPath);
1537  }
1538  cling::Transaction* T = 0;
1539  // Put the template decls and the number of arguments to skip in the TNormalizedCtxt
1540  for (auto& fwdDeclArgToSkipPair : fwdDeclsArgToSkip){
1541  const std::string& fwdDecl = fwdDeclArgToSkipPair.first;
1542  const int nArgsToSkip = fwdDeclArgToSkipPair.second;
1543  auto compRes = fInterpreter->declare(fwdDecl.c_str(), &T);
1544  assert(cling::Interpreter::kSuccess == compRes &&
1545  "A fwd declaration could not be compiled");
1546  if (compRes!=cling::Interpreter::kSuccess){
1547  Warning("TCling::RegisterModule",
1548  "Problems in declaring string '%s' were encountered.",
1549  fwdDecl.c_str()) ;
1550  continue;
1551  }
1552 
1553  // Drill through namespaces recursively until the template is found
1554  if(ClassTemplateDecl* TD = FindTemplateInNamespace(T->getFirstDecl().getSingleDecl())){
1555  fNormalizedCtxt->AddTemplAndNargsToKeep(TD->getCanonicalDecl(), nArgsToSkip);
1556  }
1557 
1558  }
1559 
1560  // FIXME: Remove #define __ROOTCLING__ once PCMs are there.
1561  // This is used to give Sema the same view on ACLiC'ed files (which
1562  // are then #included through the dictionary) as rootcling had.
1563  TString code = gNonInterpreterClassDef;
1564  code += payloadCode;
1565 
1566  const char* dyLibName = nullptr;
1567  // If this call happens after dlopen has finished (i.e. late registration)
1568  // there is no need to dlopen the library recursively. See ROOT-8437 where
1569  // the dyLibName would correspond to the binary.
1570  if (!lateRegistration) {
1571  // We need to open the dictionary shared library, to resolve symbols
1572  // requested by the JIT from it: as the library is currently being dlopen'ed,
1573  // its symbols are not yet reachable from the process.
1574  // Recursive dlopen seems to work just fine.
1575  dyLibName = FindLibraryName(triggerFunc);
1576  if (dyLibName) {
1577  // We were able to determine the library name.
1578  void* dyLibHandle = dlopen(dyLibName, RTLD_LAZY | RTLD_GLOBAL);
1579  if (!dyLibHandle) {
1580 #ifdef R__WIN32
1581  char dyLibError[1000];
1582  FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(),
1583  MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), dyLibError,
1584  sizeof(dyLibError), NULL);
1585 #else
1586  const char* dyLibError = dlerror();
1587  if (dyLibError)
1588 #endif
1589  {
1590  if (gDebug > 0) {
1591  ::Info("TCling::RegisterModule",
1592  "Cannot open shared library %s for dictionary %s:\n %s",
1593  dyLibName, modulename, dyLibError);
1594  }
1595  }
1596  dyLibName = 0;
1597  } else {
1598  fRegisterModuleDyLibs.push_back(dyLibHandle);
1599  } // if (!dyLibHandle) .. else
1600  } // if (dyLibName)
1601  } // if (!lateRegistration)
1602 
1603  if (hasHeaderParsingOnDemand && fwdDeclsCode){
1604  // We now parse the forward declarations. All the classes are then modified
1605  // in order for them to have an external lexical storage.
1606  std::string fwdDeclsCodeLessEnums;
1607  {
1608  // Search for enum forward decls and only declare them if no
1609  // declaration exists yet.
1610  std::string fwdDeclsLine;
1611  std::istringstream fwdDeclsCodeStr(fwdDeclsCode);
1612  std::vector<std::string> scope;
1613  while (std::getline(fwdDeclsCodeStr, fwdDeclsLine)) {
1614  if (fwdDeclsLine.find("namespace ") == 0
1615  || fwdDeclsLine.find("inline namespace ") == 0) {
1616  // skip leading "namespace ", trailing " {"
1617  scope.push_back(fwdDeclsLine.substr(10,
1618  fwdDeclsLine.length() - 10 - 2));
1619  } else if (fwdDeclsLine == "}") {
1620  scope.pop_back();
1621  } else if (fwdDeclsLine.find("enum __attribute__((annotate(\"") == 0) {
1622  clang::DeclContext* DC = 0;
1623  for (auto &&aScope: scope) {
1624  DC = cling::utils::Lookup::Namespace(&fInterpreter->getSema(), aScope.c_str(), DC);
1625  if (!DC) {
1626  // No decl context means we have to fwd declare the enum.
1627  break;
1628  }
1629  }
1630  if (scope.empty() || DC) {
1631  // We know the scope; let's look for the enum.
1632  size_t posEnumName = fwdDeclsLine.find("\"))) ", 32);
1633  R__ASSERT(posEnumName != std::string::npos && "Inconsistent enum fwd decl!");
1634  posEnumName += 5; // skip "\"))) "
1635  while (isspace(fwdDeclsLine[posEnumName]))
1636  ++posEnumName;
1637  size_t posEnumNameEnd = fwdDeclsLine.find(" : ", posEnumName);
1638  R__ASSERT(posEnumNameEnd != std::string::npos && "Inconsistent enum fwd decl (end)!");
1639  while (isspace(fwdDeclsLine[posEnumNameEnd]))
1640  --posEnumNameEnd;
1641  // posEnumNameEnd now points to the last character of the name.
1642 
1643  std::string enumName = fwdDeclsLine.substr(posEnumName,
1644  posEnumNameEnd - posEnumName + 1);
1645 
1646  if (clang::NamedDecl* enumDecl
1647  = cling::utils::Lookup::Named(&fInterpreter->getSema(),
1648  enumName.c_str(), DC)) {
1649  // We have an existing enum decl (forward or definition);
1650  // skip this.
1651  R__ASSERT(llvm::dyn_cast<clang::EnumDecl>(enumDecl) && "not an enum decl!");
1652  (void)enumDecl;
1653  continue;
1654  }
1655  }
1656  }
1657  fwdDeclsCodeLessEnums += fwdDeclsLine + "\n";
1658  }
1659  }
1660 
1661  if (fwdDeclsCodeLessEnums.size() != 0){ // Avoid the overhead if nothing is to be declared
1662  auto compRes = fInterpreter->declare(fwdDeclsCodeLessEnums, &T);
1663  assert(cling::Interpreter::kSuccess == compRes &&
1664  "The forward declarations could not be compiled");
1665  if (compRes!=cling::Interpreter::kSuccess){
1666  Warning("TCling::RegisterModule",
1667  "Problems in compiling forward declarations for module %s: '%s'",
1668  modulename, fwdDeclsCodeLessEnums.c_str()) ;
1669  }
1670  else if (T){
1671  // Loop over all decls in the transaction and go through them all
1672  // to mark them properly.
1673  // In order to do that, we first iterate over all the DelayedCallInfos
1674  // within the transaction. Then we loop over all Decls in the DeclGroupRef
1675  // contained in the DelayedCallInfos. For each decl, we traverse.
1676  ExtLexicalStorageAdder elsa;
1677  for (auto dciIt = T->decls_begin();dciIt!=T->decls_end();dciIt++){
1678  cling::Transaction::DelayCallInfo& dci = *dciIt;
1679  for(auto dit = dci.m_DGR.begin(); dit != dci.m_DGR.end(); ++dit) {
1680  clang::Decl* declPtr = *dit;
1681  elsa.TraverseDecl(declPtr);
1682  }
1683  }
1684  }
1685  }
1686 
1687  // Now we register all the headers necessary for the class
1688  // Typical format of the array:
1689  // {"A", "classes.h", "@",
1690  // "vector<A>", "vector", "@",
1691  // "myClass", payloadCode, "@",
1692  // nullptr};
1693 
1694  std::string temp;
1695  for (const char** classesHeader = classesHeaders; *classesHeader; ++classesHeader) {
1696  temp=*classesHeader;
1697 
1698  size_t theTemplateHash = 0;
1699  bool addTemplate = false;
1700  size_t posTemplate = temp.find('<');
1701  if (posTemplate != std::string::npos) {
1702  // Add an entry for the template itself.
1703  std::string templateName = temp.substr(0, posTemplate);
1704  theTemplateHash = fStringHashFunction(templateName);
1705  addTemplate = true;
1706  }
1707  size_t theHash = fStringHashFunction(temp);
1708  classesHeader++;
1709  for (const char** classesHeader_inner = classesHeader; 0!=strcmp(*classesHeader_inner,"@"); ++classesHeader_inner,++classesHeader){
1710  // This is done in order to distinguish headers from files and from the payloadCode
1711  if (payloadCode == *classesHeader_inner ){
1712  fPayloads.insert(theHash);
1713  if (addTemplate) fPayloads.insert(theTemplateHash);
1714  }
1715  if (gDebug > 2)
1716  Info("TCling::RegisterModule",
1717  "Adding a header for %s", temp.c_str());
1718  fClassesHeadersMap[theHash].push_back(*classesHeader_inner);
1719  if (addTemplate) {
1720  if (fClassesHeadersMap.find(theTemplateHash) == fClassesHeadersMap.end()) {
1721  fClassesHeadersMap[theTemplateHash].push_back(*classesHeader_inner);
1722  }
1723  addTemplate = false;
1724  }
1725  }
1726  }
1727  }
1728 
1729 
1730  if (strcmp(modulename,"libCore")!=0 && strcmp(modulename,"libRint")!=0
1731  && strcmp(modulename,"libThread")!=0 && strcmp(modulename,"libRIO")!=0
1732  && strcmp(modulename,"libcomplexDict")!=0 && strcmp(modulename,"libdequeDict")!=0
1733  && strcmp(modulename,"liblistDict")!=0 && strcmp(modulename,"libforward_listDict")!=0
1734  && strcmp(modulename,"libvectorDict")!=0
1735  && strcmp(modulename,"libmapDict")!=0 && strcmp(modulename,"libmultimap2Dict")!=0
1736  && strcmp(modulename,"libmap2Dict")!=0 && strcmp(modulename,"libmultimapDict")!=0
1737  && strcmp(modulename,"libsetDict")!=0 && strcmp(modulename,"libmultisetDict")!=0
1738  && strcmp(modulename,"libunordered_setDict")!=0 && strcmp(modulename,"libunordered_multisetDict")!=0
1739  && strcmp(modulename,"libunordered_mapDict")!=0 && strcmp(modulename,"libunordered_multimapDict")!=0
1740  && strcmp(modulename,"libvalarrayDict")!=0
1741  && strcmp(modulename,"G__GenVector32")!=0 && strcmp(modulename,"G__Smatrix32")!=0
1742 
1743  ) {
1744  // No pcm for now for libCore or libRint, the info is in the pch.
1745  if (!LoadPCM(pcmFileName, headers, triggerFunc)) {
1746  ::Error("TCling::RegisterModule", "cannot find dictionary module %s",
1747  ROOT::TMetaUtils::GetModuleFileName(modulename).c_str());
1748  }
1749  }
1750 
1751  bool oldValue = false;
1752  if (fClingCallbacks)
1753  oldValue = SetClassAutoloading(false);
1754 
1755  { // scope within which diagnostics are de-activated
1756  // For now we disable diagnostics because we saw them already at
1757  // dictionary generation time. That won't be an issue with the PCMs.
1758 
1759  clangDiagSuppr diagSuppr(fInterpreter->getSema().getDiagnostics());
1760 
1761 #if defined(R__MUST_REVISIT)
1762 #if R__MUST_REVISIT(6,2)
1763  Warning("TCling::RegisterModule","Diagnostics suppression should be gone by now.");
1764 #endif
1765 #endif
1766 
1767  if (!hasHeaderParsingOnDemand){
1768  SuspendAutoParsing autoParseRaii(this);
1769 
1770  const cling::Transaction* watermark = fInterpreter->getLastTransaction();
1771  cling::Interpreter::CompilationResult compRes = fInterpreter->parseForModule(code.Data());
1772  if (isACLiC) {
1773  // Register an unload point.
1774  fMetaProcessor->registerUnloadPoint(watermark, headers[0]);
1775  }
1776 
1777  assert(cling::Interpreter::kSuccess == compRes &&
1778  "Payload code of a dictionary could not be parsed correctly.");
1779  if (compRes!=cling::Interpreter::kSuccess) {
1780  Warning("TCling::RegisterModule",
1781  "Problems declaring payload for module %s.", modulename) ;
1782  }
1783  }
1784  }
1785 
1786  // Now that all the header have been registered/compiled, let's
1787  // make sure to 'reset' the TClass that have a class init in this module
1788  // but already had their type information available (using information/header
1789  // loaded from other modules or from class rules).
1790  if (!hasHeaderParsingOnDemand) {
1791  // This code is likely to be superseded by the similar code in LoadPCM,
1792  // and have been disabled, (inadvertently or awkwardly) by
1793  // commit 7903f09f3beea69e82ffba29f59fb2d656a4fd54 (Refactor the routines used for header parsing on demand)
1794  // whereas it seems that a more semantically correct conditional would have
1795  // been 'if this module does not have a rootpcm'.
1796  // Note: this need to be review when the clang pcm are being installed.
1797  // #if defined(R__MUST_REVISIT)
1798  while (!fClassesToUpdate.empty()) {
1799  TClass *oldcl = fClassesToUpdate.back().first;
1800  if (oldcl->GetState() != TClass::kHasTClassInit) {
1801  // if (gDebug > 2) Info("RegisterModule", "Forcing TClass init for %s", oldcl->GetName());
1802  DictFuncPtr_t dict = fClassesToUpdate.back().second;
1803  fClassesToUpdate.pop_back();
1804  // Calling func could manipulate the list so, let maintain the list
1805  // then call the dictionary function.
1806  TClass *ncl = dict();
1807  if (ncl) ncl->PostLoadCheck();
1808  } else {
1809  fClassesToUpdate.pop_back();
1810  }
1811  }
1812  }
1813 
1814  if (fClingCallbacks)
1815  SetClassAutoloading(oldValue);
1816 
1817  if (!hasHeaderParsingOnDemand) {
1818  // __ROOTCLING__ might be pulled in through PCH
1819  fInterpreter->declare("#ifdef __ROOTCLING__\n"
1820  "#undef __ROOTCLING__\n"
1821  + gInterpreterClassDef +
1822  "#endif");
1823  }
1824 
1825  if (dyLibName) {
1826  void* dyLibHandle = fRegisterModuleDyLibs.back();
1827  fRegisterModuleDyLibs.pop_back();
1828  dlclose(dyLibHandle);
1829  }
1830 
1831  SetClassAutoloading(oldAutoloadValue);
1832 }
1833 
1834 ////////////////////////////////////////////////////////////////////////////////
1835 /// Register classes that already existed prior to their dictionary loading
1836 /// and that already had a ClassInfo (and thus would not be refresh via
1837 /// UpdateClassInfo.
1838 
1840 {
1841  fClassesToUpdate.push_back(std::make_pair(oldcl,dict));
1842 }
1843 
1844 ////////////////////////////////////////////////////////////////////////////////
1845 /// If the dictionary is loaded, we can remove the class from the list
1846 /// (otherwise the class might be loaded twice).
1847 
1849 {
1850  typedef std::vector<std::pair<TClass*,DictFuncPtr_t> >::iterator iterator;
1851  iterator stop = fClassesToUpdate.end();
1852  for(iterator i = fClassesToUpdate.begin();
1853  i != stop;
1854  ++i)
1855  {
1856  if ( i->first == oldcl ) {
1857  fClassesToUpdate.erase(i);
1858  return;
1859  }
1860  }
1861 }
1862 
1863 ////////////////////////////////////////////////////////////////////////////////
1864 /// Let cling process a command line.
1865 ///
1866 /// If the command is executed and the error is 0, then the return value
1867 /// is the int value corresponding to the result of the executed command
1868 /// (float and double return values will be truncated).
1869 ///
1870 
1871 // Method for handling the interpreter exceptions.
1872 // the MetaProcessor is passing in as argument to teh function, because
1873 // cling::Interpreter::CompilationResult is a nested class and it cannot be
1874 // forward declared, thus this method cannot be a static member function
1875 // of TCling.
1876 
1877 static int HandleInterpreterException(cling::MetaProcessor* metaProcessor,
1878  const char* input_line,
1879  cling::Interpreter::CompilationResult& compRes,
1881 {
1882  try {
1883  return metaProcessor->process(input_line, compRes, result);
1884  }
1885  catch (cling::InvalidDerefException& ex)
1886  {
1887  Error("HandleInterpreterException", "%s.\n%s", ex.what(), "Execution of your code was aborted.");
1888  ex.diagnose();
1889  }
1890  return 0;
1891 }
1892 
1893 ////////////////////////////////////////////////////////////////////////////////
1894 
1895 bool TCling::DiagnoseIfInterpreterException(const std::exception &e) const
1896 {
1897  if (auto ie = dynamic_cast<const cling::InterpreterException*>(&e)) {
1898  ie->diagnose();
1899  return true;
1900  }
1901  return false;
1902 }
1903 
1904 ////////////////////////////////////////////////////////////////////////////////
1905 
1906 Long_t TCling::ProcessLine(const char* line, EErrorCode* error/*=0*/)
1907 {
1908  // Copy the passed line, it comes from a static buffer in TApplication
1909  // which can be reentered through the Cling evaluation routines,
1910  // which would overwrite the static buffer and we would forget what we
1911  // were doing.
1912  //
1913  TString sLine(line);
1914  if (strstr(line,fantomline)) {
1915  // End-Of-Line action
1916  // See the comment (copied from above):
1917  // It is a "fantom" method to synchronize user keyboard input
1918  // and ROOT prompt line (for WIN32)
1919  // and is implemented by
1920  if (gApplication) {
1921  if (gApplication->IsCmdThread()) {
1923  gGlobalMutex->Lock();
1924  if (!gInterpreterMutex)
1926  gGlobalMutex->UnLock();
1927  }
1929  gROOT->SetLineIsProcessing();
1930 
1932 
1933  gROOT->SetLineHasBeenProcessed();
1934  }
1935  }
1936  return 0;
1937  }
1938 
1940  gGlobalMutex->Lock();
1941  if (!gInterpreterMutex)
1943  gGlobalMutex->UnLock();
1944  }
1946  gROOT->SetLineIsProcessing();
1947 
1948  struct InterpreterFlagsRAII {
1949  cling::Interpreter* fInterpreter;
1950  bool fWasDynamicLookupEnabled;
1951 
1952  InterpreterFlagsRAII(cling::Interpreter* interp):
1953  fInterpreter(interp),
1954  fWasDynamicLookupEnabled(interp->isDynamicLookupEnabled())
1955  {
1956  fInterpreter->enableDynamicLookup(true);
1957  }
1958  ~InterpreterFlagsRAII() {
1959  fInterpreter->enableDynamicLookup(fWasDynamicLookupEnabled);
1960  gROOT->SetLineHasBeenProcessed();
1961  }
1962  } interpreterFlagsRAII(fInterpreter);
1963 
1964  // A non-zero returned value means the given line was
1965  // not a complete statement.
1966  int indent = 0;
1967  // This will hold the resulting value of the evaluation the given line.
1969  cling::Interpreter::CompilationResult compRes = cling::Interpreter::kSuccess;
1970  if (!strncmp(sLine.Data(), ".L", 2) || !strncmp(sLine.Data(), ".x", 2) ||
1971  !strncmp(sLine.Data(), ".X", 2)) {
1972  // If there was a trailing "+", then CINT compiled the code above,
1973  // and we will need to strip the "+" before passing the line to cling.
1974  TString mod_line(sLine);
1975  TString aclicMode;
1976  TString arguments;
1977  TString io;
1978  TString fname = gSystem->SplitAclicMode(sLine.Data() + 3,
1979  aclicMode, arguments, io);
1980  if (aclicMode.Length()) {
1981  // Remove the leading '+'
1982  R__ASSERT(aclicMode[0]=='+' && "ACLiC mode must start with a +");
1983  aclicMode[0]='k'; // We always want to keep the .so around.
1984  if (aclicMode[1]=='+') {
1985  // We have a 2nd +
1986  aclicMode[1]='f'; // We want to force the recompilation.
1987  }
1988  if (!gSystem->CompileMacro(fname,aclicMode)) {
1989  // ACLiC failed.
1990  compRes = cling::Interpreter::kFailure;
1991  } else {
1992  if (strncmp(sLine.Data(), ".L", 2) != 0) {
1993  // if execution was requested.
1994 
1995  if (arguments.Length()==0) {
1996  arguments = "()";
1997  }
1998  // We need to remove the extension.
1999  Ssiz_t ext = fname.Last('.');
2000  if (ext != kNPOS) {
2001  fname.Remove(ext);
2002  }
2003  const char *function = gSystem->BaseName(fname);
2004  mod_line = function + arguments + io;
2005  cling::MetaProcessor::MaybeRedirectOutputRAII RAII(fMetaProcessor);
2006  indent = HandleInterpreterException(fMetaProcessor, mod_line, compRes, &result);
2007  }
2008  }
2009  } else {
2010  // not ACLiC
2011  size_t unnamedMacroOpenCurly;
2012  {
2013  std::string code;
2014  std::string codeline;
2015  std::ifstream in(fname);
2016  while (in) {
2017  std::getline(in, codeline);
2018  code += codeline + "\n";
2019  }
2020  unnamedMacroOpenCurly
2021  = cling::utils::isUnnamedMacro(code, fInterpreter->getCI()->getLangOpts());
2022  }
2023 
2024  fCurExecutingMacros.push_back(fname);
2025  cling::MetaProcessor::MaybeRedirectOutputRAII RAII(fMetaProcessor);
2026  if (unnamedMacroOpenCurly != std::string::npos) {
2027  compRes = fMetaProcessor->readInputFromFile(fname.Data(), &result,
2028  unnamedMacroOpenCurly);
2029  } else {
2030  // No DynLookup for .x, .L of named macros.
2031  fInterpreter->enableDynamicLookup(false);
2032  indent = HandleInterpreterException(fMetaProcessor, mod_line, compRes, &result);
2033  }
2034  fCurExecutingMacros.pop_back();
2035  }
2036  } // .L / .X / .x
2037  else {
2038  if (0!=strncmp(sLine.Data(), ".autodict ",10) && sLine != ".autodict") {
2039  // explicitly ignore .autodict without having to support it
2040  // in cling.
2041  cling::MetaProcessor::MaybeRedirectOutputRAII RAII(fMetaProcessor);
2042 
2043  // Turn off autoparsing if this is an include directive
2044  bool isInclusionDirective = sLine.Contains("\n#include") || sLine.BeginsWith("#include");
2045  if (isInclusionDirective) {
2046  SuspendAutoParsing autoParseRaii(this);
2047  indent = HandleInterpreterException(fMetaProcessor, sLine, compRes, &result);
2048  } else {
2049  indent = HandleInterpreterException(fMetaProcessor, sLine, compRes, &result);
2050  }
2051  }
2052  }
2053  if (result.isValid())
2054  RegisterTemporary(result);
2055  if (indent) {
2056  if (error)
2057  *error = kProcessing;
2058  return 0;
2059  }
2060  if (error) {
2061  switch (compRes) {
2062  case cling::Interpreter::kSuccess: *error = kNoError; break;
2063  case cling::Interpreter::kFailure: *error = kRecoverable; break;
2064  case cling::Interpreter::kMoreInputExpected: *error = kProcessing; break;
2065  }
2066  }
2067  if (compRes == cling::Interpreter::kSuccess
2068  && result.isValid()
2069  && !result.isVoid())
2070  {
2071  gROOT->SetLineHasBeenProcessed();
2072  return result.simplisticCastAs<long>();
2073  }
2074  gROOT->SetLineHasBeenProcessed();
2075  return 0;
2076 }
2077 
2078 ////////////////////////////////////////////////////////////////////////////////
2079 /// No-op; see TRint instead.
2080 
2082 {
2083 }
2084 
2085 ////////////////////////////////////////////////////////////////////////////////
2086 /// Add the given path to the list of directories in which the interpreter
2087 /// looks for include files. Only one path item can be specified at a
2088 /// time, i.e. "path1:path2" is NOT supported.
2089 
2090 void TCling::AddIncludePath(const char *path)
2091 {
2093  // Favorite source of annoyance: gSystem->AddIncludePath() needs "-I",
2094  // gCling->AddIncludePath() does not! Work around that inconsistency:
2095  if (path[0] == '-' && path[1] == 'I')
2096  path += 2;
2097 
2098  fInterpreter->AddIncludePath(path);
2099 }
2100 
2101 ////////////////////////////////////////////////////////////////////////////////
2102 /// Visit all members over members, recursing over base classes.
2103 
2104 void TCling::InspectMembers(TMemberInspector& insp, const void* obj,
2105  const TClass* cl, Bool_t isTransient)
2106 {
2110  }
2111 
2112  if (!cl || cl->GetCollectionProxy()) {
2113  // We do not need to investigate the content of the STL
2114  // collection, they are opaque to us (and details are
2115  // uninteresting).
2116  return;
2117  }
2118 
2119  static const TClassRef clRefString("std::string");
2120  if (clRefString == cl) {
2121  // We stream std::string without going through members..
2122  return;
2123  }
2124 
2125  if (TClassEdit::IsStdArray(cl->GetName())) {
2126  // We treat std arrays as C arrays
2127  return;
2128  }
2129 
2130  const char* cobj = (const char*) obj; // for ptr arithmetics
2131 
2132  // Treat the case of std::complex in a special manner. We want to enforce
2133  // the layout of a stl implementation independent class, which is the
2134  // complex as implemented in ROOT5.
2135 
2136  // A simple lambda to simplify the code
2137  auto inspInspect = [&] (ptrdiff_t offset){
2138  insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), "_real", cobj, isTransient);
2139  insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), "_imag", cobj + offset, isTransient);
2140  };
2141 
2142  auto complexType = TClassEdit::GetComplexType(cl->GetName());
2143  switch(complexType) {
2145  {
2146  break;
2147  }
2149  {
2150  inspInspect(sizeof(float));
2151  return;
2152  }
2154  {
2155  inspInspect(sizeof(double));
2156  return;
2157  }
2159  {
2160  inspInspect(sizeof(int));
2161  return;
2162  }
2164  {
2165  inspInspect(sizeof(long));
2166  return;
2167  }
2168  }
2169 
2170  static clang::PrintingPolicy
2171  printPol(fInterpreter->getCI()->getLangOpts());
2172  if (printPol.Indentation) {
2173  // not yet initialized
2174  printPol.Indentation = 0;
2175  printPol.SuppressInitializers = true;
2176  }
2177 
2178  const char* clname = cl->GetName();
2179  // Printf("Inspecting class %s\n", clname);
2180 
2181  const clang::ASTContext& astContext = fInterpreter->getCI()->getASTContext();
2182  const clang::Decl *scopeDecl = 0;
2183  const clang::Type *recordType = 0;
2184 
2185  if (cl->GetClassInfo()) {
2186  TClingClassInfo * clingCI = (TClingClassInfo *)cl->GetClassInfo();
2187  scopeDecl = clingCI->GetDecl();
2188  recordType = clingCI->GetType();
2189  } else {
2190  const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
2191  // Diags will complain about private classes:
2192  scopeDecl = lh.findScope(clname, cling::LookupHelper::NoDiagnostics,
2193  &recordType);
2194  }
2195  if (!scopeDecl) {
2196  Error("InspectMembers", "Cannot find Decl for class %s", clname);
2197  return;
2198  }
2199  const clang::CXXRecordDecl* recordDecl
2200  = llvm::dyn_cast<const clang::CXXRecordDecl>(scopeDecl);
2201  if (!recordDecl) {
2202  Error("InspectMembers", "Cannot find Decl for class %s is not a CXXRecordDecl.", clname);
2203  return;
2204  }
2205 
2206  {
2207  // Force possible deserializations first. We need to have no pending
2208  // Transaction when passing control flow to the inspector below (ROOT-7779).
2209  cling::Interpreter::PushTransactionRAII deserRAII(fInterpreter);
2210 
2211  astContext.getASTRecordLayout(recordDecl);
2212 
2213  for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2214  eField = recordDecl->field_end(); iField != eField; ++iField) {}
2215  }
2216 
2217  const clang::ASTRecordLayout& recLayout
2218  = astContext.getASTRecordLayout(recordDecl);
2219 
2220  // TVirtualCollectionProxy *proxy = cl->GetCollectionProxy();
2221  // if (proxy && ( proxy->GetProperties() & TVirtualCollectionProxy::kIsEmulated ) ) {
2222  // Error("InspectMembers","The TClass for %s has an emulated proxy but we are looking at a compiled version of the collection!\n",
2223  // cl->GetName());
2224  // }
2225  if (cl->Size() != recLayout.getSize().getQuantity()) {
2226  Error("InspectMembers","TClass and cling disagree on the size of the class %s, respectively %d %lld\n",
2227  cl->GetName(),cl->Size(),(Long64_t)recLayout.getSize().getQuantity());
2228  }
2229 
2230  unsigned iNField = 0;
2231  // iterate over fields
2232  // FieldDecls are non-static, else it would be a VarDecl.
2233  for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2234  eField = recordDecl->field_end(); iField != eField;
2235  ++iField, ++iNField) {
2236 
2237 
2238  clang::QualType memberQT = iField->getType();
2239  if (recordType) {
2240  // if (we_need_to_do_the_subst_because_the_class_is_a_template_instance_of_double32_t)
2241  memberQT = ROOT::TMetaUtils::ReSubstTemplateArg(memberQT, recordType);
2242  }
2243  memberQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, memberQT, fNormalizedCtxt->GetConfig(), false /* fully qualify */);
2244  if (memberQT.isNull()) {
2245  std::string memberName;
2246  llvm::raw_string_ostream stream(memberName);
2247  // Don't trigger fopen of the source file to count lines:
2248  printPol.AnonymousTagLocations = false;
2249  iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2250  stream.flush();
2251  Error("InspectMembers",
2252  "Cannot retrieve QualType for member %s while inspecting class %s",
2253  memberName.c_str(), clname);
2254  continue; // skip member
2255  }
2256  const clang::Type* memType = memberQT.getTypePtr();
2257  if (!memType) {
2258  std::string memberName;
2259  llvm::raw_string_ostream stream(memberName);
2260  // Don't trigger fopen of the source file to count lines:
2261  printPol.AnonymousTagLocations = false;
2262  iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2263  stream.flush();
2264  Error("InspectMembers",
2265  "Cannot retrieve Type for member %s while inspecting class %s",
2266  memberName.c_str(), clname);
2267  continue; // skip member
2268  }
2269 
2270  const clang::Type* memNonPtrType = memType;
2271  Bool_t ispointer = false;
2272  if (memNonPtrType->isPointerType()) {
2273  ispointer = true;
2274  clang::QualType ptrQT
2275  = memNonPtrType->getAs<clang::PointerType>()->getPointeeType();
2276  if (recordType) {
2277  // if (we_need_to_do_the_subst_because_the_class_is_a_template_instance_of_double32_t)
2278  ptrQT = ROOT::TMetaUtils::ReSubstTemplateArg(ptrQT, recordType);
2279  }
2280  ptrQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, ptrQT, fNormalizedCtxt->GetConfig(), false /* fully qualify */);
2281  if (ptrQT.isNull()) {
2282  std::string memberName;
2283  llvm::raw_string_ostream stream(memberName);
2284  // Don't trigger fopen of the source file to count lines:
2285  printPol.AnonymousTagLocations = false;
2286  iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2287  stream.flush();
2288  Error("InspectMembers",
2289  "Cannot retrieve pointee Type for member %s while inspecting class %s",
2290  memberName.c_str(), clname);
2291  continue; // skip member
2292  }
2293  memNonPtrType = ptrQT.getTypePtr();
2294  }
2295 
2296  // assemble array size(s): "[12][4][]"
2297  llvm::SmallString<8> arraySize;
2298  const clang::ArrayType* arrType = memNonPtrType->getAsArrayTypeUnsafe();
2299  unsigned arrLevel = 0;
2300  bool haveErrorDueToArray = false;
2301  while (arrType) {
2302  ++arrLevel;
2303  arraySize += '[';
2304  const clang::ConstantArrayType* constArrType =
2305  clang::dyn_cast<clang::ConstantArrayType>(arrType);
2306  if (constArrType) {
2307  constArrType->getSize().toStringUnsigned(arraySize);
2308  }
2309  arraySize += ']';
2310  clang::QualType subArrQT = arrType->getElementType();
2311  if (subArrQT.isNull()) {
2312  std::string memberName;
2313  llvm::raw_string_ostream stream(memberName);
2314  // Don't trigger fopen of the source file to count lines:
2315  printPol.AnonymousTagLocations = false;
2316  iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2317  stream.flush();
2318  Error("InspectMembers",
2319  "Cannot retrieve QualType for array level %d (i.e. element type of %s) for member %s while inspecting class %s",
2320  arrLevel, subArrQT.getAsString(printPol).c_str(),
2321  memberName.c_str(), clname);
2322  haveErrorDueToArray = true;
2323  break;
2324  }
2325  arrType = subArrQT.getTypePtr()->getAsArrayTypeUnsafe();
2326  }
2327  if (haveErrorDueToArray) {
2328  continue; // skip member
2329  }
2330 
2331  // construct member name
2332  std::string fieldName;
2333  if (memType->isPointerType()) {
2334  fieldName = "*";
2335  }
2336 
2337  // Check if this field has a custom ioname, if not, just use the one of the decl
2338  std::string ioname(iField->getName());
2340  fieldName += ioname;
2341  fieldName += arraySize;
2342 
2343  // get member offset
2344  // NOTE currently we do not support bitfield and do not support
2345  // member that are not aligned on 'bit' boundaries.
2346  clang::CharUnits offset(astContext.toCharUnitsFromBits(recLayout.getFieldOffset(iNField)));
2347  ptrdiff_t fieldOffset = offset.getQuantity();
2348 
2349  // R__insp.Inspect(R__cl, R__insp.GetParent(), "fBits[2]", fBits);
2350  // R__insp.Inspect(R__cl, R__insp.GetParent(), "fName", &fName);
2351  // R__insp.InspectMember(fName, "fName.");
2352  // R__insp.Inspect(R__cl, R__insp.GetParent(), "*fClass", &fClass);
2353 
2354  // If the class has a custom streamer and the type of the filed is a
2355  // private enum, struct or class, skip it.
2356  if (!insp.IsTreatingNonAccessibleTypes()){
2357  auto iFiledQtype = iField->getType();
2358  if (auto tagDecl = iFiledQtype->getAsTagDecl()){
2359  auto declAccess = tagDecl->getAccess();
2360  if (declAccess == AS_private || declAccess == AS_protected) {
2361  continue;
2362  }
2363  }
2364  }
2365 
2366  insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), fieldName.c_str(), cobj + fieldOffset, isTransient);
2367 
2368  if (!ispointer) {
2369  const clang::CXXRecordDecl* fieldRecDecl = memNonPtrType->getAsCXXRecordDecl();
2370  if (fieldRecDecl) {
2371  // nested objects get an extra call to InspectMember
2372  // R__insp.InspectMember("FileStat_t", (void*)&fFileStat, "fFileStat.", false);
2373  std::string sFieldRecName;
2374  if (!ROOT::TMetaUtils::ExtractAttrPropertyFromName(*fieldRecDecl,"iotype",sFieldRecName)){
2376  clang::QualType(memNonPtrType,0),
2377  *fInterpreter,
2378  *fNormalizedCtxt);
2379  }
2380 
2381  TDataMember* mbr = cl->GetDataMember(ioname.c_str());
2382  // if we can not find the member (which should not really happen),
2383  // let's consider it transient.
2384  Bool_t transient = isTransient || !mbr || !mbr->IsPersistent();
2385 
2386  insp.InspectMember(sFieldRecName.c_str(), cobj + fieldOffset,
2387  (fieldName + '.').c_str(), transient);
2388 
2389  }
2390  }
2391  } // loop over fields
2392 
2393  // inspect bases
2394  // TNamed::ShowMembers(R__insp);
2395  unsigned iNBase = 0;
2396  for (clang::CXXRecordDecl::base_class_const_iterator iBase
2397  = recordDecl->bases_begin(), eBase = recordDecl->bases_end();
2398  iBase != eBase; ++iBase, ++iNBase) {
2399  clang::QualType baseQT = iBase->getType();
2400  if (baseQT.isNull()) {
2401  Error("InspectMembers",
2402  "Cannot find QualType for base number %d while inspecting class %s",
2403  iNBase, clname);
2404  continue;
2405  }
2406  const clang::CXXRecordDecl* baseDecl
2407  = baseQT->getAsCXXRecordDecl();
2408  if (!baseDecl) {
2409  Error("InspectMembers",
2410  "Cannot find CXXRecordDecl for base number %d while inspecting class %s",
2411  iNBase, clname);
2412  continue;
2413  }
2414  TClass* baseCl=nullptr;
2415  std::string sBaseName;
2416  // Try with the DeclId
2417  std::vector<TClass*> foundClasses;
2418  TClass::GetClass(static_cast<DeclId_t>(baseDecl), foundClasses);
2419  if (foundClasses.size()==1){
2420  baseCl=foundClasses[0];
2421  } else {
2422  // Try with the normalised Name, as a fallback
2423  if (!baseCl){
2425  baseQT,
2426  *fInterpreter,
2427  *fNormalizedCtxt);
2428  baseCl = TClass::GetClass(sBaseName.c_str());
2429  }
2430  }
2431 
2432  if (!baseCl){
2433  std::string qualNameForDiag;
2434  ROOT::TMetaUtils::GetQualifiedName(qualNameForDiag, *baseDecl);
2435  Error("InspectMembers",
2436  "Cannot find TClass for base class %s", qualNameForDiag.c_str() );
2437  continue;
2438  }
2439 
2440  int64_t baseOffset;
2441  if (iBase->isVirtual()) {
2443  if (!isTransient) {
2444  Error("InspectMembers",
2445  "Base %s of class %s is virtual but no object provided",
2446  sBaseName.c_str(), clname);
2447  }
2449  } else {
2450  // We have an object to determine the vbase offset.
2452  TClingClassInfo* baseCi = (TClingClassInfo*)baseCl->GetClassInfo();
2453  if (ci && baseCi) {
2454  baseOffset = ci->GetBaseOffset(baseCi, const_cast<void*>(obj),
2455  true /*isDerivedObj*/);
2456  if (baseOffset == -1) {
2457  Error("InspectMembers",
2458  "Error calculating offset of virtual base %s of class %s",
2459  sBaseName.c_str(), clname);
2460  }
2461  } else {
2462  Error("InspectMembers",
2463  "Cannot calculate offset of virtual base %s of class %s",
2464  sBaseName.c_str(), clname);
2465  continue;
2466  }
2467  }
2468  } else {
2469  baseOffset = recLayout.getBaseClassOffset(baseDecl).getQuantity();
2470  }
2471  // TOFIX: baseCl can be null here!
2472  if (baseCl->IsLoaded()) {
2473  // For loaded class, CallShowMember will (especially for TObject)
2474  // call the virtual ShowMember rather than the class specific version
2475  // resulting in an infinite recursion.
2476  InspectMembers(insp, cobj + baseOffset, baseCl, isTransient);
2477  } else {
2478  baseCl->CallShowMembers(cobj + baseOffset,
2479  insp, isTransient);
2480  }
2481  } // loop over bases
2482 }
2483 
2484 ////////////////////////////////////////////////////////////////////////////////
2485 /// Reset the interpreter internal state in case a previous action was not correctly
2486 /// terminated.
2487 
2489 {
2490  // No-op there is not equivalent state (to be cleared) in Cling.
2491 }
2492 
2493 ////////////////////////////////////////////////////////////////////////////////
2494 /// Delete existing temporary values.
2495 
2497 {
2498  // No-op for cling due to cling::Value.
2499 }
2500 
2501 ////////////////////////////////////////////////////////////////////////////////
2502 /// Declare code to the interpreter, without any of the interpreter actions
2503 /// that could trigger a re-interpretation of the code. I.e. make cling
2504 /// behave like a compiler: no dynamic lookup, no input wrapping for
2505 /// subsequent execution, no automatic provision of declarations but just a
2506 /// plain #include.
2507 /// Returns true on success, false on failure.
2508 
2509 bool TCling::Declare(const char* code)
2510 {
2512 
2513  int oldload = SetClassAutoloading(0);
2514  SuspendAutoParsing autoParseRaii(this);
2515 
2516  bool oldDynLookup = fInterpreter->isDynamicLookupEnabled();
2517  fInterpreter->enableDynamicLookup(false);
2518  bool oldRawInput = fInterpreter->isRawInputEnabled();
2519  fInterpreter->enableRawInput(true);
2520 
2521  Bool_t ret = LoadText(code);
2522 
2523  fInterpreter->enableRawInput(oldRawInput);
2524  fInterpreter->enableDynamicLookup(oldDynLookup);
2525  SetClassAutoloading(oldload);
2526  return ret;
2527 }
2528 
2529 ////////////////////////////////////////////////////////////////////////////////
2530 /// Enable the automatic loading of shared libraries when a class
2531 /// is used that is stored in a not yet loaded library. Uses the
2532 /// information stored in the class/library map (typically
2533 /// $ROOTSYS/etc/system.rootmap).
2534 
2536 {
2537  if (fAllowLibLoad) {
2538  LoadLibraryMap();
2539  SetClassAutoloading(true);
2540  }
2541 }
2542 
2543 ////////////////////////////////////////////////////////////////////////////////
2544 /// It calls a "fantom" method to synchronize user keyboard input
2545 /// and ROOT prompt line.
2546 
2548 {
2550 }
2551 
2552 ////////////////////////////////////////////////////////////////////////////////
2553 /// Return true if the file has already been loaded by cint.
2554 /// We will try in this order:
2555 /// actual filename
2556 /// filename as a path relative to
2557 /// the include path
2558 /// the shared library path
2559 
2560 Bool_t TCling::IsLoaded(const char* filename) const
2561 {
2563 
2564  //FIXME: if we use llvm::sys::fs::make_absolute all this can go away. See
2565  // cling::DynamicLibraryManager.
2566 
2567  std::string file_name = filename;
2568  size_t at = std::string::npos;
2569  while ((at = file_name.find("/./")) != std::string::npos)
2570  file_name.replace(at, 3, "/");
2571 
2572  std::string filesStr = "";
2573  llvm::raw_string_ostream filesOS(filesStr);
2574  clang::SourceManager &SM = fInterpreter->getCI()->getSourceManager();
2575  cling::ClangInternalState::printIncludedFiles(filesOS, SM);
2576  filesOS.flush();
2577 
2578  llvm::SmallVector<llvm::StringRef, 100> files;
2579  llvm::StringRef(filesStr).split(files, "\n");
2580 
2581  std::set<std::string> fileMap;
2582  // Fill fileMap; return early on exact match.
2583  for (llvm::SmallVector<llvm::StringRef, 100>::const_iterator
2584  iF = files.begin(), iE = files.end(); iF != iE; ++iF) {
2585  if ((*iF) == file_name.c_str()) return kTRUE; // exact match
2586  fileMap.insert(*iF);
2587  }
2588 
2589  if (fileMap.empty()) return kFALSE;
2590 
2591  // Check MacroPath.
2592  TString sFilename(file_name.c_str());
2594  && fileMap.count(sFilename.Data())) {
2595  return kTRUE;
2596  }
2597 
2598  // Check IncludePath.
2599  TString incPath = gSystem->GetIncludePath(); // of the form -Idir1 -Idir2 -Idir3
2600  incPath.Append(":").Prepend(" "); // to match " -I" (note leading ' ')
2601  incPath.ReplaceAll(" -I", ":"); // of form :dir1 :dir2:dir3
2602  while (incPath.Index(" :") != -1) {
2603  incPath.ReplaceAll(" :", ":");
2604  }
2605  incPath.Prepend(".:");
2606  sFilename = file_name.c_str();
2607  if (gSystem->FindFile(incPath, sFilename, kReadPermission)
2608  && fileMap.count(sFilename.Data())) {
2609  return kTRUE;
2610  }
2611 
2612  // Check shared library.
2613  sFilename = file_name.c_str();
2614  const char *found = gSystem->FindDynamicLibrary(sFilename, kTRUE);
2615  cling::DynamicLibraryManager* dyLibManager
2616  = fInterpreter->getDynamicLibraryManager();
2617  if (found) {
2618  if (dyLibManager->isLibraryLoaded(found)) {
2619  return kTRUE;
2620  }
2621  }
2622  //FIXME: We must use the cling::Interpreter::lookupFileOrLibrary iface.
2623  const clang::DirectoryLookup *CurDir = 0;
2624  clang::Preprocessor &PP = fInterpreter->getCI()->getPreprocessor();
2625  clang::HeaderSearch &HS = PP.getHeaderSearchInfo();
2626  const clang::FileEntry *FE = HS.LookupFile(file_name.c_str(),
2627  clang::SourceLocation(),
2628  /*isAngled*/ false,
2629  /*FromDir*/ 0, CurDir,
2630  clang::ArrayRef<std::pair<const clang::FileEntry *,
2631  const clang::DirectoryEntry *>>(),
2632  /*SearchPath*/ 0,
2633  /*RelativePath*/ 0,
2634  /*RequestingModule*/ 0,
2635  /*SuggestedModule*/ 0,
2636  /*SkipCache*/ false,
2637  /*BuildSystemModule*/ false,
2638  /*OpenFile*/ false,
2639  /*CacheFail*/ false);
2640  if (FE && FE->isValid()) {
2641  // check in the source manager if the file is actually loaded
2642  clang::SourceManager &SM = fInterpreter->getCI()->getSourceManager();
2643  // this works only with header (and source) files...
2644  clang::FileID FID = SM.translateFile(FE);
2645  if (!FID.isInvalid() && FID.getHashValue() == 0)
2646  return kFALSE;
2647  else {
2648  clang::SrcMgr::SLocEntry SLocE = SM.getSLocEntry(FID);
2649  if (SLocE.isFile() && SLocE.getFile().getContentCache()->getRawBuffer() == 0)
2650  return kFALSE;
2651  if (!FID.isInvalid())
2652  return kTRUE;
2653  }
2654  // ...then check shared library again, but with full path now
2655  sFilename = FE->getName();
2656  if (gSystem->FindDynamicLibrary(sFilename, kTRUE)
2657  && fileMap.count(sFilename.Data())) {
2658  return kTRUE;
2659  }
2660  }
2661  return kFALSE;
2662 }
2663 
2664 ////////////////////////////////////////////////////////////////////////////////
2665 
2667 {
2668 #if defined(R__WIN32) || defined(__CYGWIN__)
2669  HMODULE hModules[1024];
2670  void *hProcess;
2671  unsigned long cbModules;
2672  unsigned int i;
2673  hProcess = (void *)::GetCurrentProcess();
2674  ::EnumProcessModules(hProcess, hModules, sizeof(hModules), &cbModules);
2675  // start at 1 to skip the executable itself
2676  for (i = 1; i < (cbModules / sizeof(void *)); i++) {
2677  static const int bufsize = 260;
2678  wchar_t winname[bufsize];
2679  char posixname[bufsize];
2680  ::GetModuleFileNameExW(hProcess, hModules[i], winname, bufsize);
2681 #if defined(__CYGWIN__)
2682  cygwin_conv_path(CCP_WIN_W_TO_POSIX, winname, posixname, bufsize);
2683 #else
2684  std::wstring wpath = winname;
2685  std::replace(wpath.begin(), wpath.end(), '\\', '/');
2686  string path(wpath.begin(), wpath.end());
2687  strncpy(posixname, path.c_str(), bufsize);
2688 #endif
2689  if (!fSharedLibs.Contains(posixname)) {
2690  RegisterLoadedSharedLibrary(posixname);
2691  }
2692  }
2693 #elif defined(R__MACOSX)
2694  // fPrevLoadedDynLibInfo stores the *next* image index to look at
2695  uint32_t imageIndex = (uint32_t) (size_t) fPrevLoadedDynLibInfo;
2696 
2697  while (const mach_header* mh = _dyld_get_image_header(imageIndex)) {
2698  // Skip non-dylibs
2699  if (mh->filetype == MH_DYLIB) {
2700  if (const char* imageName = _dyld_get_image_name(imageIndex)) {
2701  RegisterLoadedSharedLibrary(imageName);
2702  }
2703  }
2704 
2705  ++imageIndex;
2706  }
2707  fPrevLoadedDynLibInfo = (void*)(size_t)imageIndex;
2708 #elif defined(R__LINUX)
2709  struct PointerNo4 {
2710  void* fSkip[3];
2711  void* fPtr;
2712  };
2713  struct LinkMap {
2714  void* fAddr;
2715  const char* fName;
2716  void* fLd;
2717  LinkMap* fNext;
2718  LinkMap* fPrev;
2719  };
2720  if (!fPrevLoadedDynLibInfo || fPrevLoadedDynLibInfo == (void*)(size_t)-1) {
2721  PointerNo4* procLinkMap = (PointerNo4*)dlopen(0, RTLD_LAZY | RTLD_GLOBAL);
2722  // 4th pointer of 4th pointer is the linkmap.
2723  // See http://syprog.blogspot.fr/2011/12/listing-loaded-shared-objects-in-linux.html
2724  LinkMap* linkMap = (LinkMap*) ((PointerNo4*)procLinkMap->fPtr)->fPtr;
2725  RegisterLoadedSharedLibrary(linkMap->fName);
2726  fPrevLoadedDynLibInfo = linkMap;
2727  // reduce use count of link map structure:
2728  dlclose(procLinkMap);
2729  }
2730 
2731  LinkMap* iDyLib = (LinkMap*)fPrevLoadedDynLibInfo;
2732  while (iDyLib->fNext) {
2733  iDyLib = iDyLib->fNext;
2734  RegisterLoadedSharedLibrary(iDyLib->fName);
2735  }
2736  fPrevLoadedDynLibInfo = iDyLib;
2737 #else
2738  Error("TCling::UpdateListOfLoadedSharedLibraries",
2739  "Platform not supported!");
2740 #endif
2741 }
2742 
2743 ////////////////////////////////////////////////////////////////////////////////
2744 /// Register a new shared library name with the interpreter; add it to
2745 /// fSharedLibs.
2746 
2747 void TCling::RegisterLoadedSharedLibrary(const char* filename)
2748 {
2749  // Ignore NULL filenames, aka "the process".
2750  if (!filename) return;
2751 
2752  // Tell the interpreter that this library is available; all libraries can be
2753  // used to resolve symbols.
2754  cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
2755  if (!DLM->isLibraryLoaded(filename)) {
2756  DLM->loadLibrary(filename, true /*permanent*/);
2757  }
2758 
2759 #if defined(R__MACOSX)
2760  // Check that this is not a system library
2761  if (!strncmp(filename, "/usr/lib/system/", 16)
2762  || !strncmp(filename, "/usr/lib/libc++", 15)
2763  || !strncmp(filename, "/System/Library/Frameworks/", 27)
2764  || !strncmp(filename, "/System/Library/PrivateFrameworks/", 34)
2765  || !strncmp(filename, "/System/Library/CoreServices/", 29)
2766  || !strcmp(filename, "cl_kernels") // yepp, no directory
2767  || strstr(filename, "/usr/lib/libSystem")
2768  || strstr(filename, "/usr/lib/libstdc++")
2769  || strstr(filename, "/usr/lib/libicucore")
2770  || strstr(filename, "/usr/lib/libbsm")
2771  || strstr(filename, "/usr/lib/libobjc")
2772  || strstr(filename, "/usr/lib/libresolv")
2773  || strstr(filename, "/usr/lib/libauto")
2774  || strstr(filename, "/usr/lib/libcups")
2775  || strstr(filename, "/usr/lib/libDiagnosticMessagesClient")
2776  || strstr(filename, "/usr/lib/liblangid")
2777  || strstr(filename, "/usr/lib/libCRFSuite")
2778  || strstr(filename, "/usr/lib/libpam")
2779  || strstr(filename, "/usr/lib/libOpenScriptingUtil")
2780  || strstr(filename, "/usr/lib/libextension"))
2781  return;
2782 #elif defined(__CYGWIN__)
2783  // Check that this is not a system library
2784  static const int bufsize = 260;
2785  char posixwindir[bufsize];
2786  char *windir = getenv("WINDIR");
2787  if (windir)
2788  cygwin_conv_path(CCP_WIN_A_TO_POSIX, windir, posixwindir, bufsize);
2789  else
2790  snprintf(posixwindir, sizeof(posixwindir), "/Windows/");
2791  if (strstr(filename, posixwindir) ||
2792  strstr(filename, "/usr/bin/cyg"))
2793  return;
2794 #elif defined(R__WIN32)
2795  if (strstr(filename, "/Windows/"))
2796  return;
2797 #elif defined (R__LINUX)
2798  if (strstr(filename, "/ld-linux")
2799  || strstr(filename, "linux-gnu/")
2800  || strstr(filename, "/libstdc++.")
2801  || strstr(filename, "/libgcc")
2802  || strstr(filename, "/libc.")
2803  || strstr(filename, "/libdl.")
2804  || strstr(filename, "/libm."))
2805  return;
2806 #endif
2807  // Update string of available libraries.
2808  if (!fSharedLibs.IsNull()) {
2809  fSharedLibs.Append(" ");
2810  }
2811  fSharedLibs.Append(filename);
2812 }
2813 
2814 ////////////////////////////////////////////////////////////////////////////////
2815 /// Load a library file in cling's memory.
2816 /// if 'system' is true, the library is never unloaded.
2817 /// Return 0 on success, -1 on failure.
2818 
2819 Int_t TCling::Load(const char* filename, Bool_t system)
2820 {
2821  if (!fAllowLibLoad) {
2822  Error("Load","Trying to load library (%s) from rootcling.",filename);
2823  return -1;
2824  }
2825 
2826  // Used to return 0 on success, 1 on duplicate, -1 on failure, -2 on "fatal".
2828  cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
2829  std::string canonLib = DLM->lookupLibrary(filename);
2830  cling::DynamicLibraryManager::LoadLibResult res
2831  = cling::DynamicLibraryManager::kLoadLibNotFound;
2832  if (!canonLib.empty()) {
2833  if (system)
2834  res = DLM->loadLibrary(filename, system);
2835  else {
2836  // For the non system libs, we'd like to be able to unload them.
2837  // FIXME: Here we lose the information about kLoadLibAlreadyLoaded case.
2838  cling::Interpreter::CompilationResult compRes;
2839  cling::MetaProcessor::MaybeRedirectOutputRAII RAII(fMetaProcessor);
2840  HandleInterpreterException(fMetaProcessor, Form(".L %s", canonLib.c_str()), compRes, /*cling::Value*/0);
2841  if (compRes == cling::Interpreter::kSuccess)
2842  res = cling::DynamicLibraryManager::kLoadLibSuccess;
2843  }
2844  }
2845 
2846  if (res == cling::DynamicLibraryManager::kLoadLibSuccess) {
2848  }
2849  switch (res) {
2850  case cling::DynamicLibraryManager::kLoadLibSuccess: return 0;
2851  case cling::DynamicLibraryManager::kLoadLibAlreadyLoaded: return 1;
2852  default: break;
2853  };
2854  return -1;
2855 }
2856 
2857 ////////////////////////////////////////////////////////////////////////////////
2858 /// Load a macro file in cling's memory.
2859 
2860 void TCling::LoadMacro(const char* filename, EErrorCode* error)
2861 {
2862  ProcessLine(Form(".L %s", filename), error);
2863 }
2864 
2865 ////////////////////////////////////////////////////////////////////////////////
2866 /// Let cling process a command line asynch.
2867 
2869 {
2870  return ProcessLine(line, error);
2871 }
2872 
2873 ////////////////////////////////////////////////////////////////////////////////
2874 /// Let cling process a command line synchronously, i.e we are waiting
2875 /// it will be finished.
2876 
2878 {
2880  if (gApplication) {
2881  if (gApplication->IsCmdThread()) {
2882  return ProcessLine(line, error);
2883  }
2884  return 0;
2885  }
2886  return ProcessLine(line, error);
2887 }
2888 
2889 ////////////////////////////////////////////////////////////////////////////////
2890 /// Directly execute an executable statement (e.g. "func()", "3+5", etc.
2891 /// however not declarations, like "Int_t x;").
2892 
2893 Long_t TCling::Calc(const char* line, EErrorCode* error)
2894 {
2895 #ifdef R__WIN32
2896  // Test on ApplicationImp not being 0 is needed because only at end of
2897  // TApplication ctor the IsLineProcessing flag is set to 0, so before
2898  // we can not use it.
2900  while (gROOT->IsLineProcessing() && !gApplication) {
2901  Warning("Calc", "waiting for cling thread to free");
2902  gSystem->Sleep(500);
2903  }
2904  gROOT->SetLineIsProcessing();
2905  }
2906 #endif // R__WIN32
2908  if (error) {
2909  *error = TInterpreter::kNoError;
2910  }
2911  cling::Value valRef;
2912  cling::Interpreter::CompilationResult cr = fInterpreter->evaluate(line, valRef);
2913  if (cr != cling::Interpreter::kSuccess) {
2914  // Failure in compilation.
2915  if (error) {
2916  // Note: Yes these codes are weird.
2917  *error = TInterpreter::kRecoverable;
2918  }
2919  return 0L;
2920  }
2921  if (!valRef.isValid()) {
2922  // Failure at runtime.
2923  if (error) {
2924  // Note: Yes these codes are weird.
2925  *error = TInterpreter::kDangerous;
2926  }
2927  return 0L;
2928  }
2929 
2930  if (valRef.isVoid()) {
2931  return 0;
2932  }
2933 
2934  RegisterTemporary(valRef);
2935 #ifdef R__WIN32
2937  gROOT->SetLineHasBeenProcessed();
2938  }
2939 #endif // R__WIN32
2940  return valRef.simplisticCastAs<long>();
2941 }
2942 
2943 ////////////////////////////////////////////////////////////////////////////////
2944 /// Set a getline function to call when input is needed.
2945 
2946 void TCling::SetGetline(const char * (*getlineFunc)(const char* prompt),
2947  void (*histaddFunc)(const char* line))
2948 {
2949  // If cling offers a replacement for G__pause(), it would need to
2950  // also offer a way to customize at least the history recording.
2951 
2952 #if defined(R__MUST_REVISIT)
2953 #if R__MUST_REVISIT(6,2)
2954  Warning("SetGetline","Cling should support the equivalent of SetGetlineFunc(getlineFunc, histaddFunc)");
2955 #endif
2956 #endif
2957 }
2958 
2959 ////////////////////////////////////////////////////////////////////////////////
2960 /// Helper function to increase the internal Cling count of transactions
2961 /// that change the AST.
2962 
2963 Bool_t TCling::HandleNewTransaction(const cling::Transaction &T)
2964 {
2966 
2967  if ((std::distance(T.decls_begin(), T.decls_end()) != 1)
2968  || T.deserialized_decls_begin() != T.deserialized_decls_end()
2969  || T.macros_begin() != T.macros_end()
2970  || ((!T.getFirstDecl().isNull()) && ((*T.getFirstDecl().begin()) != T.getWrapperFD()))) {
2972  return true;
2973  }
2974  return false;
2975 }
2976 
2977 ////////////////////////////////////////////////////////////////////////////////
2978 /// Delete object from cling symbol table so it can not be used anymore.
2979 /// cling objects are always on the heap.
2980 
2982 {
2984  // Note that fgSetOfSpecials is supposed to be updated by TClingCallbacks::tryFindROOTSpecialInternal
2985  // (but isn't at the moment).
2986  if (obj->IsOnHeap() && fgSetOfSpecials && !((std::set<TObject*>*)fgSetOfSpecials)->empty()) {
2987  std::set<TObject*>::iterator iSpecial = ((std::set<TObject*>*)fgSetOfSpecials)->find(obj);
2988  if (iSpecial != ((std::set<TObject*>*)fgSetOfSpecials)->end()) {
2989  DeleteGlobal(obj);
2990  ((std::set<TObject*>*)fgSetOfSpecials)->erase(iSpecial);
2991  }
2992  }
2993 }
2994 
2995 ////////////////////////////////////////////////////////////////////////////////
2996 /// Pressing Ctrl+C should forward here. In the case where we have had
2997 /// continuation requested we must reset it.
2998 
3000 {
3001  fMetaProcessor->cancelContinuation();
3002  // Reset the Cling state to the state saved by the last call to
3003  // TCling::SaveContext().
3004 #if defined(R__MUST_REVISIT)
3005 #if R__MUST_REVISIT(6,2)
3007  Warning("Reset","Cling should support the equivalent of scratch_upto(&fDictPos)");
3008 #endif
3009 #endif
3010 }
3011 
3012 ////////////////////////////////////////////////////////////////////////////////
3013 /// Reset the Cling state to its initial state.
3014 
3016 {
3017 #if defined(R__MUST_REVISIT)
3018 #if R__MUST_REVISIT(6,2)
3020  Warning("ResetAll","Cling should support the equivalent of complete reset (unload everything but the startup decls.");
3021 #endif
3022 #endif
3023 }
3024 
3025 ////////////////////////////////////////////////////////////////////////////////
3026 /// Reset in Cling the list of global variables to the state saved by the last
3027 /// call to TCling::SaveGlobalsContext().
3028 ///
3029 /// Note: Right now, all we do is run the global destructors.
3030 
3032 {
3034  // TODO:
3035  // Here we should iterate over the transactions (N-3) and revert.
3036  // N-3 because the first three internal to cling.
3037 
3038  fInterpreter->runAndRemoveStaticDestructors();
3039 }
3040 
3041 ////////////////////////////////////////////////////////////////////////////////
3042 /// Reset the Cling 'user' global objects/variables state to the state saved by the last
3043 /// call to TCling::SaveGlobalsContext().
3044 
3045 void TCling::ResetGlobalVar(void* obj)
3046 {
3047 #if defined(R__MUST_REVISIT)
3048 #if R__MUST_REVISIT(6,2)
3050  Warning("ResetGlobalVar","Cling should support the equivalent of resetglobalvar(obj)");
3051 #endif
3052 #endif
3053 }
3054 
3055 ////////////////////////////////////////////////////////////////////////////////
3056 /// Rewind Cling dictionary to the point where it was before executing
3057 /// the current macro. This function is typically called after SEGV or
3058 /// ctlr-C after doing a longjmp back to the prompt.
3059 
3061 {
3062 #if defined(R__MUST_REVISIT)
3063 #if R__MUST_REVISIT(6,2)
3065  Warning("RewindDictionary","Cling should provide a way to revert transaction similar to rewinddictionary()");
3066 #endif
3067 #endif
3068 }
3069 
3070 ////////////////////////////////////////////////////////////////////////////////
3071 /// Delete obj from Cling symbol table so it cannot be accessed anymore.
3072 /// Returns 1 in case of success and 0 in case object was not in table.
3073 
3075 {
3076 #if defined(R__MUST_REVISIT)
3077 #if R__MUST_REVISIT(6,2)
3079  Warning("DeleteGlobal","Cling should provide the equivalent of deleteglobal(obj), see also DeleteVariable.");
3080 #endif
3081 #endif
3082  return 0;
3083 }
3084 
3085 ////////////////////////////////////////////////////////////////////////////////
3086 /// Undeclare obj called name.
3087 /// Returns 1 in case of success, 0 for failure.
3088 
3090 {
3091 #if defined(R__MUST_REVISIT)
3092 #if R__MUST_REVISIT(6,2)
3093  Warning("DeleteVariable","should do more that just reseting the value to zero");
3094 #endif
3095 #endif
3096 
3098  llvm::StringRef srName(name);
3099  const char* unscopedName = name;
3100  llvm::StringRef::size_type posScope = srName.rfind("::");
3101  const clang::DeclContext* declCtx = 0;
3102  if (posScope != llvm::StringRef::npos) {
3103  const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
3104  const clang::Decl* scopeDecl
3105  = lh.findScope(srName.substr(0, posScope),
3106  cling::LookupHelper::WithDiagnostics);
3107  if (!scopeDecl) {
3108  Error("DeleteVariable", "Cannot find enclosing scope for variable %s",
3109  name);
3110  return 0;
3111  }
3112  declCtx = llvm::dyn_cast<clang::DeclContext>(scopeDecl);
3113  if (!declCtx) {
3114  Error("DeleteVariable",
3115  "Enclosing scope for variable %s is not a declaration context",
3116  name);
3117  return 0;
3118  }
3119  unscopedName += posScope + 2;
3120  }
3121  clang::NamedDecl* nVarDecl
3122  = cling::utils::Lookup::Named(&fInterpreter->getSema(), unscopedName, declCtx);
3123  if (!nVarDecl) {
3124  Error("DeleteVariable", "Unknown variable %s", name);
3125  return 0;
3126  }
3127  clang::VarDecl* varDecl = llvm::dyn_cast<clang::VarDecl>(nVarDecl);
3128  if (!varDecl) {
3129  Error("DeleteVariable", "Entity %s is not a variable", name);
3130  return 0;
3131  }
3132 
3133  clang::QualType qType = varDecl->getType();
3134  const clang::Type* type = qType->getUnqualifiedDesugaredType();
3135  // Cannot set a reference's address to nullptr; the JIT can place it
3136  // into read-only memory (ROOT-7100).
3137  if (type->isPointerType()) {
3138  int** ppInt = (int**)fInterpreter->getAddressOfGlobal(GlobalDecl(varDecl));
3139  // set pointer to invalid.
3140  if (ppInt) *ppInt = 0;
3141  }
3142  return 1;
3143 }
3144 
3145 ////////////////////////////////////////////////////////////////////////////////
3146 /// Save the current Cling state.
3147 
3149 {
3150 #if defined(R__MUST_REVISIT)
3151 #if R__MUST_REVISIT(6,2)
3153  Warning("SaveContext","Cling should provide a way to record a state watermark similar to store_dictposition(&fDictPos)");
3154 #endif
3155 #endif
3156 }
3157 
3158 ////////////////////////////////////////////////////////////////////////////////
3159 /// Save the current Cling state of global objects.
3160 
3162 {
3163 #if defined(R__MUST_REVISIT)
3164 #if R__MUST_REVISIT(6,2)
3166  Warning("SaveGlobalsContext","Cling should provide a way to record a watermark for the list of global variable similar to store_dictposition(&fDictPosGlobals)");
3167 #endif
3168 #endif
3169 }
3170 
3171 ////////////////////////////////////////////////////////////////////////////////
3172 /// No op: see TClingCallbacks (used to update the list of globals)
3173 
3175 {
3176 }
3177 
3178 ////////////////////////////////////////////////////////////////////////////////
3179 /// No op: see TClingCallbacks (used to update the list of global functions)
3180 
3182 {
3183 }
3184 
3185 ////////////////////////////////////////////////////////////////////////////////
3186 /// No op: see TClingCallbacks (used to update the list of types)
3187 
3189 {
3190 }
3191 
3192 ////////////////////////////////////////////////////////////////////////////////
3193 /// Check in what order the member of a tuple are layout.
3194 enum class ETupleOrdering {
3195  kAscending,
3196  kDescending,
3197  kUnexpected
3198 };
3199 
3200 struct AlternateTupleIntDoubleAsc
3201 {
3202  Int_t _0;
3203  Double_t _1;
3204 };
3205 
3206 struct AlternateTupleIntDoubleDes
3207 {
3208  Double_t _1;
3209  Int_t _0;
3210 };
3211 
3213 {
3214  std::tuple<int,double> value;
3215  AlternateTupleIntDoubleAsc asc;
3216  AlternateTupleIntDoubleDes des;
3217 
3218  size_t offset0 = ((char*)&(std::get<0>(value))) - ((char*)&value);
3219  size_t offset1 = ((char*)&(std::get<1>(value))) - ((char*)&value);
3220 
3221  size_t ascOffset0 = ((char*)&(asc._0)) - ((char*)&asc);
3222  size_t ascOffset1 = ((char*)&(asc._1)) - ((char*)&asc);
3223 
3224  size_t desOffset0 = ((char*)&(des._0)) - ((char*)&des);
3225  size_t desOffset1 = ((char*)&(des._1)) - ((char*)&des);
3226 
3227  if (offset0 == ascOffset0 && offset1 == ascOffset1) {
3229  } else if (offset0 == desOffset0 && offset1 == desOffset1) {
3231  } else {
3233  }
3234 }
3235 
3236 std::string AtlernateTuple(const char *classname)
3237 {
3238  TClassEdit::TSplitType tupleContent(classname);
3239  std::string alternateName = "TEmulatedTuple";
3240  alternateName.append( classname + 5 );
3241 
3242  std::string guard_name;
3243  ROOT::TMetaUtils::GetCppName(guard_name,alternateName.c_str());
3244  std::ostringstream guard;
3245  guard << "ROOT_INTERNAL_TEmulated_";
3246  guard << guard_name;
3247 
3248  std::ostringstream alternateTuple;
3249  alternateTuple << "#ifndef " << guard.str() << "\n";
3250  alternateTuple << "#define " << guard.str() << "\n";
3251  alternateTuple << "namespace ROOT { namespace Internal {\n";
3252  alternateTuple << "template <class... Types> struct TEmulatedTuple;\n";
3253  alternateTuple << "template <> struct " << alternateName << " {\n";
3254 
3255  // This could also be a compile time choice ...
3256  switch(IsTupleAscending()) {
3258  unsigned int nMember = 0;
3259  auto iter = tupleContent.fElements.begin() + 1; // Skip the template name (tuple)
3260  auto theEnd = tupleContent.fElements.end() - 1; // skip the 'stars'.
3261  while (iter != theEnd) {
3262  alternateTuple << " " << *iter << " _" << nMember << ";\n";
3263  ++iter;
3264  ++nMember;
3265  }
3266  break;
3267  }
3269  unsigned int nMember = tupleContent.fElements.size() - 3;
3270  auto iter = tupleContent.fElements.rbegin() + 1; // Skip the template name (tuple)
3271  auto theEnd = tupleContent.fElements.rend() - 1; // skip the 'stars'.
3272  while (iter != theEnd) {
3273  alternateTuple << " " << *iter << " _" << nMember << ";\n";
3274  ++iter;
3275  --nMember;
3276  }
3277  break;
3278  }
3280  Fatal("TCling::SetClassInfo::AtlernateTuple",
3281  "Layout of std::tuple on this platform is unexpected.");
3282  break;
3283  }
3284  }
3285 
3286  alternateTuple << "};\n";
3287  alternateTuple << "}}\n";
3288  alternateTuple << "#endif\n";
3289  if (!gCling->Declare(alternateTuple.str().c_str())) {
3290  Error("Load","Could not declare %s",alternateName.c_str());
3291  return "";
3292  }
3293  alternateName = "ROOT::Internal::" + alternateName;
3294  return alternateName;
3295 }
3296 
3297 ////////////////////////////////////////////////////////////////////////////////
3298 /// Set pointer to the TClingClassInfo in TClass.
3299 /// If 'reload' is true, (attempt to) generate a new ClassInfo even if we
3300 /// already have one.
3301 
3303 {
3305  if (cl->fClassInfo && !reload) {
3306  return;
3307  }
3308  //Remove the decl_id from the DeclIdToTClass map
3309  TClingClassInfo* TClinginfo = (TClingClassInfo*) cl->fClassInfo;
3310  if (TClinginfo) {
3311  TClass::RemoveClassDeclId(TClinginfo->GetDeclId());
3312  }
3313  delete TClinginfo;
3314  cl->fClassInfo = 0;
3315  std::string name(cl->GetName());
3316 
3317  // Handle the special case of 'tuple' where we ignore the real implementation
3318  // details and just overlay a 'simpler'/'simplistic' version that is easy
3319  // for the I/O to understand and handle.
3320  if (strncmp(cl->GetName(),"tuple<",strlen("tuple<"))==0) {
3321 
3322  name = AtlernateTuple(cl->GetName());
3323 
3324  }
3325 
3326  TClingClassInfo* info = new TClingClassInfo(fInterpreter, name.c_str());
3327  if (!info->IsValid()) {
3328  if (cl->fState != TClass::kHasTClassInit) {
3329  if (cl->fStreamerInfo->GetEntries() != 0) {
3330  cl->fState = TClass::kEmulated;
3331  } else {
3333  }
3334  }
3335  delete info;
3336  return;
3337  }
3338  cl->fClassInfo = (ClassInfo_t*)info; // Note: We are transferring ownership here.
3339  // In case a class contains an external enum, the enum will be seen as a
3340  // class. We must detect this special case and make the class a Zombie.
3341  // Here we assume that a class has at least one method.
3342  // We can NOT call TClass::Property from here, because this method
3343  // assumes that the TClass is well formed to do a lot of information
3344  // caching. The method SetClassInfo (i.e. here) is usually called during
3345  // the building phase of the TClass, hence it is NOT well formed yet.
3346  Bool_t zombieCandidate = kFALSE;
3347  if (
3348  info->IsValid() &&
3349  !(info->Property() & (kIsClass | kIsStruct | kIsNamespace))
3350  ) {
3351  zombieCandidate = kTRUE;
3352  }
3353  if (!info->IsLoaded()) {
3354  if (info->Property() & (kIsNamespace)) {
3355  // Namespaces can have info but no corresponding CINT dictionary
3356  // because they are auto-created if one of their contained
3357  // classes has a dictionary.
3358  zombieCandidate = kTRUE;
3359  }
3360  // this happens when no dictionary is available
3361  delete info;
3362  cl->fClassInfo = 0;
3363  }
3364  if (zombieCandidate && !cl->GetCollectionType()) {
3365  cl->MakeZombie();
3366  }
3367  // If we reach here, the info was valid (See early returns).
3368  if (cl->fState != TClass::kHasTClassInit) {
3369  if (cl->fClassInfo) {
3372  } else {
3373 // if (TClassEdit::IsSTLCont(cl->GetName()) {
3374 // There will be an emulated collection proxy, is that the same?
3375 // cl->fState = TClass::kEmulated;
3376 // } else {
3377  if (cl->fStreamerInfo->GetEntries() != 0) {
3378  cl->fState = TClass::kEmulated;
3379  } else {
3381  }
3382 // }
3383  }
3384  }
3385  if (cl->fClassInfo) {
3386  TClass::AddClassToDeclIdMap(((TClingClassInfo*)cl->fClassInfo)->GetDeclId(), cl);
3387  }
3388 }
3389 
3390 ////////////////////////////////////////////////////////////////////////////////
3391 /// Checks if an entity with the specified name is defined in Cling.
3392 /// Returns kFALSE if the entity is not defined.
3393 /// By default, structs, namespaces, classes, enums and unions are looked for.
3394 /// If the flag isClassOrNamespaceOnly is true, classes, structs and
3395 /// namespaces only are considered. I.e. if the name is an enum or a union,
3396 /// the returned value is false.
3397 ///
3398 /// In the case where the class is not loaded and belongs to a namespace
3399 /// or is nested, looking for the full class name is outputting a lots of
3400 /// (expected) error messages. Currently the only way to avoid this is to
3401 /// specifically check that each level of nesting is already loaded.
3402 /// In case of templates the idea is that everything between the outer
3403 /// '<' and '>' has to be skipped, e.g.: aap<pippo<noot>::klaas>::a_class
3404 
3405 Bool_t TCling::CheckClassInfo(const char* name, Bool_t autoload, Bool_t isClassOrNamespaceOnly /* = kFALSE*/ )
3406 {
3408  static const char *anonEnum = "anonymous enum ";
3409  static const int cmplen = strlen(anonEnum);
3410 
3411  if (0 == strncmp(name,anonEnum,cmplen)) {
3412  return kFALSE;
3413  }
3414 
3415  // Avoid the double search below in case the name is a fundamental type
3416  // or typedef to a fundamental type.
3417  THashTable *typeTable = dynamic_cast<THashTable*>( gROOT->GetListOfTypes() );
3418  TDataType *fundType = (TDataType *)typeTable->THashTable::FindObject( name );
3419 
3420  if (fundType && fundType->GetType() < TVirtualStreamerInfo::kObject
3421  && fundType->GetType() > 0) {
3422  // Fundamental type, no a class.
3423  return kFALSE;
3424  }
3425 
3426  // Migrated from within TClass::GetClass
3427  // If we want to know if a class or a namespace with this name exists in the
3428  // interpreter and this is an enum in the type system, before or after loading
3429  // according to the autoload function argument, return false.
3430  if (isClassOrNamespaceOnly &&
3431  TEnum::GetEnum(name, autoload ? TEnum::kAutoload : TEnum::kNone)) return false;
3432 
3433  const char *classname = name;
3434 
3435  int storeAutoload = SetClassAutoloading(autoload);
3436 
3437  // First we want to check whether the decl exist, but _without_
3438  // generating any template instantiation. However, the lookup
3439  // still will create a forward declaration of the class template instance
3440  // if it exist. In this case, the return value of findScope will still
3441  // be zero but the type will be initialized.
3442  // Note in the corresponding code in ROOT 5, CINT was not instantiating
3443  // this forward declaration.
3444  const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
3445  const clang::Type *type = 0;
3446  const clang::Decl *decl
3447  = lh.findScope(classname,
3448  gDebug > 5 ? cling::LookupHelper::WithDiagnostics
3449  : cling::LookupHelper::NoDiagnostics,
3450  &type, /* intantiateTemplate= */ false );
3451  if (!decl) {
3452  std::string buf = TClassEdit::InsertStd(classname);
3453  decl = lh.findScope(buf,
3454  gDebug > 5 ? cling::LookupHelper::WithDiagnostics
3455  : cling::LookupHelper::NoDiagnostics,
3456  &type,false);
3457  }
3458 
3459  if (type) {
3460  // If decl==0 and the type is valid, then we have a forward declaration.
3461  if (!decl) {
3462  // If we have a forward declaration for a class template instantiation,
3463  // we want to ignore it if it was produced/induced by the call to
3464  // findScope, however we can not distinguish those from the
3465  // instantiation induce by 'soft' use (and thus also induce by the
3466  // same underlying code paths)
3467  // ['soft' use = use not requiring a complete definition]
3468  // So to reduce the amount of disruption to the existing code we
3469  // would just ignore those for STL collection, for which we really
3470  // need to have the compiled collection proxy (and thus the TClass
3471  // bootstrap).
3472  clang::ClassTemplateSpecializationDecl *tmpltDecl =
3473  llvm::dyn_cast_or_null<clang::ClassTemplateSpecializationDecl>
3474  (type->getAsCXXRecordDecl());
3475  if (tmpltDecl && !tmpltDecl->getPointOfInstantiation().isValid()) {
3476  // Since the point of instantiation is invalid, we 'guess' that
3477  // the 'instantiation' of the forwarded type appended in
3478  // findscope.
3479  if (ROOT::TMetaUtils::IsSTLCont(*tmpltDecl)) {
3480  // For STL Collection we return false.
3481  SetClassAutoloading(storeAutoload);
3482  return kFALSE;
3483  }
3484  }
3485  }
3486  TClingClassInfo tci(fInterpreter, *type);
3487  if (!tci.IsValid()) {
3488  SetClassAutoloading(storeAutoload);
3489  return kFALSE;
3490  }
3491  auto propertiesMask = isClassOrNamespaceOnly ? kIsClass | kIsStruct | kIsNamespace :
3493 
3494  if (tci.Property() & propertiesMask) {
3495  // We are now sure that the entry is not in fact an autoload entry.
3496  SetClassAutoloading(storeAutoload);
3497  return kTRUE;
3498  }
3499  }
3500 
3501  SetClassAutoloading(storeAutoload);
3502  return (decl);
3503 
3504  // Setting up iterator part of TClingTypedefInfo is too slow.
3505  // Copy the lookup code instead:
3506  /*
3507  TClingTypedefInfo t(fInterpreter, name);
3508  if (t.IsValid() && !(t.Property() & kIsFundamental)) {
3509  delete[] classname;
3510  SetClassAutoloading(storeAutoload);
3511  return kTRUE;
3512  }
3513  */
3514 
3515 // const clang::Decl *decl = lh.findScope(name);
3516 // if (!decl) {
3517 // std::string buf = TClassEdit::InsertStd(name);
3518 // decl = lh.findScope(buf);
3519 // }
3520 
3521 // SetClassAutoloading(storeAutoload);
3522 // return (decl);
3523 }
3524 
3525 ////////////////////////////////////////////////////////////////////////////////
3526 /// Return true if there is a class template by the given name ...
3527 
3529 {
3530  const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
3531  const clang::Decl *decl
3532  = lh.findClassTemplate(name,
3533  gDebug > 5 ? cling::LookupHelper::WithDiagnostics
3534  : cling::LookupHelper::NoDiagnostics);
3535  if (!decl) {
3536  std::string strname = "std::";
3537  strname += name;
3538  decl = lh.findClassTemplate(strname,
3539  gDebug > 5 ? cling::LookupHelper::WithDiagnostics
3540  : cling::LookupHelper::NoDiagnostics);
3541  }
3542  return 0 != decl;
3543 }
3544 
3545 ////////////////////////////////////////////////////////////////////////////////
3546 /// Create list of pointers to base class(es) for TClass cl.
3547 
3549 {
3551  if (cl->fBase) {
3552  return;
3553  }
3555  if (!tci) return;
3557  TList *listOfBase = new TList;
3558  while (t.Next()) {
3559  // if name cannot be obtained no use to put in list
3560  if (t.IsValid() && t.Name()) {
3562  listOfBase->Add(new TBaseClass((BaseClassInfo_t *)a, cl));
3563  }
3564  }
3565  // Now that is complete, publish it.
3566  cl->fBase = listOfBase;
3567 }
3568 
3569 ////////////////////////////////////////////////////////////////////////////////
3570 /// Create list of pointers to enums for TClass cl.
3571 
3572 void TCling::LoadEnums(TListOfEnums& enumList) const
3573 {
3575 
3576  const Decl * D;
3577  TClass* cl = enumList.GetClass();
3578  if (cl) {
3579  D = ((TClingClassInfo*)cl->GetClassInfo())->GetDecl();
3580  }
3581  else {
3582  D = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
3583  }
3584  // Iterate on the decl of the class and get the enums.
3585  if (const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
3586  cling::Interpreter::PushTransactionRAII deserRAII(fInterpreter);
3587  // Collect all contexts of the namespace.
3588  llvm::SmallVector< DeclContext *, 4> allDeclContexts;
3589  const_cast< clang::DeclContext *>(DC)->collectAllContexts(allDeclContexts);
3590  for (llvm::SmallVector<DeclContext*, 4>::iterator declIter = allDeclContexts.begin(), declEnd = allDeclContexts.end();
3591  declIter != declEnd; ++declIter) {
3592  // Iterate on all decls for each context.
3593  for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
3594  DE = (*declIter)->decls_end(); DI != DE; ++DI) {
3595  if (const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(*DI)) {
3596  // Get name of the enum type.
3597  std::string buf;
3598  PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
3599  llvm::raw_string_ostream stream(buf);
3600  // Don't trigger fopen of the source file to count lines:
3601  Policy.AnonymousTagLocations = false;
3602  ED->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
3603  stream.flush();
3604  // If the enum is unnamed we do not add it to the list of enums i.e unusable.
3605  if (!buf.empty()) {
3606  const char* name = buf.c_str();
3607  // Add the enum to the list of loaded enums.
3608  enumList.Get(ED, name);
3609  }
3610  }
3611  }
3612  }
3613  }
3614 }
3615 
3616 ////////////////////////////////////////////////////////////////////////////////
3617 /// Create list of pointers to function templates for TClass cl.
3618 
3620 {
3622 
3623  const Decl * D;
3624  TListOfFunctionTemplates* funcTempList;
3625  if (cl) {
3626  D = ((TClingClassInfo*)cl->GetClassInfo())->GetDecl();
3627  funcTempList = (TListOfFunctionTemplates*)cl->GetListOfFunctionTemplates(false);
3628  }
3629  else {
3630  D = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
3631  funcTempList = (TListOfFunctionTemplates*)gROOT->GetListOfFunctionTemplates();
3632  }
3633  // Iterate on the decl of the class and get the enums.
3634  if (const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
3635  cling::Interpreter::PushTransactionRAII deserRAII(fInterpreter);
3636  // Collect all contexts of the namespace.
3637  llvm::SmallVector< DeclContext *, 4> allDeclContexts;
3638  const_cast< clang::DeclContext *>(DC)->collectAllContexts(allDeclContexts);
3639  for (llvm::SmallVector<DeclContext*, 4>::iterator declIter = allDeclContexts.begin(),
3640  declEnd = allDeclContexts.end(); declIter != declEnd; ++declIter) {
3641  // Iterate on all decls for each context.
3642  for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
3643  DE = (*declIter)->decls_end(); DI != DE; ++DI) {
3644  if (const clang::FunctionTemplateDecl* FTD = dyn_cast<clang::FunctionTemplateDecl>(*DI)) {
3645  funcTempList->Get(FTD);
3646  }
3647  }
3648  }
3649  }
3650 }
3651 ////////////////////////////////////////////////////////////////////////////////
3652 /// Create list of pointers to data members for TClass cl.
3653 /// This is now a nop. The creation and updating is handled in
3654 /// TListOfDataMembers.
3655 
3657 {
3658 }
3659 
3660 ////////////////////////////////////////////////////////////////////////////////
3661 /// Create list of pointers to methods for TClass cl.
3662 /// This is now a nop. The creation and updating is handled in
3663 /// TListOfFunctions.
3664 
3666 {
3667 }
3668 
3669 ////////////////////////////////////////////////////////////////////////////////
3670 /// Update the list of pointers to method for TClass cl
3671 /// This is now a nop. The creation and updating is handled in
3672 /// TListOfFunctions.
3673 
3675 {
3676 }
3677 
3678 ////////////////////////////////////////////////////////////////////////////////
3679 /// Update the list of pointers to data members for TClass cl
3680 /// This is now a nop. The creation and updating is handled in
3681 /// TListOfDataMembers.
3682 
3684 {
3685 }
3686 
3687 ////////////////////////////////////////////////////////////////////////////////
3688 /// Create list of pointers to method arguments for TMethod m.
3689 
3691 {
3693  if (m->fMethodArgs) {
3694  return;
3695  }
3696  TList *arglist = new TList;
3698  while (t.Next()) {
3699  if (t.IsValid()) {
3701  arglist->Add(new TMethodArg((MethodArgInfo_t*)a, m));
3702  }
3703  }
3704  m->fMethodArgs = arglist;
3705 }
3706 
3707 
3708 ////////////////////////////////////////////////////////////////////////////////
3709 /// Generate a TClass for the given class.
3710 /// Since the caller has already check the ClassInfo, let it give use the
3711 /// result (via the value of emulation) rather than recalculate it.
3712 
3713 TClass *TCling::GenerateTClass(const char *classname, Bool_t emulation, Bool_t silent /* = kFALSE */)
3714 {
3715 // For now the following line would lead to the (unwanted) instantiation
3716 // of class template. This could/would need to be resurrected only if
3717 // we re-introduce so sort of automatic instantiation. However this would
3718 // have to include carefull look at the template parameter to avoid
3719 // creating instance we can not really use (if the parameter are only forward
3720 // declaration or do not have all the necessary interfaces).
3721 
3722  // TClingClassInfo tci(fInterpreter, classname);
3723  // if (1 || !tci.IsValid()) {
3724 
3725  Version_t version = 1;
3726  if (TClassEdit::IsSTLCont(classname)) {
3727  version = TClass::GetClass("TVirtualStreamerInfo")->GetClassVersion();
3728  }
3729  TClass *cl = new TClass(classname, version, silent);
3730  if (emulation) {
3732  } else {
3733  // Set the class version if the class is versioned.
3734  // Note that we cannot just call CLASS::Class_Version() as we might not have
3735  // an execution engine (when invoked from rootcling).
3736 
3737  // Do not call cl->GetClassVersion(), it has side effects!
3738  Version_t oldvers = cl->fClassVersion;
3739  if (oldvers == version && cl->GetClassInfo()) {
3740  // We have a version and it might need an update.
3741  Version_t newvers = oldvers;
3743  if (llvm::isa<clang::NamespaceDecl>(cli->GetDecl())) {
3744  // Namespaces don't have class versions.
3745  return cl;
3746  }
3747  TClingMethodInfo mi = cli->GetMethod("Class_Version", "", 0 /*poffset*/,
3750  if (!mi.IsValid()) {
3751  if (cl->TestBit(TClass::kIsTObject)) {
3752  Error("GenerateTClass",
3753  "Cannot find %s::Class_Version()! Class version might be wrong.",
3754  cl->GetName());
3755  }
3756  return cl;
3757  }
3758  newvers = ROOT::TMetaUtils::GetClassVersion(llvm::dyn_cast<clang::RecordDecl>(cli->GetDecl()),
3759  *fInterpreter);
3760  if (newvers == -1) {
3761  // Didn't manage to determine the class version from the AST.
3762  // Use runtime instead.
3763  if ((mi.Property() & kIsStatic)
3764  && !fInterpreter->isInSyntaxOnlyMode()) {
3765  // This better be a static function.
3767  callfunc.SetFunc(&mi);
3768  newvers = callfunc.ExecInt(0);
3769  } else {
3770  Error("GenerateTClass",
3771  "Cannot invoke %s::Class_Version()! Class version might be wrong.",
3772  cl->GetName());
3773  }
3774  }
3775  if (newvers != oldvers) {
3776  cl->fClassVersion = newvers;
3777  cl->fStreamerInfo->Expand(newvers + 2 + 10);
3778  }
3779  }
3780  }
3781 
3782  return cl;
3783 
3784 // } else {
3785 // return GenerateTClass(&tci,silent);
3786 // }
3787 }
3788 
3789 #if 0
3790 ////////////////////////////////////////////////////////////////////////////////
3791 
3792 static void GenerateTClass_GatherInnerIncludes(cling::Interpreter *interp, TString &includes,TClingClassInfo *info)
3793 {
3794  includes += info->FileName();
3795 
3796  const clang::ClassTemplateSpecializationDecl *templateCl
3797  = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(info->GetDecl());
3798  if (templateCl) {
3799  for(unsigned int i=0; i < templateCl->getTemplateArgs().size(); ++i) {
3800  const clang::TemplateArgument &arg( templateCl->getTemplateArgs().get(i) );
3801  if (arg.getKind() == clang::TemplateArgument::Type) {
3802  const clang::Type *uType = ROOT::TMetaUtils::GetUnderlyingType( arg.getAsType() );
3803 
3804  if (!uType->isFundamentalType() && !uType->isEnumeralType()) {
3805  // We really need a header file.
3806  const clang::CXXRecordDecl *argdecl = uType->getAsCXXRecordDecl();
3807  if (argdecl) {
3808  includes += ";";
3809  TClingClassInfo subinfo(interp,*(argdecl->getASTContext().getRecordType(argdecl).getTypePtr()));
3810  GenerateTClass_GatherInnerIncludes(interp, includes, &subinfo);
3811  } else {
3812  std::string Result;
3813  llvm::raw_string_ostream OS(Result);
3814  arg.print(argdecl->getASTContext().getPrintingPolicy(),OS);
3815  Warning("TCling::GenerateTClass","Missing header file for %s",OS.str().c_str());
3816  }
3817  }
3818  }
3819  }
3820  }
3821 }
3822 #endif
3823 
3824 ////////////////////////////////////////////////////////////////////////////////
3825 /// Generate a TClass for the given class.
3826 
3827 TClass *TCling::GenerateTClass(ClassInfo_t *classinfo, Bool_t silent /* = kFALSE */)
3828 {
3829  TClingClassInfo *info = (TClingClassInfo*)classinfo;
3830  if (!info || !info->IsValid()) {
3831  Fatal("GenerateTClass","Requires a valid ClassInfo object");
3832  return 0;
3833  }
3834  // We are in the case where we have AST nodes for this class.
3835  TClass *cl = 0;
3836  std::string classname;
3837  info->FullName(classname,*fNormalizedCtxt); // Could we use Name()?
3838  if (TClassEdit::IsSTLCont(classname.c_str())) {
3839 #if 0
3840  Info("GenerateTClass","Will (try to) generate the compiled TClass for %s.",classname.c_str());
3841  // We need to build up the list of required headers, by
3842  // looking at each template arguments.
3843  TString includes;
3844  GenerateTClass_GatherInnerIncludes(fInterpreter,includes,info);
3845 
3846  if (0 == GenerateDictionary(classname.c_str(),includes)) {
3847  // 0 means success.
3848  cl = TClass::LoadClass(classnam.c_str(), silent);
3849  if (cl == 0) {
3850  Error("GenerateTClass","Even though the dictionary generation for %s seemed successful we can't find the TClass bootstrap!",classname.c_str());
3851  }
3852  }
3853 #endif
3854  if (cl == 0) {
3855  int version = TClass::GetClass("TVirtualStreamerInfo")->GetClassVersion();
3856  cl = new TClass(classinfo, version, 0, 0, -1, -1, silent);
3858  }
3859  } else {
3860  // For regular class, just create a TClass on the fly ...
3861  // Not quite useful yet, but that what CINT used to do anyway.
3862  cl = new TClass(classinfo, 1, 0, 0, -1, -1, silent);
3863  }
3864  // Add the new TClass to the map of declid and TClass*.
3865  if (cl) {
3867  }
3868  return cl;
3869 }
3870 
3871 ////////////////////////////////////////////////////////////////////////////////
3872 /// Generate the dictionary for the C++ classes listed in the first
3873 /// argument (in a semi-colon separated list).
3874 /// 'includes' contains a semi-colon separated list of file to
3875 /// #include in the dictionary.
3876 /// For example:
3877 /// ~~~ {.cpp}
3878 /// gInterpreter->GenerateDictionary("vector<vector<float> >;list<vector<float> >","list;vector");
3879 /// ~~~
3880 /// or
3881 /// ~~~ {.cpp}
3882 /// gInterpreter->GenerateDictionary("myclass","myclass.h;myhelper.h");
3883 /// ~~~
3884 
3885 Int_t TCling::GenerateDictionary(const char* classes, const char* includes /* = 0 */, const char* /* options = 0 */)
3886 {
3887  if (classes == 0 || classes[0] == 0) {
3888  return 0;
3889  }
3890  // Split the input list
3891  std::vector<std::string> listClasses;
3892  for (
3893  const char* current = classes, *prev = classes;
3894  *current != 0;
3895  ++current
3896  ) {
3897  if (*current == ';') {
3898  listClasses.push_back(std::string(prev, current - prev));
3899  prev = current + 1;
3900  }
3901  else if (*(current + 1) == 0) {
3902  listClasses.push_back(std::string(prev, current + 1 - prev));
3903  prev = current + 1;
3904  }
3905  }
3906  std::vector<std::string> listIncludes;
3907  for (
3908  const char* current = includes, *prev = includes;
3909  *current != 0;
3910  ++current
3911  ) {
3912  if (*current == ';') {
3913  listIncludes.push_back(std::string(prev, current - prev));
3914  prev = current + 1;
3915  }
3916  else if (*(current + 1) == 0) {
3917  listIncludes.push_back(std::string(prev, current + 1 - prev));
3918  prev = current + 1;
3919  }
3920  }
3921  // Generate the temporary dictionary file
3922  return TCling_GenerateDictionary(listClasses, listIncludes,
3923  std::vector<std::string>(), std::vector<std::string>());
3924 }
3925 
3926 ////////////////////////////////////////////////////////////////////////////////
3927 /// Return pointer to cling Decl of global/static variable that is located
3928 /// at the address given by addr.
3929 
3930 TInterpreter::DeclId_t TCling::GetDataMember(ClassInfo_t *opaque_cl, const char *name) const
3931 {
3933  DeclId_t d;
3934  TClingClassInfo *cl = (TClingClassInfo*)opaque_cl;
3935 
3936  if (cl) {
3937  d = cl->GetDataMember(name);
3938  // We check if the decl of the data member has an annotation which indicates
3939  // an ioname.
3940  // In case this is true, if the name requested is not the ioname, we
3941  // return 0, as if the member did not exist. In some sense we override
3942  // the information in the TClassInfo instance, isolating the typesystem in
3943  // TClass from the one in the AST.
3944  if (const ValueDecl* decl = (const ValueDecl*) d){
3945  std::string ioName;
3946  bool hasIoName = ROOT::TMetaUtils::ExtractAttrPropertyFromName(*decl,"ioname",ioName);
3947  if (hasIoName && ioName != name) return 0;
3948  }
3949  }
3950  else {
3952  d = gcl.GetDataMember(name);
3953  }
3954  return d;
3955 }
3956 
3957 ////////////////////////////////////////////////////////////////////////////////
3958 /// Return pointer to cling Decl of global/static variable that is located
3959 /// at the address given by addr.
3960 
3962 {
3964 
3965  const clang::Decl* possibleEnum = 0;
3966  // FInd the context of the decl.
3967  if (cl) {
3969  if (cci) {
3970  const clang::DeclContext* dc = 0;
3971  if (const clang::Decl* D = cci->GetDecl()) {
3972  if (!(dc = dyn_cast<clang::NamespaceDecl>(D))) {
3973  dc = dyn_cast<clang::RecordDecl>(D);
3974  }
3975  }
3976  if (dc) {
3977  // If it is a data member enum.
3978  possibleEnum = cling::utils::Lookup::Named(&fInterpreter->getSema(), name, dc);
3979  } else {
3980  Error("TCling::GetEnum", "DeclContext not found for %s .\n", name);
3981  }
3982  }
3983  } else {
3984  // If it is a global enum.
3985  possibleEnum = cling::utils::Lookup::Named(&fInterpreter->getSema(), name);
3986  }
3987  if (possibleEnum && (possibleEnum != (clang::Decl*)-1)
3988  && isa<clang::EnumDecl>(possibleEnum)) {
3989  return possibleEnum;
3990  }
3991  return 0;
3992 }
3993 
3994 ////////////////////////////////////////////////////////////////////////////////
3995 /// Return pointer to cling DeclId for a global value
3996 
3997 TInterpreter::DeclId_t TCling::GetDeclId( const llvm::GlobalValue *gv ) const
3998 {
3999  if (!gv) return 0;
4000 
4001  llvm::StringRef mangled_name = gv->getName();
4002 
4003  int err = 0;
4004  char* demangled_name_c = TClassEdit::DemangleName(mangled_name.str().c_str(), err);
4005  if (err) {
4006  if (err == -2) {
4007  // It might simply be an unmangled global name.
4008  DeclId_t d;
4010  d = gcl.GetDataMember(mangled_name.str().c_str());
4011  return d;
4012  }
4013  return 0;
4014  }
4015 
4016  std::string scopename(demangled_name_c);
4017  free(demangled_name_c);
4018 
4019  //
4020  // Separate out the class or namespace part of the
4021  // function name.
4022  //
4023  std::string dataname;
4024 
4025  if (!strncmp(scopename.c_str(), "typeinfo for ", sizeof("typeinfo for ")-1)) {
4026  scopename.erase(0, sizeof("typeinfo for ")-1);
4027  } else if (!strncmp(scopename.c_str(), "vtable for ", sizeof("vtable for ")-1)) {
4028  scopename.erase(0, sizeof("vtable for ")-1);
4029  } else {
4030  // See if it is a function
4031  std::string::size_type pos = scopename.rfind('(');
4032  if (pos != std::string::npos) {
4033  return 0;
4034  }
4035  // Separate the scope and member name
4036  pos = scopename.rfind(':');
4037  if (pos != std::string::npos) {
4038  if ((pos != 0) && (scopename[pos-1] == ':')) {
4039  dataname = scopename.substr(pos+1);
4040  scopename.erase(pos-1);
4041  }
4042  } else {
4043  scopename.clear();
4044  dataname = scopename;
4045  }
4046  }
4047  //fprintf(stderr, "name: '%s'\n", name.c_str());
4048  // Now we have the class or namespace name, so do the lookup.
4049 
4050 
4051  DeclId_t d;
4052  if (scopename.size()) {
4053  TClingClassInfo cl(fInterpreter,scopename.c_str());
4054  d = cl.GetDataMember(dataname.c_str());
4055  }
4056  else {
4058  d = gcl.GetDataMember(dataname.c_str());
4059  }
4060  return d;
4061 }
4062 
4063 ////////////////////////////////////////////////////////////////////////////////
4064 /// NOT IMPLEMENTED.
4065 
4067 {
4068  Error("GetDataMemberWithValue()", "not implemented");
4069  return 0;
4070 }
4071 
4072 ////////////////////////////////////////////////////////////////////////////////
4073 /// Return pointer to cling DeclId for a data member with a given name.
4074 
4076 {
4077  // NOT IMPLEMENTED.
4078  Error("GetDataMemberAtAddr()", "not implemented");
4079  return 0;
4080 }
4081 
4082 ////////////////////////////////////////////////////////////////////////////////
4083 /// Return the cling mangled name for a method of a class with parameters
4084 /// params (params is a string of actual arguments, not formal ones). If the
4085 /// class is 0 the global function list will be searched.
4086 
4087 TString TCling::GetMangledName(TClass* cl, const char* method,
4088  const char* params, Bool_t objectIsConst /* = kFALSE */)
4089 {
4092  if (cl) {
4093  Long_t offset;
4094  func.SetFunc((TClingClassInfo*)cl->GetClassInfo(), method, params, objectIsConst,
4095  &offset);
4096  }
4097  else {
4099  Long_t offset;
4100  func.SetFunc(&gcl, method, params, &offset);
4101  }
4103  if (!mi) return "";
4104  TString mangled_name( mi->GetMangledName() );
4105  delete mi;
4106  return mangled_name;
4107 }
4108 
4109 ////////////////////////////////////////////////////////////////////////////////
4110 /// Return the cling mangled name for a method of a class with a certain
4111 /// prototype, i.e. "char*,int,float". If the class is 0 the global function
4112 /// list will be searched.
4113 
4114 TString TCling::GetMangledNameWithPrototype(TClass* cl, const char* method,
4115  const char* proto, Bool_t objectIsConst /* = kFALSE */,
4116  EFunctionMatchMode mode /* = kConversionMatch */)
4117 {
4119  if (cl) {
4120  return ((TClingClassInfo*)cl->GetClassInfo())->
4121  GetMethod(method, proto, objectIsConst, 0 /*poffset*/, mode).GetMangledName();
4122  }
4124  return gcl.GetMethod(method, proto, objectIsConst, 0 /*poffset*/, mode).GetMangledName();
4125 }
4126 
4127 ////////////////////////////////////////////////////////////////////////////////
4128 /// Return pointer to cling interface function for a method of a class with
4129 /// parameters params (params is a string of actual arguments, not formal
4130 /// ones). If the class is 0 the global function list will be searched.
4131 
4132 void* TCling::GetInterfaceMethod(TClass* cl, const char* method,
4133  const char* params, Bool_t objectIsConst /* = kFALSE */)
4134 {
4137  if (cl) {
4138  Long_t offset;
4139  func.SetFunc((TClingClassInfo*)cl->GetClassInfo(), method, params, objectIsConst,
4140  &offset);
4141  }
4142  else {
4144  Long_t offset;
4145  func.SetFunc(&gcl, method, params, &offset);
4146  }
4147  return (void*) func.InterfaceMethod();
4148 }
4149 
4150 ////////////////////////////////////////////////////////////////////////////////
4151 /// Return pointer to cling interface function for a method of a class with
4152 /// a certain name.
4153 
4154 TInterpreter::DeclId_t TCling::GetFunction(ClassInfo_t *opaque_cl, const char* method)
4155 {
4157  DeclId_t f;
4158  TClingClassInfo *cl = (TClingClassInfo*)opaque_cl;
4159  if (cl) {
4160  f = cl->GetMethod(method).GetDeclId();
4161  }
4162  else {
4164  f = gcl.GetMethod(method).GetDeclId();
4165  }
4166  return f;
4167 
4168 }
4169 
4170 ////////////////////////////////////////////////////////////////////////////////
4171 /// Insert overloads of name in cl to res.
4172 
4173 void TCling::GetFunctionOverloads(ClassInfo_t *cl, const char *funcname,
4174  std::vector<DeclId_t>& res) const
4175 {
4176  clang::Sema& S = fInterpreter->getSema();
4177  const clang::Decl* CtxDecl
4178  = cl ? (const clang::Decl*)((TClingClassInfo*)cl)->GetDeclId():
4179  S.Context.getTranslationUnitDecl();
4180  const clang::DeclContext*
4181  DeclCtx = llvm::dyn_cast<const clang::RecordDecl>(CtxDecl);
4182  if (!DeclCtx)
4183  DeclCtx = dyn_cast<clang::NamespaceDecl>(CtxDecl);
4184  if (!DeclCtx) return;
4185  clang::DeclarationName DName
4186  = &S.Context.Idents.get(funcname);
4187  clang::LookupResult R(S, DName, clang::SourceLocation(),
4188  Sema::LookupOrdinaryName, clang::Sema::ForRedeclaration);
4189  S.LookupQualifiedName(R, const_cast<DeclContext*>(DeclCtx));
4190  if (R.empty()) return;
4191  R.resolveKind();
4192  res.reserve(res.size() + (R.end() - R.begin()));
4193  for (clang::LookupResult::iterator IR = R.begin(), ER = R.end();
4194  IR != ER; ++IR) {
4195  if (const clang::FunctionDecl* FD
4196  = llvm::dyn_cast<const clang::FunctionDecl>(*IR)) {
4197  if (!FD->getDescribedFunctionTemplate()) {
4198  res.push_back(FD);
4199  }
4200  }
4201  }
4202 }
4203 
4204 ////////////////////////////////////////////////////////////////////////////////
4205 /// Return pointer to cling interface function for a method of a class with
4206 /// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
4207 /// function list will be searched.
4208 
4209 void* TCling::GetInterfaceMethodWithPrototype(TClass* cl, const char* method,
4210  const char* proto,
4211  Bool_t objectIsConst /* = kFALSE */,
4212  EFunctionMatchMode mode /* = kConversionMatch */)
4213 {
4215  void* f;
4216  if (cl) {
4217  f = ((TClingClassInfo*)cl->GetClassInfo())->
4218  GetMethod(method, proto, objectIsConst, 0 /*poffset*/, mode).InterfaceMethod(*fNormalizedCtxt);
4219  }
4220  else {
4222  f = gcl.GetMethod(method, proto, objectIsConst, 0 /*poffset*/, mode).InterfaceMethod(*fNormalizedCtxt);
4223  }
4224  return f;
4225 }
4226 
4227 ////////////////////////////////////////////////////////////////////////////////
4228 /// Return pointer to cling DeclId for a method of a class with
4229 /// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
4230 /// function list will be searched.
4231 
4232 TInterpreter::DeclId_t TCling::GetFunctionWithValues(ClassInfo_t *opaque_cl, const char* method,
4233  const char* params,
4234  Bool_t objectIsConst /* = kFALSE */)
4235 {
4237  DeclId_t f;
4238  TClingClassInfo *cl = (TClingClassInfo*)opaque_cl;
4239  if (cl) {
4240  f = cl->GetMethodWithArgs(method, params, objectIsConst, 0 /*poffset*/).GetDeclId();
4241  }
4242  else {
4244  f = gcl.GetMethod(method, params, objectIsConst, 0 /*poffset*/).GetDeclId();
4245  }
4246  return f;
4247 }
4248 
4249 ////////////////////////////////////////////////////////////////////////////////
4250 /// Return pointer to cling interface function for a method of a class with
4251 /// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
4252 /// function list will be searched.
4253 
4254 TInterpreter::DeclId_t TCling::GetFunctionWithPrototype(ClassInfo_t *opaque_cl, const char* method,
4255  const char* proto,
4256  Bool_t objectIsConst /* = kFALSE */,
4257  EFunctionMatchMode mode /* = kConversionMatch */)
4258 {
4260  DeclId_t f;
4261  TClingClassInfo *cl = (TClingClassInfo*)opaque_cl;
4262  if (cl) {
4263  f = cl->GetMethod(method, proto, objectIsConst, 0 /*poffset*/, mode).GetDeclId();
4264  }
4265  else {
4267  f = gcl.GetMethod(method, proto, objectIsConst, 0 /*poffset*/, mode).GetDeclId();
4268  }
4269  return f;
4270 }
4271 
4272 ////////////////////////////////////////////////////////////////////////////////
4273 /// Return pointer to cling interface function for a method of a class with
4274 /// a certain name.
4275 
4276 TInterpreter::DeclId_t TCling::GetFunctionTemplate(ClassInfo_t *opaque_cl, const char* name)
4277 {
4279  DeclId_t f;
4280  TClingClassInfo *cl = (TClingClassInfo*)opaque_cl;
4281  if (cl) {
4282  f = cl->GetFunctionTemplate(name);
4283  }
4284  else {
4286  f = gcl.GetFunctionTemplate(name);
4287  }
4288  return f;
4289 
4290 }
4291 
4292 ////////////////////////////////////////////////////////////////////////////////
4293 /// The 'name' is known to the interpreter, this function returns
4294 /// the internal version of this name (usually just resolving typedefs)
4295 /// This is used in particular to synchronize between the name used
4296 /// by rootcling and by the run-time environment (TClass)
4297 /// Return 0 if the name is not known.
4298 
4299 void TCling::GetInterpreterTypeName(const char* name, std::string &output, Bool_t full)
4300 {
4301  output.clear();
4302 
4304 
4305  TClingClassInfo cl(fInterpreter, name);
4306  if (!cl.IsValid()) {
4307  return ;
4308  }
4309  if (full) {
4310  cl.FullName(output,*fNormalizedCtxt);
4311  return;
4312  }
4313  // Well well well, for backward compatibility we need to act a bit too
4314  // much like CINT.
4316  splitname.ShortType(output, TClassEdit::kDropStd );
4317 
4318  return;
4319 }
4320 
4321 ////////////////////////////////////////////////////////////////////////////////
4322 /// Execute a global function with arguments params.
4323 ///
4324 /// FIXME: The cint-based version of this code does not check if the
4325 /// SetFunc() call works, and does not do any real checking
4326 /// for errors from the Exec() call. It did fetch the most
4327 /// recent cint security error and return that in error, but
4328 /// this does not really translate well to cling/clang. We
4329 /// should enhance these interfaces so that we can report
4330 /// compilation and runtime errors properly.
4331 
4332 void TCling::Execute(const char* function, const char* params, int* error)
4333 {
4335  if (error) {
4336  *error = TInterpreter::kNoError;
4337  }
4339  Long_t offset = 0L;
4341  func.SetFunc(&cl, function, params, &offset);
4342  func.Exec(0);
4343 }
4344 
4345 ////////////////////////////////////////////////////////////////////////////////
4346 /// Execute a method from class cl with arguments params.
4347 ///
4348 /// FIXME: The cint-based version of this code does not check if the
4349 /// SetFunc() call works, and does not do any real checking
4350 /// for errors from the Exec() call. It did fetch the most
4351 /// recent cint security error and return that in error, but
4352 /// this does not really translate well to cling/clang. We
4353 /// should enhance these interfaces so that we can report
4354 /// compilation and runtime errors properly.
4355 
4356 void TCling::Execute(TObject* obj, TClass* cl, const char* method,
4357  const char* params, Bool_t objectIsConst, int* error)
4358 {
4360  if (error) {
4361  *error = TInterpreter::kNoError;
4362  }
4363  // If the actual class of this object inherits 2nd (or more) from TObject,
4364  // 'obj' is unlikely to be the start of the object (as described by IsA()),
4365  // hence gInterpreter->Execute will improperly correct the offset.
4366  void* addr = cl->DynamicCast(TObject::Class(), obj, kFALSE);
4367  Long_t offset = 0L;
4369  func.SetFunc((TClingClassInfo*)cl->GetClassInfo(), method, params, objectIsConst, &offset);
4370  void* address = (void*)((Long_t)addr + offset);
4371  func.Exec(address);
4372 }
4373 
4374 ////////////////////////////////////////////////////////////////////////////////
4375 
4376 void TCling::Execute(TObject* obj, TClass* cl, const char* method,
4377  const char* params, int* error)
4378 {
4379  Execute(obj,cl,method,params,false,error);
4380 }
4381 
4382 ////////////////////////////////////////////////////////////////////////////////
4383 /// Execute a method from class cl with the arguments in array params
4384 /// (params[0] ... params[n] = array of TObjString parameters).
4385 /// Convert the TObjArray array of TObjString parameters to a character
4386 /// string of comma separated parameters.
4387 /// The parameters of type 'char' are enclosed in double quotes and all
4388 /// internal quotes are escaped.
4389 
4390 void TCling::Execute(TObject* obj, TClass* cl, TMethod* method,
4391  TObjArray* params, int* error)
4392 {
4393  if (!method) {
4394  Error("Execute", "No method was defined");
4395  return;
4396  }
4397  TList* argList = method->GetListOfMethodArgs();
4398  // Check number of actual parameters against of expected formal ones
4399 
4400  Int_t nparms = argList->LastIndex() + 1;
4401  Int_t argc = params ? params->GetEntries() : 0;
4402 
4403  if (argc > nparms) {
4404  Error("Execute","Too many parameters to call %s, got %d but expected at most %d.",method->GetName(),argc,nparms);
4405  return;
4406  }
4407  if (nparms != argc) {
4408  // Let's see if the 'missing' argument are all defaulted.
4409  // if nparms==0 then either we stopped earlier either argc is also zero and we can't reach here.
4410  assert(nparms > 0);
4411 
4412  TMethodArg *arg = (TMethodArg *) argList->At( 0 );
4413  if (arg && arg->GetDefault() && arg->GetDefault()[0]) {
4414  // There is a default value for the first missing
4415  // argument, so we are fine.
4416  } else {
4417  Int_t firstDefault = -1;
4418  for (Int_t i = 0; i < nparms; i ++) {
4419  arg = (TMethodArg *) argList->At( i );
4420  if (arg && arg->GetDefault() && arg->GetDefault()[0]) {
4421  firstDefault = i;
4422  break;
4423  }
4424  }
4425  if (firstDefault >= 0) {
4426  Error("Execute","Too few arguments to call %s, got only %d but expected at least %d and at most %d.",method->GetName(),argc,firstDefault,nparms);
4427  } else {
4428  Error("Execute","Too few arguments to call %s, got only %d but expected %d.",method->GetName(),argc,nparms);
4429  }
4430  return;
4431  }
4432  }
4433 
4434  const char* listpar = "";
4435  TString complete(10);
4436  if (params) {
4437  // Create a character string of parameters from TObjArray
4438  TIter next(params);
4439  for (Int_t i = 0; i < argc; i ++) {
4440  TMethodArg* arg = (TMethodArg*) argList->At(i);
4442  TObjString* nxtpar = (TObjString*) next();
4443  if (i) {
4444  complete += ',';
4445  }
4446  if (strstr(type.TrueName(*fNormalizedCtxt), "char")) {
4447  TString chpar('\"');
4448  chpar += (nxtpar->String()).ReplaceAll("\"", "\\\"");
4449  // At this point we have to check if string contains \\"
4450  // and apply some more sophisticated parser. Not implemented yet!
4451  complete += chpar;
4452  complete += '\"';
4453  }
4454  else {
4455  complete += nxtpar->String();
4456  }
4457  }
4458  listpar = complete.Data();
4459  }
4460 
4461  // And now execute it.
4463  if (error) {
4464  *error = TInterpreter::kNoError;
4465  }
4466  // If the actual class of this object inherits 2nd (or more) from TObject,
4467  // 'obj' is unlikely to be the start of the object (as described by IsA()),
4468  // hence gInterpreter->Execute will improperly correct the offset.
4469  void* addr = cl->DynamicCast(TObject::Class(), obj, kFALSE);
4471  TClingMethodInfo *minfo = (TClingMethodInfo*)method->fInfo;
4472  func.Init(minfo);
4473  func.SetArgs(listpar);
4474  // Now calculate the 'this' pointer offset for the method
4475  // when starting from the class described by cl.
4476  const CXXMethodDecl * mdecl = dyn_cast<CXXMethodDecl>(minfo->GetMethodDecl());
4477  Long_t offset = ((TClingClassInfo*)cl->GetClassInfo())->GetOffset(mdecl);
4478  void* address = (void*)((Long_t)addr + offset);
4479  func.Exec(address);
4480 }
4481 
4482 ////////////////////////////////////////////////////////////////////////////////
4483 
4484 void TCling::ExecuteWithArgsAndReturn(TMethod* method, void* address,
4485  const void* args[] /*=0*/,
4486  int nargs /*=0*/,
4487  void* ret/*= 0*/) const
4488 {
4489  if (!method) {
4490  Error("ExecuteWithArgsAndReturn", "No method was defined");
4491  return;
4492  }
4493 
4494  TClingMethodInfo* minfo = (TClingMethodInfo*) method->fInfo;
4496  func.ExecWithArgsAndReturn(address, args, nargs, ret);
4497 }
4498 
4499 ////////////////////////////////////////////////////////////////////////////////
4500 /// Execute a cling macro.
4501 
4502 Long_t TCling::ExecuteMacro(const char* filename, EErrorCode* error)
4503 {
4505  fCurExecutingMacros.push_back(filename);
4506  Long_t result = TApplication::ExecuteFile(filename, (int*)error);
4507  fCurExecutingMacros.pop_back();
4508  return result;
4509 }
4510 
4511 ////////////////////////////////////////////////////////////////////////////////
4512 /// Return the file name of the current un-included interpreted file.
4513 /// See the documentation for GetCurrentMacroName().
4514 
4515 const char* TCling::GetTopLevelMacroName() const
4516 {
4517  Warning("GetTopLevelMacroName", "Must change return type!");
4518  return fCurExecutingMacros.back();
4519 }
4520 
4521 ////////////////////////////////////////////////////////////////////////////////
4522 /// Return the file name of the currently interpreted file,
4523 /// included or not. Example to illustrate the difference between
4524 /// GetCurrentMacroName() and GetTopLevelMacroName():
4525 /// ~~~ {.cpp}
4526 /// void inclfile() {
4527 /// std::cout << "In inclfile.C" << std::endl;
4528 /// std::cout << " TCling::GetCurrentMacroName() returns " <<
4529 /// TCling::GetCurrentMacroName() << std::endl;
4530 /// std::cout << " TCling::GetTopLevelMacroName() returns " <<
4531 /// TCling::GetTopLevelMacroName() << std::endl;
4532 /// }
4533 /// ~~~
4534 /// ~~~ {.cpp}
4535 /// void mymacro() {
4536 /// std::cout << "In mymacro.C" << std::endl;
4537 /// std::cout << " TCling::GetCurrentMacroName() returns " <<
4538 /// TCling::GetCurrentMacroName() << std::endl;
4539 /// std::cout << " TCling::GetTopLevelMacroName() returns " <<
4540 /// TCling::GetTopLevelMacroName() << std::endl;
4541 /// std::cout << " Now calling inclfile..." << std::endl;
4542 /// gInterpreter->ProcessLine(".x inclfile.C");;
4543 /// }
4544 /// ~~~
4545 /// Running mymacro.C will print:
4546 ///
4547 /// ~~~ {.cpp}
4548 /// root [0] .x mymacro.C
4549 /// ~~~
4550 /// In mymacro.C
4551 /// ~~~ {.cpp}
4552 /// TCling::GetCurrentMacroName() returns ./mymacro.C
4553 /// TCling::GetTopLevelMacroName() returns ./mymacro.C
4554 /// ~~~
4555 /// Now calling inclfile...
4556 /// In inclfile.h
4557 /// ~~~ {.cpp}
4558 /// TCling::GetCurrentMacroName() returns inclfile.C
4559 /// TCling::GetTopLevelMacroName() returns ./mymacro.C
4560 /// ~~~
4561 
4562 const char* TCling::GetCurrentMacroName() const
4563 {
4564 #if defined(R__MUST_REVISIT)
4565 #if R__MUST_REVISIT(6,0)
4566  Warning("GetCurrentMacroName", "Must change return type!");
4567 #endif
4568 #endif
4569  return fCurExecutingMacros.back();
4570 }
4571 
4572 ////////////////////////////////////////////////////////////////////////////////
4573 /// Return the absolute type of typeDesc.
4574 /// E.g.: typeDesc = "class TNamed**", returns "TNamed".
4575 /// You need to use the result immediately before it is being overwritten.
4576 
4577 const char* TCling::TypeName(const char* typeDesc)
4578 {
4579  TTHREAD_TLS(char*) t = 0;
4580  TTHREAD_TLS(unsigned int) tlen = 0;
4581 
4582  unsigned int dlen = strlen(typeDesc);
4583  if (dlen > tlen) {
4584  delete[] t;
4585  t = new char[dlen + 1];
4586  tlen = dlen;
4587  }
4588  const char* s, *template_start;
4589  if (!strstr(typeDesc, "(*)(")) {
4590  s = strchr(typeDesc, ' ');
4591  template_start = strchr(typeDesc, '<');
4592  if (!strcmp(typeDesc, "long long")) {
4593  strlcpy(t, typeDesc, dlen + 1);
4594  }
4595  else if (!strncmp(typeDesc, "unsigned ", s + 1 - typeDesc)) {
4596  strlcpy(t, typeDesc, dlen + 1);
4597  }
4598  // s is the position of the second 'word' (if any)
4599  // except in the case of templates where there will be a space
4600  // just before any closing '>': eg.
4601  // TObj<std::vector<UShort_t,__malloc_alloc_template<0> > >*
4602  else if (s && (template_start == 0 || (s < template_start))) {
4603  strlcpy(t, s + 1, dlen + 1);
4604  }
4605  else {
4606  strlcpy(t, typeDesc, dlen + 1);
4607  }
4608  }
4609  else {
4610  strlcpy(t, typeDesc, dlen + 1);
4611  }
4612  int l = strlen(t);
4613  while (l > 0 && (t[l - 1] == '*' || t[l - 1] == '&')) {
4614  t[--l] = 0;
4615  }
4616  return t;
4617 }
4618 
4619 ////////////////////////////////////////////////////////////////////////////////
4620 /// Read and parse a rootmapfile in its new format, and return 0 in case of
4621 /// success, -1 if the file has already been read, and -3 in case its format
4622 /// is the old one (e.g. containing "Library.ClassName")
4623 
4624 int TCling::ReadRootmapFile(const char *rootmapfile, TUniqueString *uniqueString)
4625 {
4626  // For "class ", "namespace ", "typedef ", "header ", "enum ", "var " respectively
4627  const std::map<char, unsigned int> keyLenMap = {{'c',6},{'n',10},{'t',8},{'h',7},{'e',5},{'v',4}};
4628 
4629  if (rootmapfile && *rootmapfile) {
4630 
4631  // Add content of a specific rootmap file
4632  if (fRootmapFiles->FindObject(rootmapfile)) return -1;
4633  std::ifstream file(rootmapfile);
4634  std::string line; line.reserve(200);
4635  std::string lib_name; line.reserve(100);
4636  bool newFormat=false;
4637  while (getline(file, line, '\n')) {
4638  if (!newFormat &&
4639  (strstr(line.c_str(),"Library.")!=nullptr || strstr(line.c_str(),"Declare.")!=nullptr)) {
4640  file.close();
4641  return -3; // old format
4642  }
4643  newFormat=true;
4644 
4645  if (line.compare(0, 9, "{ decls }") == 0) {
4646  // forward declarations
4647 
4648  while (getline(file, line, '\n')) {
4649  if (line[0] == '[') break;
4650  uniqueString->Append(line);
4651  }
4652  }
4653  const char firstChar=line[0];
4654  if (firstChar == '[') {
4655  // new section (library)
4656  auto brpos = line.find(']');
4657  if (brpos == string::npos) continue;
4658  lib_name = line.substr(1, brpos-1);
4659  size_t nspaces = 0;
4660  while( lib_name[nspaces] == ' ' ) ++nspaces;
4661  if (nspaces) lib_name.replace(0, nspaces, "");
4662  if (gDebug > 3) {
4663  TString lib_nameTstr(lib_name.c_str());
4664  TObjArray* tokens = lib_nameTstr.Tokenize(" ");
4665  const char* lib = ((TObjString *)tokens->At(0))->GetName();
4666  const char* wlib = gSystem->DynamicPathName(lib, kTRUE);
4667  if (wlib) {
4668  Info("ReadRootmapFile", "new section for %s", lib_nameTstr.Data());
4669  }
4670  else {
4671  Info("ReadRootmapFile", "section for %s (library does not exist)", lib_nameTstr.Data());
4672  }
4673  delete[] wlib;
4674  delete tokens;
4675  }
4676  }
4677  else {
4678  auto keyLenIt = keyLenMap.find(firstChar);
4679  if (keyLenIt == keyLenMap.end()) continue;
4680  unsigned int keyLen = keyLenIt->second;
4681  // Do not make a copy, just start after the key
4682  const char *keyname = line.c_str()+keyLen;
4683  if (gDebug > 6)
4684  Info("ReadRootmapFile", "class %s in %s", keyname, lib_name.c_str());
4685  TEnvRec* isThere = fMapfile->Lookup(keyname);
4686  if (isThere){
4687  if(lib_name != isThere->GetValue()){ // the same key for two different libs
4688  if (firstChar == 'n') {
4689  if (gDebug > 3)
4690  Info("ReadRootmapFile", "namespace %s found in %s is already in %s",
4691  keyname, lib_name.c_str(), isThere->GetValue());
4692  } else if (firstChar == 'h'){ // it is a header: add the libname to the list of libs to be loaded.
4693  lib_name+=" ";
4694  lib_name+=isThere->GetValue();
4695  fMapfile->SetValue(keyname, lib_name.c_str());
4696  }
4697  else if (!TClassEdit::IsSTLCont(keyname)) {
4698  Warning("ReadRootmapFile", "%s %s found in %s is already in %s", line.substr(0, keyLen).c_str(),
4699  keyname, lib_name.c_str(), isThere->GetValue());
4700  }
4701  } else { // the same key for the same lib
4702  if (gDebug > 3)
4703  Info("ReadRootmapFile","Key %s was already defined for %s", keyname, lib_name.c_str());
4704  }
4705 
4706  } else {
4707  fMapfile->SetValue(keyname, lib_name.c_str());
4708  }
4709  }
4710  }
4711  file.close();
4712  }
4713 
4714  return 0;
4715 }
4716 
4717 ////////////////////////////////////////////////////////////////////////////////
4718 /// Create a resource table and read the (possibly) three resource files, i.e
4719 /// $ROOTSYS/etc/system<name> (or ROOTETCDIR/system<name>), $HOME/<name> and
4720 /// ./<name>. ROOT always reads ".rootrc" (in TROOT::InitSystem()). You can
4721 /// read additional user defined resource files by creating additional TEnv
4722 /// objects. By setting the shell variable ROOTENV_NO_HOME=1 the reading of
4723 /// the $HOME/<name> resource file will be skipped. This might be useful in
4724 /// case the home directory resides on an automounted remote file system
4725 /// and one wants to avoid the file system from being mounted.
4726 
4728 {
4730 
4731  fMapfile->SetRcName(name);
4732 
4733  TString sname = "system";
4734  sname += name;
4735 #ifdef ROOTETCDIR
4736  char *s = gSystem->ConcatFileName(ROOTETCDIR, sname);
4737 #else
4738  TString etc = gRootDir;
4739 #ifdef WIN32
4740  etc += "\\etc";
4741 #else
4742  etc += "/etc";
4743 #endif
4744 #if defined(R__MACOSX) && (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)
4745  // on iOS etc does not exist and system<name> resides in $ROOTSYS
4746  etc = gRootDir;
4747 #endif
4748  char *s = gSystem->ConcatFileName(etc, sname);
4749 #endif
4750 
4751  Int_t ret = ReadRootmapFile(s);
4752  if (ret == -3) // old format
4754  delete [] s;
4755  if (!gSystem->Getenv("ROOTENV_NO_HOME")) {
4757  ret = ReadRootmapFile(s);
4758  if (ret == -3) // old format
4759  fMapfile->ReadFile(s, kEnvUser);
4760  delete [] s;
4761  if (strcmp(gSystem->HomeDirectory(), gSystem->WorkingDirectory())) {
4762  ret = ReadRootmapFile(name);
4763  if (ret == -3) // old format
4764  fMapfile->ReadFile(name, kEnvLocal);
4765  }
4766  } else {
4767  ret = ReadRootmapFile(name);
4768  if (ret == -3) // old format
4769  fMapfile->ReadFile(name, kEnvLocal);
4770  }
4771  fMapfile->IgnoreDuplicates(ignore);
4772 }
4773 
4774 
4775 namespace {
4776  using namespace clang;
4777 
4778  class ExtVisibleStorageAdder: public RecursiveASTVisitor<ExtVisibleStorageAdder>{
4779  // This class is to be considered an helper for autoloading.
4780  // It is a recursive visitor is used to inspect namespaces coming from
4781  // forward declarations in rootmaps and to set the external visible
4782  // storage flag for them.
4783  public:
4784  ExtVisibleStorageAdder(std::unordered_set<const NamespaceDecl*>& nsSet): fNSSet(nsSet) {};
4785  bool VisitNamespaceDecl(NamespaceDecl* nsDecl) {
4786  // We want to enable the external lookup for this namespace
4787  // because it may shadow the lookup of other names contained
4788  // in that namespace
4789  nsDecl->setHasExternalVisibleStorage();
4790  fNSSet.insert(nsDecl);
4791  return true;
4792  }
4793  private:
4794  std::unordered_set<const NamespaceDecl*>& fNSSet;
4795 
4796  };
4797 }
4798 
4799 ////////////////////////////////////////////////////////////////////////////////
4800 /// Load map between class and library. If rootmapfile is specified a
4801 /// specific rootmap file can be added (typically used by ACLiC).
4802 /// In case of error -1 is returned, 0 otherwise.
4803 /// The interpreter uses this information to automatically load the shared
4804 /// library for a class (autoload mechanism), see the AutoLoad() methods below.
4805 
4806 Int_t TCling::LoadLibraryMap(const char* rootmapfile)
4807 {
4809  // open the [system].rootmap files
4810  if (!fMapfile) {
4811  fMapfile = new TEnv();
4813 // fMapNamespaces = new THashTable();
4814 // fMapNamespaces->SetOwner();
4815  fRootmapFiles = new TObjArray;
4817  InitRootmapFile(".rootmap");
4818  }
4819 
4820  // Prepare a list of all forward declarations for cling
4821  // For some experiments it is easily as big as 500k characters. To be on the
4822  // safe side, we go for 1M.
4823  TUniqueString uniqueString(1048576);
4824 
4825  // Load all rootmap files in the dynamic load path ((DY)LD_LIBRARY_PATH, etc.).
4826  // A rootmap file must end with the string ".rootmap".
4827  TString ldpath = gSystem->GetDynamicPath();
4828  if (ldpath != fRootmapLoadPath) {
4829  fRootmapLoadPath = ldpath;
4830 #ifdef WIN32
4831  TObjArray* paths = ldpath.Tokenize(";");
4832 #else
4833  TObjArray* paths = ldpath.Tokenize(":");
4834 #endif
4835  TString d;
4836  for (Int_t i = 0; i < paths->GetEntriesFast(); i++) {
4837  d = ((TObjString *)paths->At(i))->GetString();
4838  // check if directory already scanned
4839  Int_t skip = 0;
4840  for (Int_t j = 0; j < i; j++) {
4841  TString pd = ((TObjString *)paths->At(j))->GetString();
4842  if (pd == d) {
4843  skip++;
4844  break;
4845  }
4846  }
4847  if (!skip) {
4848  void* dirp = gSystem->OpenDirectory(d);
4849  if (dirp) {
4850  if (gDebug > 3) {
4851  Info("LoadLibraryMap", "%s", d.Data());
4852  }
4853  const char* f1;
4854  while ((f1 = gSystem->GetDirEntry(dirp))) {
4855  TString f = f1;
4856  if (f.EndsWith(".rootmap")) {
4857  TString p;
4858  p = d + "/" + f;
4860  if (!fRootmapFiles->FindObject(f) && f != ".rootmap") {
4861  if (gDebug > 4) {
4862  Info("LoadLibraryMap", " rootmap file: %s", p.Data());
4863  }
4864  Int_t ret = ReadRootmapFile(p,&uniqueString);
4865  if (ret == 0)
4866  fRootmapFiles->Add(new TNamed(gSystem->BaseName(f), p.Data()));
4867  if (ret == -3) {
4868  // old format
4870  fRootmapFiles->Add(new TNamed(f, p));
4871  }
4872  }
4873  // else {
4874  // fprintf(stderr,"Reject %s because %s is already there\n",p.Data(),f.Data());
4875  // fRootmapFiles->FindObject(f)->ls();
4876  // }
4877  }
4878  }
4879  if (f.BeginsWith("rootmap")) {
4880  TString p;
4881  p = d + "/" + f;
4882  FileStat_t stat;
4883  if (gSystem->GetPathInfo(p, stat) == 0 && R_ISREG(stat.fMode)) {
4884  Warning("LoadLibraryMap", "please rename %s to end with \".rootmap\"", p.Data());
4885  }
4886  }
4887  }
4888  }
4889  gSystem->FreeDirectory(dirp);
4890  }
4891  }
4892  delete paths;
4893  if (!fMapfile->GetTable()->GetEntries()) {
4894  return -1;
4895  }
4896  }
4897  if (rootmapfile && *rootmapfile) {
4898  Int_t res = ReadRootmapFile(rootmapfile, &uniqueString);
4899  if (res == 0) {
4900  //TString p = gSystem->ConcatFileName(gSystem->pwd(), rootmapfile);
4901  //fRootmapFiles->Add(new TNamed(gSystem->BaseName(rootmapfile), p.Data()));
4902  fRootmapFiles->Add(new TNamed(gSystem->BaseName(rootmapfile), rootmapfile));
4903  }
4904  else if (res == -3) {
4905  // old format
4907  fMapfile->ReadFile(rootmapfile, kEnvGlobal);
4908  fRootmapFiles->Add(new TNamed(gSystem->BaseName(rootmapfile), rootmapfile));
4909  fMapfile->IgnoreDuplicates(ignore);
4910  }
4911  }
4912  TEnvRec* rec;
4913  TIter next(fMapfile->GetTable());
4914  while ((rec = (TEnvRec*) next())) {
4915  TString cls = rec->GetName();
4916  if (!strncmp(cls.Data(), "Library.", 8) && cls.Length() > 8) {
4917  // get the first lib from the list of lib and dependent libs
4918  TString libs = rec->GetValue();
4919  if (libs == "") {
4920  continue;
4921  }
4922  TString delim(" ");
4923  TObjArray* tokens = libs.Tokenize(delim);
4924  const char* lib = ((TObjString*)tokens->At(0))->GetName();
4925  // convert "@@" to "::", we used "@@" because TEnv
4926  // considers "::" a terminator
4927  cls.Remove(0, 8);
4928  cls.ReplaceAll("@@", "::");
4929  // convert "-" to " ", since class names may have
4930  // blanks and TEnv considers a blank a terminator
4931  cls.ReplaceAll("-", " ");
4932  if (gDebug > 6) {
4933  const char* wlib = gSystem->DynamicPathName(lib, kTRUE);
4934  if (wlib) {
4935  Info("LoadLibraryMap", "class %s in %s", cls.Data(), wlib);
4936  }
4937  else {
4938  Info("LoadLibraryMap", "class %s in %s (library does not exist)", cls.Data(), lib);
4939  }
4940  delete[] wlib;
4941  }
4942  // Fill in the namespace candidate list
4943 // Ssiz_t last = cls.Last(':');
4944 // if (last != kNPOS) {
4945 // // Please note that the funny op overload does substring.
4946 // TString namespaceCand = cls(0, last - 1);
4947 // // This is a reference to a substring that lives in fMapfile
4948 // if (!fMapNamespaces->FindObject(namespaceCand.Data()))
4949 // fMapNamespaces->Add(new TNamed(namespaceCand.Data(), ""));
4950 // }
4951  delete tokens;
4952  }
4953  else if (!strncmp(cls.Data(), "Declare.", 8) && cls.Length() > 8) {
4954  cls.Remove(0, 8);
4955  // convert "-" to " ", since class names may have
4956  // blanks and TEnv considers a blank a terminator
4957  cls.ReplaceAll("-", " ");
4958  fInterpreter->declare(cls.Data());
4959  }
4960  }
4961 
4962  // Process the forward declarations collected
4963  cling::Transaction* T = nullptr;
4964  auto compRes= fInterpreter->declare(uniqueString.Data(), &T);
4965  assert(cling::Interpreter::kSuccess == compRes && "A declaration in a rootmap could not be compiled");
4966 
4967  if (compRes!=cling::Interpreter::kSuccess){
4968  Warning("LoadLibraryMap",
4969  "Problems in %s declaring '%s' were encountered.", rootmapfile, uniqueString.Data()) ;
4970  }
4971 
4972  if (T){
4973  ExtVisibleStorageAdder evsAdder(fNSFromRootmaps);
4974  for (auto declIt = T->decls_begin(); declIt < T->decls_end(); ++declIt) {
4975  if (declIt->m_DGR.isSingleDecl()) {
4976  if (Decl* D = declIt->m_DGR.getSingleDecl()) {
4977  if (NamespaceDecl* NSD = dyn_cast<NamespaceDecl>(D)) {
4978  evsAdder.TraverseDecl(NSD);
4979  }
4980  }
4981  }
4982  }
4983  }
4984 
4985  // clear duplicates
4986 
4987  return 0;
4988 }
4989 
4990 ////////////////////////////////////////////////////////////////////////////////
4991 /// Scan again along the dynamic path for library maps. Entries for the loaded
4992 /// shared libraries are unloaded first. This can be useful after reseting
4993 /// the dynamic path through TSystem::SetDynamicPath()
4994 /// In case of error -1 is returned, 0 otherwise.
4995 
4997 {
4999  LoadLibraryMap();
5000  return 0;
5001 }
5002 
5003 ////////////////////////////////////////////////////////////////////////////////
5004 /// Reload the library map entries coming from all the loaded shared libraries,
5005 /// after first unloading the current ones.
5006 /// In case of error -1 is returned, 0 otherwise.
5007 
5009 {
5010  const TString sharedLibLStr = GetSharedLibs();
5011  const TObjArray* sharedLibL = sharedLibLStr.Tokenize(" ");
5012  const Int_t nrSharedLibs = sharedLibL->GetEntriesFast();
5013  for (Int_t ilib = 0; ilib < nrSharedLibs; ilib++) {
5014  const TString sharedLibStr = ((TObjString*)sharedLibL->At(ilib))->GetString();
5015  const TString sharedLibBaseStr = gSystem->BaseName(sharedLibStr);
5016  const Int_t ret = UnloadLibraryMap(sharedLibBaseStr);
5017  if (ret < 0) {
5018  continue;
5019  }
5020  TString rootMapBaseStr = sharedLibBaseStr;
5021  if (sharedLibBaseStr.EndsWith(".dll")) {
5022  rootMapBaseStr.ReplaceAll(".dll", "");
5023  }
5024  else if (sharedLibBaseStr.EndsWith(".DLL")) {
5025  rootMapBaseStr.ReplaceAll(".DLL", "");
5026  }
5027  else if (sharedLibBaseStr.EndsWith(".so")) {
5028  rootMapBaseStr.ReplaceAll(".so", "");
5029  }
5030  else if (sharedLibBaseStr.EndsWith(".sl")) {
5031  rootMapBaseStr.ReplaceAll(".sl", "");
5032  }
5033  else if (sharedLibBaseStr.EndsWith(".dl")) {
5034  rootMapBaseStr.ReplaceAll(".dl", "");
5035  }
5036  else if (sharedLibBaseStr.EndsWith(".a")) {
5037  rootMapBaseStr.ReplaceAll(".a", "");
5038  }
5039  else {
5040  Error("ReloadAllSharedLibraryMaps", "Unknown library type %s", sharedLibBaseStr.Data());
5041  delete sharedLibL;
5042  return -1;
5043  }
5044  rootMapBaseStr += ".rootmap";
5045  const char* rootMap = gSystem->Which(gSystem->GetDynamicPath(), rootMapBaseStr);
5046  if (!rootMap) {
5047  Error("ReloadAllSharedLibraryMaps", "Could not find rootmap %s in path", rootMap);
5048  delete[] rootMap;
5049  delete sharedLibL;
5050  return -1;
5051  }
5052  const Int_t status = LoadLibraryMap(rootMap);
5053  if (status < 0) {
5054  Error("ReloadAllSharedLibraryMaps", "Error loading map %s", rootMap);
5055  delete[] rootMap;
5056  delete sharedLibL;
5057  return -1;
5058  }
5059  delete[] rootMap;
5060  }
5061  delete sharedLibL;
5062  return 0;
5063 }
5064 
5065 ////////////////////////////////////////////////////////////////////////////////
5066 /// Unload the library map entries coming from all the loaded shared libraries.
5067 /// Returns 0 if succesful
5068 
5070 {
5071  const TString sharedLibLStr = GetSharedLibs();
5072  const TObjArray* sharedLibL = sharedLibLStr.Tokenize(" ");
5073  for (Int_t ilib = 0; ilib < sharedLibL->GetEntriesFast(); ilib++) {
5074  const TString sharedLibStr = ((TObjString*)sharedLibL->At(ilib))->GetString();
5075  const TString sharedLibBaseStr = gSystem->BaseName(sharedLibStr);
5076  UnloadLibraryMap(sharedLibBaseStr);
5077  }
5078  delete sharedLibL;
5079  return 0;
5080 }
5081 
5082 ////////////////////////////////////////////////////////////////////////////////
5083 /// Unload library map entries coming from the specified library.
5084 /// Returns -1 in case no entries for the specified library were found,
5085 /// 0 otherwise.
5086 
5087 Int_t TCling::UnloadLibraryMap(const char* library)
5088 {
5089  if (!fMapfile || !library || !*library) {
5090  return 0;
5091  }
5092  TString libname(library);
5093  Ssiz_t idx = libname.Last('.');
5094  if (idx != kNPOS) {
5095  libname.Remove(idx);
5096  }
5097  size_t len = libname.Length();
5098  TEnvRec *rec;
5099  TIter next(fMapfile->GetTable());
5101  Int_t ret = 0;
5102  while ((rec = (TEnvRec *) next())) {
5103  TString cls = rec->GetName();
5104  if (cls.Length() > 2) {
5105  // get the first lib from the list of lib and dependent libs
5106  TString libs = rec->GetValue();
5107  if (libs == "") {
5108  continue;
5109  }
5110  TString delim(" ");
5111  TObjArray* tokens = libs.Tokenize(delim);
5112  const char* lib = ((TObjString *)tokens->At(0))->GetName();
5113  if (!strncmp(cls.Data(), "Library.", 8) && cls.Length() > 8) {
5114  // convert "@@" to "::", we used "@@" because TEnv
5115  // considers "::" a terminator
5116  cls.Remove(0, 8);
5117  cls.ReplaceAll("@@", "::");
5118  // convert "-" to " ", since class names may have
5119  // blanks and TEnv considers a blank a terminator
5120  cls.ReplaceAll("-", " ");
5121  }
5122  if (!strncmp(lib, libname.Data(), len)) {
5123  if (fMapfile->GetTable()->Remove(rec) == 0) {
5124  Error("UnloadLibraryMap", "entry for <%s, %s> not found in library map table", cls.Data(), lib);
5125  ret = -1;
5126  }
5127  }
5128  delete tokens;
5129  }
5130  }
5131  if (ret >= 0) {
5132  TString library_rootmap(library);
5133  if (!library_rootmap.EndsWith(".rootmap"))
5134  library_rootmap.Append(".rootmap");
5135  TNamed* mfile = 0;
5136  while ((mfile = (TNamed *)fRootmapFiles->FindObject(library_rootmap))) {
5137  fRootmapFiles->Remove(mfile);
5138  delete mfile;
5139  }
5141  }
5142  return ret;
5143 }
5144 
5145 ////////////////////////////////////////////////////////////////////////////////
5146 /// Register the autoloading information for a class.
5147 /// libs is a space separated list of libraries.
5148 
5149 Int_t TCling::SetClassSharedLibs(const char *cls, const char *libs)
5150 {
5151  if (!cls || !*cls)
5152  return 0;
5153 
5154  TString key = TString("Library.") + cls;
5155  // convert "::" to "@@", we used "@@" because TEnv
5156  // considers "::" a terminator
5157  key.ReplaceAll("::", "@@");
5158  // convert "-" to " ", since class names may have
5159  // blanks and TEnv considers a blank a terminator
5160  key.ReplaceAll(" ", "-");
5161 
5163  if (!fMapfile) {
5164  fMapfile = new TEnv();
5166 // fMapNamespaces = new THashTable();
5167 // fMapNamespaces->SetOwner();
5168 
5169  fRootmapFiles = new TObjArray;
5171 
5172  InitRootmapFile(".rootmap");
5173  }
5174  //fMapfile->SetValue(key, libs);
5175  fMapfile->SetValue(cls, libs);
5176  return 1;
5177 }
5178 
5179 ////////////////////////////////////////////////////////////////////////////////
5180 /// Demangle the name (from the typeinfo) and then request the class
5181 /// via the usual name based interface (TClass::GetClass).
5182 
5183 TClass *TCling::GetClass(const std::type_info& typeinfo, Bool_t load) const
5184 {
5185  int err = 0;
5186  char* demangled_name = TClassEdit::DemangleTypeIdName(typeinfo, err);
5187  if (err) return 0;
5188  TClass* theClass = TClass::GetClass(demangled_name, load, kTRUE);
5189  free(demangled_name);
5190  return theClass;
5191 }
5192 
5193 ////////////////////////////////////////////////////////////////////////////////
5194 /// Load library containing the specified class. Returns 0 in case of error
5195 /// and 1 in case if success.
5196 
5197 Int_t TCling::AutoLoad(const std::type_info& typeinfo, Bool_t knowDictNotLoaded /* = kFALSE */)
5198 {
5199  int err = 0;
5200  char* demangled_name_c = TClassEdit::DemangleTypeIdName(typeinfo, err);
5201  if (err) {
5202  return 0;
5203  }
5204 
5205  std::string demangled_name(demangled_name_c);
5206  free(demangled_name_c);
5207 
5208  // AutoLoad expects (because TClass::GetClass already prepares it that way) a
5209  // shortened name.
5210  TClassEdit::TSplitType splitname( demangled_name.c_str(), (TClassEdit::EModType)(TClassEdit::kLong64 | TClassEdit::kDropStd) );
5211  splitname.ShortType(demangled_name, TClassEdit::kDropStlDefault | TClassEdit::kDropStd);
5212 
5213  // No need to worry about typedef, they aren't any ... but there are
5214  // inlined namespaces ...
5215 
5216  Int_t result = AutoLoad(demangled_name.c_str());
5217  if (result == 0) {
5218  demangled_name = TClassEdit::GetLong64_Name(demangled_name);
5219  result = AutoLoad(demangled_name.c_str(), knowDictNotLoaded);
5220  }
5221 
5222  return result;
5223 }
5224 
5225 ////////////////////////////////////////////////////////////////////////////////
5226 /// Load library containing the specified class. Returns 0 in case of error
5227 /// and 1 in case if success.
5228 
5229 Int_t TCling::AutoLoad(const char *cls, Bool_t knowDictNotLoaded /* = kFALSE */)
5230 {
5232 
5233  if (!knowDictNotLoaded && gClassTable->GetDictNorm(cls)) {
5234  // The library is already loaded as the class's dictionary is known.
5235  // Return success.
5236  // Note: the name (cls) is expected to be normalized as it comes either
5237  // from a callbacks (that can/should calculate the normalized name from the
5238  // decl) or from TClass::GetClass (which does also calculate the normalized
5239  // name).
5240  return 1;
5241  }
5242 
5243  if (gDebug > 2) {
5244  Info("TCling::AutoLoad",
5245  "Trying to autoload for %s", cls);
5246  }
5247 
5248  Int_t status = 0;
5249  if (!gROOT || !gInterpreter || gROOT->TestBit(TObject::kInvalidObject)) {
5250  if (gDebug > 2) {
5251  Info("TCling::AutoLoad",
5252  "Disabled due to gROOT or gInterpreter being invalid/not ready (the class name is %s)", cls);
5253  }
5254  return status;
5255  }
5256  if (!fAllowLibLoad) {
5257  // Never load any library from rootcling/genreflex.
5258  if (gDebug > 2) {
5259  Info("TCling::AutoLoad",
5260  "Explicitly disabled (the class name is %s)", cls);
5261  }
5262  return 0;
5263  }
5264  // Prevent the recursion when the library dictionary are loaded.
5265  Int_t oldvalue = SetClassAutoloading(false);
5266  // Try using externally provided callback first.
5267  if (fAutoLoadCallBack) {
5268  int success = (*(AutoLoadCallBack_t)fAutoLoadCallBack)(cls);
5269  if (success) {
5270  SetClassAutoloading(oldvalue);
5271  return success;
5272  }
5273  }
5274  // lookup class to find list of dependent libraries
5275  TString deplibs = GetClassSharedLibs(cls);
5276  if (!deplibs.IsNull()) {
5277  TString delim(" ");
5278  TObjArray* tokens = deplibs.Tokenize(delim);
5279  for (Int_t i = (tokens->GetEntriesFast() - 1); i > 0; --i) {
5280  const char* deplib = ((TObjString*)tokens->At(i))->GetName();
5281  if (gROOT->LoadClass(cls, deplib) == 0) {
5282  if (gDebug > 0) {
5283  Info("TCling::AutoLoad",
5284  "loaded dependent library %s for %s", deplib, cls);
5285  }
5286  }
5287  else {
5288  Error("TCling::AutoLoad",
5289  "failure loading dependent library %s for %s",
5290  deplib, cls);
5291  }
5292  }
5293  const char* lib = ((TObjString*)tokens->At(0))->GetName();
5294  if (lib && lib[0]) {
5295  if (gROOT->LoadClass(cls, lib) == 0) {
5296  if (gDebug > 0) {
5297  Info("TCling::AutoLoad",
5298  "loaded library %s for %s", lib, cls);
5299  }
5300  status = 1;
5301  }
5302  else {
5303  Error("TCling::AutoLoad",
5304  "failure loading library %s for %s", lib, cls);
5305  }
5306  }
5307  delete tokens;
5308  }
5309 
5310  SetClassAutoloading(oldvalue);
5311  return status;
5312 }
5313 
5314 ////////////////////////////////////////////////////////////////////////////////
5315 /// Parse the payload or header.
5316 
5317 static cling::Interpreter::CompilationResult ExecAutoParse(const char *what,
5318  Bool_t header,
5319  cling::Interpreter *interpreter)
5320 {
5321  std::string code = gNonInterpreterClassDef ;
5322  if (!header) {
5323  // This is the complete header file content and not the
5324  // name of a header.
5325  code += what;
5326 
5327  } else {
5328  code += ("#include \"");
5329  code += what;
5330  code += "\"\n";
5331  }
5332  code += ("#ifdef __ROOTCLING__\n"
5333  "#undef __ROOTCLING__\n"
5334  + gInterpreterClassDef +
5335  "#endif");
5336 
5337  cling::Interpreter::CompilationResult cr;
5338  {
5339  // scope within which diagnostics are de-activated
5340  // For now we disable diagnostics because we saw them already at
5341  // dictionary generation time. That won't be an issue with the PCMs.
5342 
5343  Sema &SemaR = interpreter->getSema();
5344  ROOT::Internal::ParsingStateRAII parsingStateRAII(interpreter->getParser(), SemaR);
5345  clangDiagSuppr diagSuppr(SemaR.getDiagnostics());
5346 
5347  #if defined(R__MUST_REVISIT)
5348  #if R__MUST_REVISIT(6,2)
5349  Warning("TCling::RegisterModule","Diagnostics suppression should be gone by now.");
5350  #endif
5351  #endif
5352 
5353  cr = interpreter->parseForModule(code);
5354  }
5355  return cr;
5356 }
5357 
5358 ////////////////////////////////////////////////////////////////////////////////
5359 /// Helper routine for TCling::AutoParse implementing the actual call to the
5360 /// parser and looping over template parameters (if
5361 /// any) and when they don't have a registered header to autoparse,
5362 /// recurse over their template parameters.
5363 ///
5364 /// Returns the number of header parsed.
5365 
5366 UInt_t TCling::AutoParseImplRecurse(const char *cls, bool topLevel)
5367 {
5368  // We assume the lock has already been taken.
5369  // R__LOCKGUARD(gInterpreterMutex);
5370 
5371  Int_t nHheadersParsed = 0;
5372 
5373  // Loop on the possible autoparse keys
5374  bool skipFirstEntry = false;
5375  std::vector<std::string> autoparseKeys;
5376  if (strchr(cls, '<')) {
5377  int nestedLoc = 0;
5378  TClassEdit::GetSplit(cls, autoparseKeys, nestedLoc, TClassEdit::kDropTrailStar);
5379  // Check if we can skip the name of the template in the autoparses
5380  // Take all the scopes one by one. If all of them are in the AST, we do not
5381  // need to autoparse for that particular template.
5382  if (!autoparseKeys.empty()){
5383  TString templateName(autoparseKeys[0]);
5384  auto tokens = templateName.Tokenize("::");
5385  clang::NamedDecl* previousScopeAsNamedDecl = nullptr;
5386  clang::DeclContext* previousScopeAsContext = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
5387  if (TClassEdit::IsStdClass(cls))
5388  previousScopeAsContext = fInterpreter->getSema().getStdNamespace();
5389  for (auto const scopeObj : *tokens){
5390  auto scopeName = ((TObjString*) scopeObj)->String().Data();
5391  previousScopeAsNamedDecl = cling::utils::Lookup::Named(&fInterpreter->getSema(), scopeName, previousScopeAsContext);
5392  // Check if we have multiple nodes in the AST with this name
5393  if ((clang::NamedDecl*)-1 == previousScopeAsNamedDecl) break;
5394  previousScopeAsContext = llvm::dyn_cast_or_null<clang::DeclContext>(previousScopeAsNamedDecl);
5395  if (!previousScopeAsContext) break; // this is not a context
5396  }
5397  delete tokens;
5398  // Now, let's check if the last scope, the template, has a definition, i.e. it's not a fwd decl
5399  if ((clang::NamedDecl*)-1 != previousScopeAsNamedDecl) {
5400  if (auto templateDecl = llvm::dyn_cast_or_null<clang::ClassTemplateDecl>(previousScopeAsNamedDecl)) {
5401  if (auto templatedDecl = templateDecl->getTemplatedDecl()) {
5402  skipFirstEntry = nullptr != templatedDecl->getDefinition();
5403  }
5404  }
5405  }
5406 
5407  }
5408  }
5409  if (topLevel) autoparseKeys.emplace_back(cls);
5410 
5411  for (const auto & apKeyStr : autoparseKeys) {
5412  if (skipFirstEntry) {
5413  skipFirstEntry=false;
5414  continue;
5415  }
5416  if (apKeyStr.empty()) continue;
5417  const char *apKey = apKeyStr.c_str();
5418  std::size_t normNameHash(fStringHashFunction(apKey));
5419  // If the class was not looked up
5420  if (gDebug > 1) {
5421  Info("TCling::AutoParse",
5422  "Starting autoparse for %s\n", apKey);
5423  }
5424  if (fLookedUpClasses.insert(normNameHash).second) {
5425  auto const &iter = fClassesHeadersMap.find(normNameHash);
5426  if (iter != fClassesHeadersMap.end()) {
5427  const cling::Transaction *T = fInterpreter->getCurrentTransaction();
5428  fTransactionHeadersMap.insert({T,normNameHash});
5429  auto const &hNamesPtrs = iter->second;
5430  if (gDebug > 1) {
5431  Info("TCling::AutoParse",
5432  "We can proceed for %s. We have %s headers.", apKey, std::to_string(hNamesPtrs.size()).c_str());
5433  }
5434  for (auto & hName : hNamesPtrs) {
5435  if (fParsedPayloadsAddresses.count(hName) == 1) continue;
5436  if (0 != fPayloads.count(normNameHash)) {
5437  float initRSSval=0.f, initVSIZEval=0.f;
5438  (void) initRSSval; // Avoid unused var warning
5439  (void) initVSIZEval;
5440  if (gDebug > 0) {
5441  Info("AutoParse",
5442  "Parsing full payload for %s", apKey);
5443  ProcInfo_t info;
5444  gSystem->GetProcInfo(&info);
5445  initRSSval = 1e-3*info.fMemResident;
5446  initVSIZEval = 1e-3*info.fMemVirtual;
5447  }
5448  auto cRes = ExecAutoParse(hName, kFALSE, fInterpreter);
5449  if (cRes != cling::Interpreter::kSuccess) {
5450  if (hName[0] == '\n')
5451  Error("AutoParse", "Error parsing payload code for class %s with content:\n%s", apKey, hName);
5452  } else {
5453  fParsedPayloadsAddresses.insert(hName);
5454  nHheadersParsed++;
5455  if (gDebug > 0){
5456  ProcInfo_t info;
5457  gSystem->GetProcInfo(&info);
5458  float endRSSval = 1e-3*info.fMemResident;
5459  float endVSIZEval = 1e-3*info.fMemVirtual;
5460  Info("Autoparse", ">>> RSS key %s - before %.3f MB - after %.3f MB - delta %.3f MB", apKey, initRSSval, endRSSval, endRSSval-initRSSval);
5461  Info("Autoparse", ">>> VSIZE key %s - before %.3f MB - after %.3f MB - delta %.3f MB", apKey, initVSIZEval, endVSIZEval, endVSIZEval-initVSIZEval);
5462  }
5463  }
5464  } else if (!IsLoaded(hName)) {
5465  if (gDebug > 0) {
5466  Info("AutoParse",
5467  "Parsing single header %s", hName);
5468  }
5469  auto cRes = ExecAutoParse(hName, kTRUE, fInterpreter);
5470  if (cRes != cling::Interpreter::kSuccess) {
5471  Error("AutoParse", "Error parsing headerfile %s for class %s.", hName, apKey);
5472  } else {
5473  nHheadersParsed++;
5474  }
5475  }
5476  }
5477  }
5478  else {
5479  // There is no header registered for this class, if this a
5480  // template, it will be instantiated if/when it is requested
5481  // and if we do no load/parse its components we might end up
5482  // not using an eventual specialization.
5483  if (strchr(apKey, '<')) {
5484  nHheadersParsed += AutoParseImplRecurse(apKey, false);
5485  }
5486  }
5487  }
5488  }
5489 
5490  return nHheadersParsed;
5491 
5492 }
5493 
5494 ////////////////////////////////////////////////////////////////////////////////
5495 /// Parse the headers relative to the class
5496 /// Returns 1 in case of success, 0 in case of failure
5497 
5498 Int_t TCling::AutoParse(const char *cls)
5499 {
5501 
5504  return AutoLoad(cls);
5505  } else {
5506  return 0;
5507  }
5508  }
5509 
5510  if (gDebug > 1) {
5511  Info("TCling::AutoParse",
5512  "Trying to autoparse for %s", cls);
5513  }
5514 
5515  // The catalogue of headers is in the dictionary
5517  && !gClassTable->GetDictNorm(cls)) {
5518  // Need RAII against recursive (dictionary payload) parsing (ROOT-8445).
5519  ROOT::Internal::ParsingStateRAII parsingStateRAII(fInterpreter->getParser(),
5520  fInterpreter->getSema());
5521  AutoLoad(cls, true /*knowDictNotLoaded*/);
5522  }
5523 
5524  // Prevent the recursion when the library dictionary are loaded.
5525  Int_t oldAutoloadValue = SetClassAutoloading(false);
5526 
5527  // No recursive header parsing on demand; we require headers to be standalone.
5528  SuspendAutoParsing autoParseRAII(this);
5529 
5530  Int_t nHheadersParsed = AutoParseImplRecurse(cls,/*topLevel=*/ true);
5531 
5532  if (nHheadersParsed != 0) {
5533  while (!fClassesToUpdate.empty()) {
5534  TClass *oldcl = fClassesToUpdate.back().first;
5535  if (oldcl->GetState() != TClass::kHasTClassInit) {
5536  // if (gDebug > 2) Info("RegisterModule", "Forcing TClass init for %s", oldcl->GetName());
5537  DictFuncPtr_t dict = fClassesToUpdate.back().second;
5538  fClassesToUpdate.pop_back();
5539  // Calling func could manipulate the list so, let maintain the list
5540  // then call the dictionary function.
5541  TClass *ncl = dict();
5542  if (ncl) ncl->PostLoadCheck();
5543  } else {
5544  fClassesToUpdate.pop_back();
5545  }
5546  }
5547  }
5548 
5549  SetClassAutoloading(oldAutoloadValue);
5550 
5551  return nHheadersParsed > 0 ? 1 : 0;
5552 }
5553 
5554 
5555 ////////////////////////////////////////////////////////////////////////////////
5556 /// Autoload a library based on a missing symbol.
5557 
5558 void* TCling::LazyFunctionCreatorAutoload(const std::string& mangled_name) {
5559  // First see whether the symbol is in the library that we are currently
5560  // loading. It will have access to the symbols of its dependent libraries,
5561  // thus checking "back()" is sufficient.
5562  if (!fRegisterModuleDyLibs.empty()) {
5563  if (void* addr = dlsym(fRegisterModuleDyLibs.back(),
5564  mangled_name.c_str())) {
5565  return addr;
5566  }
5567  }
5568 
5569  int err = 0;
5570  char* demangled_name_c = TClassEdit::DemangleName(mangled_name.c_str(), err);
5571  if (err) {
5572  return 0;
5573  }
5574 
5575  std::string name(demangled_name_c);
5576  free(demangled_name_c);
5577 
5578  //fprintf(stderr, "demangled name: '%s'\n", demangled_name);
5579  //
5580  // Separate out the class or namespace part of the
5581  // function name.
5582  //
5583 
5584  if (!strncmp(name.c_str(), "typeinfo for ", sizeof("typeinfo for ")-1)) {
5585  name.erase(0, sizeof("typeinfo for ")-1);
5586  } else if (!strncmp(name.c_str(), "vtable for ", sizeof("vtable for ")-1)) {
5587  name.erase(0, sizeof("vtable for ")-1);
5588  } else if (!strncmp(name.c_str(), "operator", sizeof("operator")-1)
5589  && !isalnum(name[sizeof("operator")])) {
5590  // operator...(A, B) - let's try with A!
5591  name.erase(0, sizeof("operator")-1);
5592  std::string::size_type pos = name.rfind('(');
5593  if (pos != std::string::npos) {
5594  name.erase(0, pos + 1);
5595  pos = name.find(",");
5596  if (pos != std::string::npos) {
5597  // remove next arg up to end, leaving only the first argument type.
5598  name.erase(pos);
5599  }
5600  pos = name.rfind(" const");
5601  if (pos != std::string::npos) {
5602  name.erase(pos, strlen(" const"));
5603  }
5604  while (!name.empty() && strchr("&*", name.back()))
5605  name.erase(name.length() - 1);
5606  }
5607  } else {
5608  // Remove the function arguments.
5609  std::string::size_type pos = name.rfind('(');
5610  if (pos != std::string::npos) {
5611  name.erase(pos);
5612  }
5613  // Remove the function name.
5614  pos = name.rfind(':');
5615  if (pos != std::string::npos) {
5616  if ((pos != 0) && (name[pos-1] == ':')) {
5617  name.erase(pos-1);
5618  }
5619  }
5620  }
5621  //fprintf(stderr, "name: '%s'\n", name.c_str());
5622  // Now we have the class or namespace name, so do the lookup.
5623  TString libs = GetClassSharedLibs(name.c_str());
5624  if (libs.IsNull()) {
5625  // Not found in the map, all done.
5626  return 0;
5627  }
5628  //fprintf(stderr, "library: %s\n", iter->second.c_str());
5629  // Now we have the name of the libraries to load, so load them.
5630 
5631  TString lib;
5632  Ssiz_t posLib = 0;
5633  while (libs.Tokenize(lib, posLib)) {
5634  if (gSystem->Load(lib, "", kFALSE /*system*/) < 0) {
5635  // The library load failed, all done.
5636  //fprintf(stderr, "load failed: %s\n", errmsg.c_str());
5637  return 0;
5638  }
5639  }
5640 
5641  //fprintf(stderr, "load succeeded.\n");
5642  // Get the address of the function being called.
5643  void* addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(mangled_name.c_str());
5644  //fprintf(stderr, "addr: %016lx\n", reinterpret_cast<unsigned long>(addr));
5645  return addr;
5646 }
5647 
5648 ////////////////////////////////////////////////////////////////////////////////
5649 
5651 {
5652 // if (fMapNamespaces){
5653 // return fMapNamespaces->FindObject(name);
5654 // }
5655  return false;
5656 }
5657 
5658 ////////////////////////////////////////////////////////////////////////////////
5659 
5660 Bool_t TCling::IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl* nsDecl)
5661 {
5662  return fNSFromRootmaps.count(nsDecl) != 0;
5663 }
5664 
5665 ////////////////////////////////////////////////////////////////////////////////
5666 /// Internal function. Inform a TClass about its new TagDecl or NamespaceDecl.
5667 
5668 void TCling::UpdateClassInfoWithDecl(const void* vTD)
5669 {
5670  const NamedDecl* ND = static_cast<const NamedDecl*>(vTD);
5671  const TagDecl* td = dyn_cast<TagDecl>(ND);
5672  std::string name;
5673  TagDecl* tdDef = 0;
5674  if (td) {
5675  tdDef = td->getDefinition();
5676  // Let's pass the decl to the TClass only if it has a definition.
5677  if (!tdDef) return;
5678  td = tdDef;
5679  ND = td;
5680 
5681  if (llvm::isa<clang::FunctionDecl>(td->getDeclContext())) {
5682  // Ignore declaration within a function.
5683  return;
5684  }
5685  clang::QualType type( td->getTypeForDecl(), 0 );
5686 
5687  auto declName=ND->getNameAsString();
5688  if (!TClass::HasNoInfoOrEmuOrFwdDeclaredDecl(declName.c_str())){
5689 // printf ("Impossible to find a TClassEntry in kNoInfo or kEmulated the decl of which would be called %s. Skip w/o building the normalized name.\n",declName );
5690  return;
5691  }
5692 
5694  } else {
5695  name = ND->getNameAsString();
5696  }
5697 
5698  // Supposedly we are being called while something is being
5699  // loaded ... let's now tell the autoloader to do the work
5700  // yet another time.
5701  int storedAutoloading = SetClassAutoloading(false);
5702  // FIXME: There can be more than one TClass for a single decl.
5703  // for example vector<double> and vector<Double32_t>
5704  TClass* cl = (TClass*)gROOT->GetListOfClasses()->FindObject(name.c_str());
5705  if (cl && GetModTClasses().find(cl) == GetModTClasses().end()) {
5707  if (cci) {
5708  // If we only had a forward declaration then update the
5709  // TClingClassInfo with the definition if we have it now.
5710  const TagDecl* tdOld = llvm::dyn_cast_or_null<TagDecl>(cci->GetDecl());
5711  if (!tdOld || (tdDef && tdDef != tdOld)) {
5712  cl->ResetCaches();
5714  if (td) {
5715  // It's a tag decl, not a namespace decl.
5716  cci->Init(*cci->GetType());
5718  }
5719  }
5720  } else if (!cl->TestBit(TClass::kLoading) && !cl->fHasRootPcmInfo) {
5721  cl->ResetCaches();
5722  // yes, this is almost a waste of time, but we do need to lookup
5723  // the 'type' corresponding to the TClass anyway in order to
5724  // preserve the opaque typedefs (Double32_t)
5725  cl->fClassInfo = (ClassInfo_t *)new TClingClassInfo(fInterpreter, cl->GetName());
5726  // We now need to update the state and bits.
5727  if (cl->fState != TClass::kHasTClassInit) {
5728  // if (!cl->fClassInfo->IsValid()) cl->fState = TClass::kForwardDeclared; else
5731  }
5732  TClass::AddClassToDeclIdMap(((TClingClassInfo*)(cl->fClassInfo))->GetDeclId(), cl);
5733  }
5734  }
5735  SetClassAutoloading(storedAutoloading);
5736 }
5737 
5738 ////////////////////////////////////////////////////////////////////////////////
5739 /// No op: see TClingCallbacks
5740 
5741 void TCling::UpdateClassInfo(char* item, Long_t tagnum)
5742 {
5743 }
5744 
5745 //______________________________________________________________________________
5746 //FIXME: Factor out that function in TClass, because TClass does it already twice
5747 void TCling::UpdateClassInfoWork(const char* item)
5748 {
5749  // This is a no-op as part of the API.
5750  // TCling uses UpdateClassInfoWithDecl() instead.
5751 }
5752 
5753 ////////////////////////////////////////////////////////////////////////////////
5754 /// Update all canvases at end the terminal input command.
5755 
5757 {
5758  TIter next(gROOT->GetListOfCanvases());
5759  TVirtualPad* canvas;
5760  while ((canvas = (TVirtualPad*)next())) {
5761  canvas->Update();
5762  }
5763 }
5764 
5765 ////////////////////////////////////////////////////////////////////////////////
5766 
5767 void TCling::UpdateListsOnCommitted(const cling::Transaction &T) {
5768  std::set<TClass*> modifiedTClasses; // TClasses that require update after this transaction
5769 
5770  // If the transaction does not contain anything we can return earlier.
5771  if (!HandleNewTransaction(T)) return;
5772 
5773  bool isTUTransaction = false;
5774  if (!T.empty() && T.decls_begin() + 1 == T.decls_end() && !T.hasNestedTransactions()) {
5775  clang::Decl* FirstDecl = *(T.decls_begin()->m_DGR.begin());
5776  if (llvm::isa<clang::TranslationUnitDecl>(FirstDecl)) {
5777  // The is the first transaction, we have to expose to meta
5778  // what's already in the AST.
5779  isTUTransaction = true;
5780  }
5781  }
5782 
5783  std::set<const void*> TransactionDeclSet;
5784  if (!isTUTransaction && T.decls_end() - T.decls_begin()) {
5785  const clang::Decl* WrapperFD = T.getWrapperFD();
5786  for (cling::Transaction::const_iterator I = T.decls_begin(), E = T.decls_end();
5787  I != E; ++I) {
5788  if (I->m_Call != cling::Transaction::kCCIHandleTopLevelDecl
5789  && I->m_Call != cling::Transaction::kCCIHandleTagDeclDefinition)
5790  continue;
5791 
5792  for (DeclGroupRef::const_iterator DI = I->m_DGR.begin(),
5793  DE = I->m_DGR.end(); DI != DE; ++DI) {
5794  if (*DI == WrapperFD)
5795  continue;
5796  TransactionDeclSet.insert(*DI);
5797  ((TCling*)gCling)->HandleNewDecl(*DI, false, modifiedTClasses);
5798  }
5799  }
5800  }
5801 
5802  // The above might trigger more decls to be deserialized.
5803  // Thus the iteration over the deserialized decls must be last.
5804  for (cling::Transaction::const_iterator I = T.deserialized_decls_begin(),
5805  E = T.deserialized_decls_end(); I != E; ++I) {
5806  for (DeclGroupRef::const_iterator DI = I->m_DGR.begin(),
5807  DE = I->m_DGR.end(); DI != DE; ++DI)
5808  if (TransactionDeclSet.find(*DI) == TransactionDeclSet.end()) {
5809  //FIXME: HandleNewDecl should take DeclGroupRef
5810  ((TCling*)gCling)->HandleNewDecl(*DI, /*isDeserialized*/true,
5811  modifiedTClasses);
5812  }
5813  }
5814 
5815 
5816  // When fully building the reflection info in TClass, a deserialization
5817  // could be triggered, which may result in request for building the
5818  // reflection info for the same TClass. This in turn will clear the caches
5819  // for the TClass in-flight and cause null ptr derefs.
5820  // FIXME: This is a quick fix, solving most of the issues. The actual
5821  // question is: Shouldn't TClass provide a lock mechanism on update or lock
5822  // itself until the update is done.
5823  //
5824  std::vector<TClass*> modifiedTClassesDiff(modifiedTClasses.size());
5825  std::vector<TClass*>::iterator it;
5826  it = set_difference(modifiedTClasses.begin(), modifiedTClasses.end(),
5827  ((TCling*)gCling)->GetModTClasses().begin(),
5828  ((TCling*)gCling)->GetModTClasses().end(),
5829  modifiedTClassesDiff.begin());
5830  modifiedTClassesDiff.resize(it - modifiedTClassesDiff.begin());
5831 
5832  // Lock the TClass for updates
5833  ((TCling*)gCling)->GetModTClasses().insert(modifiedTClassesDiff.begin(),
5834  modifiedTClassesDiff.end());
5835  for (std::vector<TClass*>::const_iterator I = modifiedTClassesDiff.begin(),
5836  E = modifiedTClassesDiff.end(); I != E; ++I) {
5837  // Make sure the TClass has not been deleted.
5838  if (!gROOT->GetListOfClasses()->FindObject(*I)) {
5839  continue;
5840  }
5841  // Could trigger deserialization of decls.
5842  cling::Interpreter::PushTransactionRAII RAII(fInterpreter);
5843  // Unlock the TClass for updates
5844  ((TCling*)gCling)->GetModTClasses().erase(*I);
5845 
5846  }
5847 }
5848 
5849 ////////////////////////////////////////////////////////////////////////////////
5850 /// Helper function to go through the members of a class or namespace and unload them.
5851 
5852 void TCling::UnloadClassMembers(TClass* cl, const clang::DeclContext* DC) {
5853 
5854  TDataMember* var = 0;
5855  TFunction* function = 0;
5856  TEnum* e = 0;
5857  TFunctionTemplate* functiontemplate = 0;
5859  TListOfFunctions* functions = (TListOfFunctions*)cl->GetListOfMethods();
5860  TListOfEnums* enums = (TListOfEnums*)cl->GetListOfEnums();
5862  for (DeclContext::decl_iterator RI = DC->decls_begin(), RE = DC->decls_end(); RI != RE; ++RI) {
5863  if (isa<VarDecl>(*RI) || isa<FieldDecl>(*RI)) {
5864  const clang::ValueDecl* VD = dyn_cast<ValueDecl>(*RI);
5865  var = (TDataMember*)datamembers->FindObject(VD->getNameAsString().c_str());
5866  if (var) {
5867  // Unload the global by setting the DataMemberInfo_t to 0
5868  datamembers->Unload(var);
5869  var->Update(0);
5870  }
5871  } else if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(*RI)) {
5872  function = (TFunction*)functions->FindObject(FD->getNameAsString().c_str());
5873  if (function) {
5874  functions->Unload(function);
5875  function->Update(0);
5876  }
5877  } else if (const EnumDecl* ED = dyn_cast<EnumDecl>(*RI)) {
5878  e = (TEnum*)enums->FindObject(ED->getNameAsString().c_str());
5879  if (e) {
5880  TIter iEnumConst(e->GetConstants());
5881  while (TEnumConstant* enumConst = (TEnumConstant*)iEnumConst()) {
5882  // Since the enum is already created and valid that ensures us that
5883  // we have the enum constants created as well.
5884  enumConst = (TEnumConstant*)datamembers->FindObject(enumConst->GetName());
5885  if (enumConst && enumConst->IsValid()) {
5886  datamembers->Unload(enumConst);
5887  enumConst->Update(0);
5888  }
5889  }
5890  enums->Unload(e);
5891  e->Update(0);
5892  }
5893  } else if (const FunctionTemplateDecl* FTD = dyn_cast<FunctionTemplateDecl>(*RI)) {
5894  functiontemplate = (TFunctionTemplate*)functiontemplates->FindObject(FTD->getNameAsString().c_str());
5895  if (functiontemplate) {
5896  functiontemplates->Unload(functiontemplate);
5897  functiontemplate->Update(0);
5898  }
5899  }
5900  }
5901 }
5902 
5903 ////////////////////////////////////////////////////////////////////////////////
5904 
5905 void TCling::UpdateListsOnUnloaded(const cling::Transaction &T)
5906 {
5908 
5909  // Unload the objects from the lists and update the objects' state.
5910  TListOfFunctions* functions = (TListOfFunctions*)gROOT->GetListOfGlobalFunctions();
5911  TListOfFunctionTemplates* functiontemplates = (TListOfFunctionTemplates*)gROOT->GetListOfFunctionTemplates();
5912  TListOfEnums* enums = (TListOfEnums*)gROOT->GetListOfEnums();
5913  TListOfDataMembers* globals = (TListOfDataMembers*)gROOT->GetListOfGlobals();
5914  cling::Transaction::const_nested_iterator iNested = T.nested_begin();
5915  for(cling::Transaction::const_iterator I = T.decls_begin(), E = T.decls_end();
5916  I != E; ++I) {
5917  if (I->m_Call == cling::Transaction::kCCIHandleVTable)
5918  continue;