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