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